/* Generate the UUID for a UPnPdevice */ void upnp_gen_uuid(char *uuid, char *deviceType) { unsigned char new_uuid[16]; unsigned char mac[6]; md5_ctx_t mdContext; upnp_osl_primary_lanmac((char *)mac); /* Generate hash */ md5_begin(&mdContext); md5_hash(mac, sizeof(mac),&mdContext); md5_hash((unsigned char *)deviceType, strlen(deviceType),&mdContext); md5_end(new_uuid, &mdContext); sprintf(uuid, "%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", new_uuid[0], new_uuid[1], new_uuid[2], new_uuid[3], new_uuid[4], new_uuid[5], new_uuid[6], new_uuid[7], new_uuid[8], new_uuid[9], new_uuid[10], new_uuid[11], new_uuid[12], new_uuid[13], new_uuid[14], new_uuid[15]); uuid[36] = '\0'; return; }
bool QCrawlerDB::storeRecord(QCrawlerRecord &rec) { QString url = rec.crawl_url().url(); QString host = rec.crawl_url().host(); QString url_md5 = md5_hash(url); QString parent_url_md5 = rec.crawl_url().parent_url_md5(); int crawl_level = rec.crawl_url().crawl_level(); QString anchor_text = rec.crawl_url().anchor_text(); QString raw_html = rec.raw_html(); // QString raw_title = rec.raw_title(); // QString raw_content = rec.raw_content(); QString raw_content_md5 = md5_hash(rec.raw_content()); int links_size = rec.raw_sub_links().size(); int download_time = rec.download_time(); int last_modified = rec.last_modified(); int loading_time = rec.loading_time(); TCMAP *cols = tcmapnew(); tcmapput2(cols, "url", url.toUtf8().constData()); tcmapput2(cols, "host", host.toUtf8().constData()); tcmapput2(cols, "url_md5", url_md5.toUtf8().constData()); tcmapput2(cols, "parent_url_md5", parent_url_md5.toUtf8().constData()); tcmapput2(cols, "crawl_level", QByteArray::number(crawl_level).constData()); tcmapput2(cols, "anchor_text", anchor_text.toUtf8().constData()); // tcmapput2(cols, "raw_html", raw_html.toUtf8().constData()); // tcmapput2(cols, "raw_title", raw_title.toUtf8().constData()); // tcmapput2(cols, "raw_content", rec.raw_content().toUtf8().constData()); // tcmapput2(cols, "raw_content_md5", md5_hash(rec.raw_content()).toUtf8().constData()); tcmapput2(cols, "title", rec.title().toUtf8().constData()); tcmapput2(cols, "content", rec.content().toUtf8().constData()); tcmapput2(cols, "links_size", QByteArray::number(links_size).constData()); tcmapput2(cols, "download_time", QByteArray::number(download_time).constData()); tcmapput2(cols, "last_modified", QByteArray::number(last_modified).constData()); tcmapput2(cols, "loading_time", QByteArray::number(loading_time).constData()); bool status = true; if(!tcrdbtblput(record_db, url_md5.toUtf8().constData(), url_md5.toUtf8().size(), cols)){ int ecode = tcrdbecode(record_db); fprintf(stderr, "store record put error: %s\n", tcrdberrmsg(ecode)); status = false; } tcmapdel(cols); // raw_html store if (!tcrdbput2(html_record_db, url_md5.toUtf8().constData(), raw_html.toUtf8().constData())) { int ecode = tcrdbecode(url_hash_db); fprintf(stderr, "update url status put error: %s\n", tcrdberrmsg(ecode)); return false; } return status; }
static int nw_clients_start_acquire_data(struct nodewatcher_module *module, struct ubus_context *ubus, struct uci_context *uci) { json_object *object = json_object_new_object(); /* Iterate over DHCP leases */ FILE *leases_file = fopen("/tmp/dhcp.leases", "r"); if (leases_file) { while (!feof(leases_file)) { unsigned int expiry; char mac[18]; char ip_address[46]; if (fscanf(leases_file, "%u %17s %45s %*[^\n]\n", &expiry, mac, ip_address) == 3) { json_object *client = json_object_new_object(); json_object *addresses = json_object_new_array(); json_object *address = json_object_new_object(); json_object_object_add(address, "family", json_object_new_string("ipv4")); json_object_object_add(address, "address", json_object_new_string(ip_address)); json_object_object_add(address, "expires", json_object_new_int(expiry)); json_object_array_add(addresses, address); json_object_object_add(client, "addresses", addresses); /* Compute salted hash of MAC address */ md5_ctx_t ctx; uint8_t raw_mac_id[16]; char mac_id[33]; md5_begin(&ctx); md5_hash(NW_CLIENT_ID_SALT, NW_CLIENT_ID_SALT_LENGTH, &ctx); md5_hash(mac, 17, &ctx); md5_end(raw_mac_id, &ctx); /* Base64 encode the hash so it is more compact */ if (nw_base64_encode(raw_mac_id, sizeof(raw_mac_id), mac_id, sizeof(mac_id)) == 0) { json_object_object_add(object, mac_id, client); } else { json_object_put(client); } } } fclose(leases_file); } /* Store resulting JSON object */ return nw_module_finish_acquire_data(module, object); }
int md5sum(char *file, uint32_t *md5) { char buf[256]; md5_ctx_t ctx; int len, fd; int ret = 0; memset(md5, 0, sizeof(*md5) * 4); fd = open(file, O_RDONLY); if (fd < 0) return -1; md5_begin(&ctx); do { len = read(fd, buf, sizeof(buf)); if (len < 0) { if (errno == EINTR) continue; ret = -1; goto out; } if (!len) break; md5_hash(buf, len, &ctx); } while(1); md5_end(md5, &ctx); out: close(fd); return ret; }
static int md5(lua_State *L) { size_t len; const char *input = lua_tolstring(L, 1, &len); if (input == NULL) { lua_pushstring(L, "first argument: should be the input string"); lua_error(L); __builtin_unreachable(); } unsigned char digest[MD5_DIGEST_LEN]; char output[MD5_STRLEN]; struct md5_ctx ctx; md5_begin(&ctx); md5_hash(input, len, &ctx); md5_end(digest, &ctx); // fill the digest bytewise in the output string int i; for (i = 0; i < MD5_DIGEST_LEN; i++) { sprintf(output + 2*i, "%02x", digest[i]); } lua_pushstring(L, output); return 1; }
int md5_file(const char *path, char out[MD5_DIGEST_LENGTH * 2 + 1]) { FILE *fp; char buffer[BUFSIZ]; unsigned char hash[SHA256_DIGEST_LENGTH]; size_t r = 0; MD5_CTX md5; if ((fp = fopen(path, "rb")) == NULL) { pkg_emit_errno("fopen", path); return EPKG_FATAL; } MD5_Init(&md5); while ((r = fread(buffer, 1, BUFSIZ, fp)) > 0) MD5_Update(&md5, buffer, r); if (ferror(fp) != 0) { fclose(fp); out[0] = '\0'; pkg_emit_errno("fread", path); return EPKG_FATAL; } fclose(fp); MD5_Final(hash, &md5); md5_hash(hash, out); return (EPKG_OK); }
int verify_user_info(msg_user_login_t<remote_t>* plogin, bool check_sign = true) { if (check_sign){ std::string sign_pat = plogin->acc_name_ + std::string(plogin->pwd_hash_) + plogin->machine_mark_ + the_config.signkey_; std::string sign_key = md5_hash(sign_pat); std::string sign_remote; sign_remote.insert(sign_remote.begin(), plogin->sign_, plogin->sign_ + 32); if (sign_key != sign_remote){ return error_wrong_sign; } } //防止sql注入攻击 sql_trim(plogin->acc_name_); sql_trim(plogin->machine_mark_); Database& db = *db_; Query q(db); //如果是在禁止列表中,不允许登录 std::string sql = "select 1 from user_blacklist where machine_mark = '" + std::string(plogin->machine_mark_) + "'"; if (!q.get_result(sql)){ return error_sql_execute_error; } if (q.fetch_row()){ return error_user_banned; } q.free_result(); return error_success; }
int brute_force_fixed_length (const uint32_t hash[4], byte_t* result, byte_t* test, int p, int len) { static md5_t MD5; static uint32_t check[4]; byte_t c; if (p < len-1) { for (c = START; c <= END; ++c) { test[p] = c; if (brute_force_fixed_length(hash, result, test, p + 1, len)) return 1; } } else { for (c = START; c <= END; ++c) { test[p] = c; md5_init(&MD5); md5_update(&MD5, test, len); md5_hash(&MD5, check); if (compare(hash, check)) { strcpy(result, test); return 1; } } } return 0; }
/* * Computes MD5 checksum of "passwd" (a null-terminated string) followed * by "salt" (which need not be null-terminated). * * Output format is "md5" followed by a 32-hex-digit MD5 checksum. * Hence, the output buffer "buf" must be at least 36 bytes long. * * Returns TRUE if okay, FALSE on error (out of memory). */ bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf) { size_t passwd_len = strlen(passwd); /* +1 here is just to avoid risk of unportable malloc(0) */ char *crypt_buf = malloc(passwd_len + salt_len + 1); bool ret; if (!crypt_buf) return false; /* * Place salt at the end because it may be known by users trying to crack * the MD5 output. */ memcpy(crypt_buf, passwd, passwd_len); memcpy(crypt_buf + passwd_len, salt, salt_len); strcpy(buf, "md5"); ret = md5_hash(crypt_buf, passwd_len + salt_len, buf + 3); free(crypt_buf); return ret; }
/* * generate one key from a string using the de facto standard * * resultant key is stored in * one 128 bit key: keys[0-15] * * (NOTE: I'm not sure why, but it seems that only values 0-12 are used, * resulting in 104 bits of keying, not 128) */ void wep_keygen128(char *str, u_char *keys) { md5_ctx_t ctx; u_char buf[64]; int i, j; /* repeat str until buf is full */ j = 0; for(i = 0; i < 64; i++) { if(str[j] == 0) j = 0; buf[i] = str[j++]; } md5_begin(&ctx); md5_hash(buf, sizeof buf, &ctx); md5_end(buf, &ctx); memcpy(keys, buf, WEPKEYSTORE); for(i = 0; i < WEPSTRONGKEYSIZE; i++) { keys[i] = buf[i]; } for(; i < WEPKEYSTORE; i++) { keys[i] = 0; } return; }
static void create_response(char *response, struct digest_auth_info *auth, char *method, char *password) { char *elem[3], ha1[33], ha2[33]; elem[0] = auth->username; elem[1] = auth->realm; elem[2] = password; md5_hash(elem, 3, ha1); elem[0] = method; elem[1] = auth->uri; md5_hash(elem, 2, ha2); elem[0] = ha1; elem[1] = auth->nonce; elem[2] = ha2; md5_hash(elem, 3, response); }
inline Uint32 md5_hash(const Uint64* keybuf, Uint32 no_of_32_words) { Uint32 result[4]; md5_hash(result, keybuf, no_of_32_words); return result[0]; }
static int mtd_verify(const char *mtd, char *file) { uint32_t f_md5[4], m_md5[4]; struct stat s; md5_ctx_t ctx; int ret = 0; int fd; if (quiet < 2) fprintf(stderr, "Verifying %s against %s ...\n", mtd, file); if (stat(file, &s) || md5sum(file, f_md5)) { fprintf(stderr, "Failed to hash %s\n", file); return -1; } fd = mtd_check_open(mtd); if(fd < 0) { fprintf(stderr, "Could not open mtd device: %s\n", mtd); return -1; } md5_begin(&ctx); do { char buf[256]; int len = (s.st_size > sizeof(buf)) ? (sizeof(buf)) : (s.st_size); int rlen = read(fd, buf, len); if (rlen < 0) { if (errno == EINTR) continue; ret = -1; goto out; } if (!rlen) break; md5_hash(buf, rlen, &ctx); s.st_size -= rlen; } while (s.st_size > 0); md5_end(m_md5, &ctx); fprintf(stderr, "%08x%08x%08x%08x - %s\n", m_md5[0], m_md5[1], m_md5[2], m_md5[3], mtd); fprintf(stderr, "%08x%08x%08x%08x - %s\n", f_md5[0], f_md5[1], f_md5[2], f_md5[3], file); ret = memcmp(f_md5, m_md5, sizeof(m_md5)); if (!ret) fprintf(stderr, "Success\n"); else fprintf(stderr, "Failed\n"); out: close(fd); return ret; }
Uint32 Restore::calulate_hash(Uint32 tableId, const Uint32 *src) { jam(); Uint64 Tmp[(MAX_KEY_SIZE_IN_WORDS*MAX_XFRM_MULTIPLY) >> 1]; Uint32 keyPartLen[MAX_ATTRIBUTES_IN_INDEX]; Uint32 keyLen = xfrm_key(tableId, src, (Uint32*)Tmp, sizeof(Tmp) >> 2, keyPartLen); ndbrequire(keyLen); return md5_hash(Tmp, keyLen); }
/* Check if we have an up-to-date thumbnail for this image. * If so, return it. Otherwise, returns NULL. */ static GdkPixbuf* get_thumbnail_for(const char *pathname) { GdkPixbuf *thumb = NULL; char *thumb_path, *uri; const char *ssize, *smtime; struct stat info; time_t ttime, now; char* path = pathdup(pathname); uri = g_filename_to_uri(path, NULL, NULL); if(!uri) uri = g_strconcat("file://", path, NULL); char* md5 = md5_hash(uri); g_free(uri); thumb_path = g_strdup_printf("%s/.thumbnails/normal/%s.png", g_get_home_dir(), md5); g_free(md5); thumb = gdk_pixbuf_new_from_file(thumb_path, NULL); if (!thumb) goto err; // Note that these don't need freeing... ssize = gdk_pixbuf_get_option(thumb, "tEXt::Thumb::Size"); if (!ssize) goto err; smtime = gdk_pixbuf_get_option(thumb, "tEXt::Thumb::MTime"); if (!smtime) goto err; if (stat(path, &info) != 0) goto err; ttime=(time_t) atol(smtime); time(&now); if (info.st_mtime != ttime && now>ttime+PIXMAP_THUMB_TOO_OLD_TIME) goto err; if (info.st_size < atol(ssize)) goto err; goto out; err: if (thumb) gdk_pixbuf_unref(thumb); thumb = NULL; out: g_free(path); g_free(thumb_path); return thumb; }
/* * Nonce format: * * Bytes 0- 3: date of nonce creation in seconds since epoch * Bytes 4-15: random bytes * Bytes 16-31: MD5( bytes[0..15] + ":" + digest secret ) */ static void create_nonce(struct digest_auth_info *auth) { unsigned char token[16]; char *v[2] = { auth->nonce, digest_secret }; struct timeval now; int i; if (! secret_created) create_digest_secret(); gettimeofday(&now, NULL); PUT_32(token, now.tv_sec); random_bytes(token + 4, sizeof(token) - 4); for (i = 0; i < 16; ++i) sprintf(auth->nonce + (i << 1), "%02x", token[i]); auth->nonce[32] = 0; md5_hash(v, 2, auth->nonce + 32); }
/* * encrypt fields in a json message */ void encrypt_fields(char **fields, int len, struct json_object *msg) { const char *field_key, *raw_string; char *encrypted_string; json_object *element; int i; for (i = 0; i < len; i++) { field_key = fields[i]; element = json_object_object_get(msg, field_key); if (element) { raw_string = json_object_get_string(element); } else { continue; } encrypted_string = md5_hash(raw_string); json_object_object_add(msg, field_key, json_object_new_string(encrypted_string)); free(encrypted_string); } }
void UpdateDialog::next_file_update(QNetworkReply* r){ if(r != NULL){ if(r->error()== QNetworkReply::NoError){ ui->progress_text->setText(ui->progress_text->toPlainText() +"\n"+tr("Download finished")); QString fp = downloadfile_list[current_file]->canonicalFilePath(); QFile f(fp.left(fp.lastIndexOf(".update"))); int lioSlash = fp.lastIndexOf("/"); if(lioSlash>=0){ QDir().mkpath(fp.left(lioSlash)); } QByteArray a = r->readAll(); QCryptographicHash md5_hash(QCryptographicHash::Md5); md5_hash.addData(a); QCryptographicHash sha1_hash(QCryptographicHash::Sha1); sha1_hash.addData(a); if(sha1_hash.result().toHex().toUpper() == downloadfile_list[current_file]->sha1Hash().toUpper() && md5_hash.result().toHex().toUpper() == downloadfile_list[current_file]->md5Hash().toUpper()){ f.open(QFile::WriteOnly); f.write(a); }else{ ui->progress_text->setText(ui->progress_text->toPlainText() +"\n"+tr("Installation failure") ); ui->progress_text->verticalScrollBar()->setValue(ui->progress_text->verticalScrollBar()->maximum()); } }else{ ui->error_dl_label->setText(r->errorString()); ui->progress_text->setText(ui->progress_text->toPlainText() +"\n"+tr("Download error")+r->errorString() ); ui->progress_text->verticalScrollBar()->setValue(ui->progress_text->verticalScrollBar()->maximum()); } } current_file++; if(current_file >= downloadfile_list.length()){ ui->nextButton->setEnabled(true); return; } ui->progress_text->setText(ui->progress_text->toPlainText() +"\n"+tr("Download: ")+repositories_list[current_repo_index]+downloadfile_list[current_file]->canonicalFilePath() ); ui->progress_text->verticalScrollBar()->setValue(ui->progress_text->verticalScrollBar()->maximum()); ui->current_download_filename->setText(tr("Download: ")+repositories_list[current_repo_index]+downloadfile_list[current_file]->canonicalFilePath()); QNetworkReply* i = dl_manager.post(QNetworkRequest(QUrl(repositories_list[current_repo_index]+downloadfile_list[current_file]->canonicalFilePath())),""); connect(i,SIGNAL(downloadProgress(qint64,qint64)),this,SLOT(file_update_progress(qint64,qint64))); ui->total_progress->setValue(current_file); }
void CalcFileHashesTask::run() { QByteArray buffer; const int buff_size = 65536; QCryptographicHash md5_hash(QCryptographicHash::Md5); QCryptographicHash sha1_hash(QCryptographicHash::Sha1); QCryptographicHash sha256_hash(QCryptographicHash::Sha256); qDebug() << "CalcFileHashesTask::run thread " << QThread::currentThread(); buffer.resize(buff_size); if (!file) { return; } if(!file->open(QIODevice::ReadOnly)) { // error opening qDebug() << "CalcFileHashesTask Error opening file " << file->error(); file->SetState(kErrorAccess); return; } QCryptographicHash cryptoHash(QCryptographicHash::Md5); while(!file->atEnd()){ buffer = file->read(buff_size); md5_hash.addData(buffer); sha1_hash.addData(buffer); sha256_hash.addData(buffer); } file->SetMd5(md5_hash.result()); file->SetSha1(sha1_hash.result()); file->SetSha256(sha256_hash.result()); file->close(); file->SetState(kHashesCalculated); // mark done }
void start_milkfish_boot(void) { md5_ctx_t MD; if (strlen(nvram_safe_get("milkfish_routerid")) != 32) { unsigned char hash[32]; char *et0 = nvram_safe_get("et0macaddr"); md5_begin(&MD); md5_hash(et0, 17, &MD); md5_end((unsigned char *)hash, &MD); char request[32]; int i; for (i = 0; i < 16; i++) sprintf(&request[2 * i], "%02x", hash[i]); nvram_set("milkfish_routerid", request); nvram_set("need_commit", "1"); } // Start the milkfish services eval("milkfish_services", "start"); // dbtext module setup mkdir("/var/openser", 0700); mkdir("/var/openser/dbtext", 0700); eval("cp", "/etc/openser/dbtext/aliases", "/var/openser/dbtext/"); eval("cp", "/etc/openser/dbtext/location", "/var/openser/dbtext/"); eval("cp", "/etc/openser/dbtext/subscriber", "/var/openser/dbtext/"); eval("cp", "/etc/openser/dbtext/version", "/var/openser/dbtext/"); eval("cp", "/etc/openser/dbtext/uri", "/var/openser/dbtext/"); eval("cp", "/etc/openser/dbtext/grp", "/var/openser/dbtext/"); // restore dbtext parts which may have been saved into nvram eval("milkfish_services", "sipdb", "restorenvdd"); // firewall configuration in networking/firewall.c return; }
/* * Computes MD5 checksum of "passwd" (a null-terminated string) followed * by "salt" (which need not be null-terminated). * * Output format is a 32-hex-digit MD5 checksum. * Hence, the output buffer "buf" must be at least 33 bytes long. * * Returns 1 if okay, 0 on error (out of memory). */ int md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf) { size_t passwd_len = strlen(passwd); char *crypt_buf = malloc(passwd_len + salt_len); int ret; if (!crypt_buf) return 0; /* failed */ /* * Place salt at the end because it may be known by users trying to crack * the MD5 output. */ strcpy(crypt_buf, passwd); memcpy(crypt_buf + passwd_len, salt, salt_len); ret = md5_hash(crypt_buf, passwd_len + salt_len, buf); free(crypt_buf); return ret; }
inline Md5 md5_hash(const std::string &str){ return md5_hash(str.data(), str.size()); }
inline Md5 md5_hash(const char *str){ return md5_hash(str, std::strlen(str)); }
CK_RV digest_mgr_digest( STDLL_TokData_t *tokdata, SESSION *sess, CK_BBOOL length_only, DIGEST_CONTEXT *ctx, CK_BYTE *in_data, CK_ULONG in_data_len, CK_BYTE *out_data, CK_ULONG *out_data_len ) { CK_RV rc; if (!sess || !ctx){ TRACE_ERROR("Invalid function arguments.\n"); return CKR_FUNCTION_FAILED; } if (ctx->active == FALSE){ TRACE_ERROR("%s\n", ock_err(ERR_OPERATION_NOT_INITIALIZED)); return CKR_OPERATION_NOT_INITIALIZED; } // if the caller just wants the encrypted length, there is no reason to // specify the input data. I just need the data length // if ((length_only == FALSE) && (!in_data || !out_data)){ TRACE_ERROR("%s\n", ock_err(ERR_FUNCTION_FAILED)); rc = CKR_FUNCTION_FAILED; goto out; } if (ctx->multi == TRUE){ TRACE_ERROR("%s\n", ock_err(ERR_OPERATION_ACTIVE)); rc = CKR_OPERATION_ACTIVE; goto out; } switch (ctx->mech.mechanism) { case CKM_SHA_1: case CKM_SHA256: case CKM_SHA384: case CKM_SHA512: rc = sha_hash( tokdata, sess, length_only, ctx, in_data, in_data_len, out_data, out_data_len ); break; #if !(NOMD2 ) case CKM_MD2: rc = md2_hash( tokdata, sess, length_only, ctx, in_data, in_data_len, out_data, out_data_len ); break; #endif case CKM_MD5: rc = md5_hash( tokdata, sess, length_only, ctx, in_data, in_data_len, out_data, out_data_len ); break; default: TRACE_ERROR("%s\n", ock_err(ERR_MECHANISM_INVALID)); rc = CKR_MECHANISM_INVALID; } out: if ( !((rc == CKR_BUFFER_TOO_SMALL) || (rc == CKR_OK && length_only == TRUE)) ) { // "A call to C_Digest always terminates the active digest operation unless it // returns CKR_BUFFER_TOO_SMALL or is a successful call (i.e., one which returns CKR_OK) // to determine the length of the buffer needed to hold the message digest." digest_mgr_cleanup(ctx); } return rc; }
int parse_pkcs8_private_key( rsa_key *privkey, const unsigned char *buffer, int buffer_length, const unsigned char *passphrase ) { struct asn1struct pkcs8_key; struct asn1struct private_key; struct asn1struct *encryptionId; struct asn1struct *salt; struct asn1struct *iteration_count; struct asn1struct *encrypted_key; struct asn1struct *key_type_oid; struct asn1struct *priv_key_data; digest_ctx initial_hash; int counter; unsigned char passphrase_hash_in[ MD5_RESULT_SIZE * sizeof( int ) ]; unsigned char passphrase_hash_out[ MD5_RESULT_SIZE * sizeof( int ) ]; unsigned char *decrypted_key; asn1parse( buffer, buffer_length, &pkcs8_key ); encryptionId = pkcs8_key.children->children; if ( memcmp( OID_pbeWithMD5andDES_CBC, encryptionId->data, encryptionId->length ) ) { fprintf( stderr, "Unsupported key encryption algorithm\n" ); asn1free( &pkcs8_key ); return 1; } // TODO support more algorithms salt = encryptionId->next->children; iteration_count = salt->next; encrypted_key = pkcs8_key.children->next; // ugly typecasting counter = ntohs( *iteration_count->data ); new_md5_digest( &initial_hash ); update_digest( &initial_hash, passphrase, strlen( passphrase ) ); update_digest( &initial_hash, salt->data, salt->length ); finalize_digest( &initial_hash ); memcpy( passphrase_hash_out, initial_hash.hash, initial_hash.hash_len * sizeof( int ) ); while ( --counter ) { memcpy( passphrase_hash_in, passphrase_hash_out, sizeof( int ) * MD5_RESULT_SIZE ); md5_hash( passphrase_hash_in, sizeof( int ) * MD5_RESULT_SIZE, ( unsigned int * ) passphrase_hash_out ); } decrypted_key = ( unsigned char * ) malloc( encrypted_key->length ); des_decrypt( encrypted_key->data, encrypted_key->length, decrypted_key, ( unsigned char * ) passphrase_hash_out + DES_KEY_SIZE, ( unsigned char * ) passphrase_hash_out ); // sanity check if ( decrypted_key[ encrypted_key->length - 1 ] > 8 ) { fprintf( stderr, "Decryption error, bad padding\n"); asn1free( &pkcs8_key ); free( decrypted_key ); return 1; } asn1parse( decrypted_key, encrypted_key->length - decrypted_key[ encrypted_key->length - 1 ], &private_key ); free( decrypted_key ); key_type_oid = private_key.children->next->children; if ( memcmp( OID_RSAPrivateKey, key_type_oid->data, key_type_oid->length ) ) { fprintf( stderr, "Unsupported private key type" ); asn1free( &pkcs8_key ); asn1free( &private_key ); } priv_key_data = private_key.children->next->next; parse_pkcs8_private_key( privkey, priv_key_data->data, priv_key_data->length, "password" ); asn1free( &pkcs8_key ); asn1free( &private_key ); return 0; }
int load_user_from_db(msg_user_login_t<remote_t>* plogin, player_ptr& pp, bool check_sign) { int verify = verify_user_info(plogin, check_sign); if (verify != error_success){ return verify; } char saccname[256] = {0}; int len = mysql_real_escape_string(&db_->grabdb()->mysql,saccname, plogin->acc_name_, strlen(plogin->acc_name_)); Database& db = *db_; Query q(db); std::string sql = "select uid, pwd, nickname, iid, gold, gold_game, gold_free, vip_level," " idnumber, mobile_number, mobile_verified, mail, mail_verified, level, addr_province, addr_city, addr_region," " gender, byear, bmonth, bday, address, age," " headpic from user_account where uname = '" + std::string(saccname) + "'" " or iid = '" + std::string(saccname) + "'" " or (mobile_number = '" + std::string(saccname) + "' and mobile_verified = 1)" " or (mail = '" + std::string(saccname) + "' and mail_verified = 1)"; if (!q.get_result(sql)) return error_sql_execute_error; if (!q.fetch_row()){ return error_no_record; } std::string uid = q.getstr(); std::string pwd = q.getstr(); std::string nickname = q.getstr(); __int64 iid = q.getbigint(); __int64 gold = q.getbigint(); __int64 gold_game = q.getbigint(); __int64 gold_free = q.getbigint(); int vip_lv = q.getval(); std::string idnumber = q.getstr(); std::string mobile = q.getstr(); int mobile_verified = q.getval(); std::string mail = q.getstr(); int mail_verified = q.getval(); int lv = q.getval(); int r1 = q.getval(); int r2 = q.getval(); int r3 = q.getval(); int gender = q.getval(); int byear = q.getval(); int bmonth = q.getval(); int bday = q.getval(); std::string addr = q.getstr(); int age = q.getval(); std::vector<char> headpic; q.getblob("headpic", headpic); if (md5_hash(pwd) != plogin->pwd_hash_){ return error_wrong_password; } if (nickname == ""){ nickname = "newplayer"; } q.free_result(); plogin->from_sock_->set_authorized(); __int64 seq = 0; ::time(&seq); { BEGIN_UPDATE_TABLE("user_account"); SET_FIELD_VALUE("machine_mark", plogin->machine_mark_); SET_FINAL_VALUE("is_online", 1); WITH_END_CONDITION("where uid = '" + uid + "'"); EXECUTE_IMMEDIATE(); } { BEGIN_INSERT_TABLE("log_user_loginout"); SET_FIELD_VALUE("uid", uid); SET_FINAL_VALUE("islogin", 1); EXECUTE_IMMEDIATE(); } std::string token = md5_hash(uid + boost::lexical_cast<std::string>(seq) + the_config.token_generate_key_); pp->uid_ = uid; pp->connect_lost_tick_ = boost::posix_time::microsec_clock::local_time(); pp->is_connection_lost_ = 0; pp->iid_ = iid; pp->nickname_ = nickname; pp->head_ico_ = headpic; pp->gold_ = gold; pp->vip_level_ = vip_lv; pp->token_ = token; pp->seq_ = seq; pp->idnumber_ = idnumber; pp->age_ = age; pp->mobile_ = mobile; pp->email_ = mail; pp->region1_ = r1; pp->region2_ = r2; pp->region3_ = r3; pp->gold_game_ = gold_game; pp->mobile_v_ = mobile_verified; pp->email_v_ = mail_verified; pp->byear_ = byear; pp->bmonth_ = bmonth; pp->bday_ = bday; pp->address_ = addr; pp->gender_ = gender; pp->gold_free_ = gold_free; return error_success; }
void Dbtup::scanReply(Signal* signal, ScanOpPtr scanPtr) { ScanOp& scan = *scanPtr.p; FragrecordPtr fragPtr; fragPtr.i = scan.m_fragPtrI; ptrCheckGuard(fragPtr, cnoOfFragrec, fragrecord); Fragrecord& frag = *fragPtr.p; // for reading tuple key in Current state Uint32* pkData = (Uint32*)c_dataBuffer; unsigned pkSize = 0; if (scan.m_state == ScanOp::Current) { // found an entry to return jam(); ndbrequire(scan.m_accLockOp == RNIL); if (scan.m_bits & ScanOp::SCAN_LOCK) { jam(); // read tuple key - use TUX routine const ScanPos& pos = scan.m_scanPos; const Local_key& key_mm = pos.m_key_mm; int ret = tuxReadPk(fragPtr.i, pos.m_realpid_mm, key_mm.m_page_idx, pkData, true); ndbrequire(ret > 0); pkSize = ret; dbg((DBTUP, "PK size=%d data=%08x", pkSize, pkData[0])); // get read lock or exclusive lock AccLockReq* const lockReq = (AccLockReq*)signal->getDataPtrSend(); lockReq->returnCode = RNIL; lockReq->requestInfo = (scan.m_bits & ScanOp::SCAN_LOCK_SH) ? AccLockReq::LockShared : AccLockReq::LockExclusive; lockReq->accOpPtr = RNIL; lockReq->userPtr = scanPtr.i; lockReq->userRef = reference(); lockReq->tableId = scan.m_tableId; lockReq->fragId = frag.fragmentId; lockReq->fragPtrI = RNIL; // no cached frag ptr yet lockReq->hashValue = md5_hash((Uint64*)pkData, pkSize); lockReq->tupAddr = key_mm.ref(); lockReq->transId1 = scan.m_transId1; lockReq->transId2 = scan.m_transId2; EXECUTE_DIRECT(DBACC, GSN_ACC_LOCKREQ, signal, AccLockReq::LockSignalLength); jamEntry(); switch (lockReq->returnCode) { case AccLockReq::Success: jam(); scan.m_state = ScanOp::Locked; scan.m_accLockOp = lockReq->accOpPtr; break; case AccLockReq::IsBlocked: jam(); // normal lock wait scan.m_state = ScanOp::Blocked; scan.m_bits |= ScanOp::SCAN_LOCK_WAIT; scan.m_accLockOp = lockReq->accOpPtr; // LQH will wake us up signal->theData[0] = scan.m_userPtr; signal->theData[1] = true; EXECUTE_DIRECT(DBLQH, GSN_CHECK_LCP_STOP, signal, 2); jamEntry(); return; break; case AccLockReq::Refused: jam(); // we cannot see deleted tuple (assert only) ndbassert(false); // skip it scan.m_state = ScanOp::Next; signal->theData[0] = scan.m_userPtr; signal->theData[1] = true; EXECUTE_DIRECT(DBLQH, GSN_CHECK_LCP_STOP, signal, 2); jamEntry(); return; break; case AccLockReq::NoFreeOp: jam(); // max ops should depend on max scans (assert only) ndbassert(false); // stay in Current state scan.m_state = ScanOp::Current; signal->theData[0] = scan.m_userPtr; signal->theData[1] = true; EXECUTE_DIRECT(DBLQH, GSN_CHECK_LCP_STOP, signal, 2); jamEntry(); return; break; default: ndbrequire(false); break; } } else { scan.m_state = ScanOp::Locked; } } if (scan.m_state == ScanOp::Locked) { // we have lock or do not need one jam(); // conf signal NextScanConf* const conf = (NextScanConf*)signal->getDataPtrSend(); conf->scanPtr = scan.m_userPtr; // the lock is passed to LQH Uint32 accLockOp = scan.m_accLockOp; if (accLockOp != RNIL) { scan.m_accLockOp = RNIL; // remember it until LQH unlocks it addAccLockOp(scan, accLockOp); } else { ndbrequire(! (scan.m_bits & ScanOp::SCAN_LOCK)); // operation RNIL in LQH would signal no tuple returned accLockOp = (Uint32)-1; } const ScanPos& pos = scan.m_scanPos; conf->accOperationPtr = accLockOp; conf->fragId = frag.fragmentId; conf->localKey[0] = pos.m_key_mm.ref(); conf->localKey[1] = 0; conf->localKeyLength = 1; unsigned signalLength = 6; if (scan.m_bits & ScanOp::SCAN_LOCK) { sendSignal(scan.m_userRef, GSN_NEXT_SCANCONF, signal, signalLength, JBB); } else { Uint32 blockNo = refToBlock(scan.m_userRef); EXECUTE_DIRECT(blockNo, GSN_NEXT_SCANCONF, signal, signalLength); jamEntry(); } // next time look for next entry scan.m_state = ScanOp::Next; return; } if (scan.m_state == ScanOp::Last || scan.m_state == ScanOp::Invalid) { jam(); NextScanConf* const conf = (NextScanConf*)signal->getDataPtrSend(); conf->scanPtr = scan.m_userPtr; conf->accOperationPtr = RNIL; conf->fragId = RNIL; unsigned signalLength = 3; sendSignal(scanPtr.p->m_userRef, GSN_NEXT_SCANCONF, signal, signalLength, JBB); return; } ndbrequire(false); }
void loadanopedb() { char accname[50]; char md5_pass[40]; char email[EMAILLEN+1]; int acclvl; char channelname[CHANLEN+1]; char owner[50]; char entrymsg[200]; User *uptr,*owner_ptr; Chan *chan_ptr; MYSQL_RES *result; MYSQL_ROW row; char *pass; if (!reconnect_to_db()) { fprintf(stderr,"Cannot connect to db\n"); operlog("Cannot connect to db"); return; } mysql_query(&mysql2,"SELECT display,pass,email FROM anope_ns_core"); if ((result = mysql_use_result(&mysql2)) == NULL) { printf("CRITICAL: Cannot load anope user db: mysql_use_result returned NULL !\n"); return; } while ((row = mysql_fetch_row(result))) { bzero(accname,50); bzero(md5_pass,40); bzero(email,EMAILLEN); strncpy(accname,row[0],50); if (row[1][0] == '\0') { printf("ANOPE ERROR: User %s does not have any pass !\n",accname); continue; } if (me.anopemd5 == 0) { pass = md5_hash(row[1]); strncpy(md5_pass,pass,40); free(pass); } else strncpy(md5_pass,row[1],40); strncpy(email,row[2],EMAILLEN); if (find_user(accname)) continue; uptr = AddUser(accname,1); uptr->lastseen = time(NULL); uptr->options = 0; uptr->timeout = TIMEOUT_DFLT; bzero(uptr->vhost,HOSTLEN); bzero(uptr->md5_pass,34); strncpy(uptr->md5_pass,md5_pass,32); strncpy(uptr->email,email,EMAILLEN); } mysql_query(&mysql2,"SELECT name,founder,entry_message FROM anope_cs_info"); if ((result = mysql_use_result(&mysql2)) == NULL) { printf("CRITICAL: Cannot load anope chan db: mysql_use_result returned NULL !\n"); return; } while((row = mysql_fetch_row(result))) { strncpy(channelname,row[0],CHANLEN); strncpy(owner,row[1],50); strncpy(entrymsg,row[2],200); if (find_channel(channelname)) continue; owner_ptr = find_user(owner); if (!owner_ptr) { fprintf(stderr,"ANOPE ERROR: Cannot load channel %s with owner %s : find_user returned NULL !!\n",channelname,owner); continue; } chan_ptr = CreateChannel(channelname,owner,time(NULL)); chan_ptr->autolimit = 0; strncpy(chan_ptr->entrymsg,entrymsg,sizeof(chan_ptr->entrymsg)-1); bzero(chan_ptr->mlock,50); } mysql_query(&mysql2,"SELECT channel,display,level FROM anope_cs_access"); if ((result = mysql_use_result(&mysql2)) == NULL) { printf("CRITICAL: Cannot load anope channel access db: mysql_use_result returned NULL !\n"); return; } while((row = mysql_fetch_row(result))) { strncpy(channelname,row[0],CHANLEN); strncpy(accname,row[1],50); acclvl = strtol(row[2],NULL,10); chan_ptr = find_channel(channelname); if (!chan_ptr) { fprintf(stderr,"ANOPE ERROR: Cannot load access for user %s for channel %s : find_channel returned NULL !!\n",accname,channelname); continue; } uptr = find_user(accname); if (!uptr) { fprintf(stderr,"ANOPE ERROR: Cannot load access for user %s for channel %s : find_user returned NULL !!\n",accname,channelname); continue; } if (find_cflag(accname,channelname)) continue; if (acclvl < CHLEV_OWNER) AddUserToChannel(uptr,chan_ptr,acclvl,0); } mysql_close(&mysql); }
void hotspotsys_config(void) { FILE *fp; char *next; char var[64]; char *dnslist; int i; md5_ctx_t MD; if (strlen(nvram_safe_get("hotss_remotekey")) != 12) { unsigned char hash[32]; char *et0 = nvram_safe_get("et0macaddr"); md5_begin(&MD); md5_hash(et0, 17, &MD); md5_end((unsigned char *)hash, &MD); char idkey[16]; int i; for (i = 0; i < 6; i++) sprintf(&idkey[2 * i], "%02d", (hash[i] + hash[i + 1]) % 100); idkey[12] = '\0'; nvram_set("hotss_remotekey", idkey); nvram_commit(); char sendid[256]; sprintf(sendid, "/usr/bin/wget http://tech.hotspotsystem.com/up.php?mac=`nvram get wl0_hwaddr|sed s/:/-/g`\\&operator=%s\\&location=%s\\&remotekey=%s", nvram_get("hotss_operatorid"), nvram_get("hotss_locationid"), nvram_get("hotss_remotekey")); system2(sendid); } if (!(fp = fopen("/tmp/chilli/hotss.conf", "w"))) { perror("/tmp/chilli/hotss.conf"); return; } fprintf(fp, "ipup /tmp/chilli/ip-up.sh\n"); fprintf(fp, "ipdown /tmp/chilli/ip-down.sh\n"); fprintf(fp, "radiusserver1 radius.hotspotsystem.com\n"); fprintf(fp, "radiusserver2 radius2.hotspotsystem.com\n"); fprintf(fp, "radiussecret hotsys123\n"); fprintf(fp, "dhcpif %s\n", nvram_safe_get("hotss_interface")); if (nvram_invmatch("hotss_net", "")) fprintf(fp, "net %s\n", nvram_get("hotss_net")); char *uamdomain = "customer.hotspotsystem.com"; if (!nvram_match("hotss_customuam", "")) { uamdomain = nvram_safe_get("hotss_customuam"); } fprintf(fp, "uamserver %s://%s/customer/hotspotlogin.php\n", nvram_default_get("hotss_customuamproto", "https"), uamdomain); if (nvram_invmatch("wan_get_dns", "0.0.0.0") && nvram_invmatch("wan_get_dns", "")) { dnslist = nvram_safe_get("wan_get_dns"); i = 1; foreach(var, dnslist, next) { if (i > 2) break; fprintf(fp, "dns%d %s\n", i, var); i++; } } else if (nvram_invmatch("wan_dns", "0.0.0.0")
NSS_IMPLEMENT nssCryptokiObject * nssToken_ImportTrust ( NSSToken *tok, nssSession *sessionOpt, NSSDER *certEncoding, NSSDER *certIssuer, NSSDER *certSerial, nssTrustLevel serverAuth, nssTrustLevel clientAuth, nssTrustLevel codeSigning, nssTrustLevel emailProtection, PRBool stepUpApproved, PRBool asTokenObject ) { nssCryptokiObject *object; CK_OBJECT_CLASS tobjc = CKO_NSS_TRUST; CK_TRUST ckSA, ckCA, ckCS, ckEP; CK_ATTRIBUTE_PTR attr; CK_ATTRIBUTE trust_tmpl[11]; CK_ULONG tsize; PRUint8 sha1[20]; /* this is cheating... */ PRUint8 md5[16]; NSSItem sha1_result, md5_result; sha1_result.data = sha1; sha1_result.size = sizeof sha1; md5_result.data = md5; md5_result.size = sizeof md5; sha1_hash(certEncoding, &sha1_result); md5_hash(certEncoding, &md5_result); ckSA = get_ck_trust(serverAuth); ckCA = get_ck_trust(clientAuth); ckCS = get_ck_trust(codeSigning); ckEP = get_ck_trust(emailProtection); NSS_CK_TEMPLATE_START(trust_tmpl, attr, tsize); if (asTokenObject) { NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true); } else { NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false); } NSS_CK_SET_ATTRIBUTE_VAR( attr, CKA_CLASS, tobjc); NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_ISSUER, certIssuer); NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_SERIAL_NUMBER, certSerial); NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_CERT_SHA1_HASH, &sha1_result); NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_CERT_MD5_HASH, &md5_result); /* now set the trust values */ NSS_CK_SET_ATTRIBUTE_VAR(attr, CKA_TRUST_SERVER_AUTH, ckSA); NSS_CK_SET_ATTRIBUTE_VAR(attr, CKA_TRUST_CLIENT_AUTH, ckCA); NSS_CK_SET_ATTRIBUTE_VAR(attr, CKA_TRUST_CODE_SIGNING, ckCS); NSS_CK_SET_ATTRIBUTE_VAR(attr, CKA_TRUST_EMAIL_PROTECTION, ckEP); if (stepUpApproved) { NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TRUST_STEP_UP_APPROVED, &g_ck_true); } else { NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TRUST_STEP_UP_APPROVED, &g_ck_false); } NSS_CK_TEMPLATE_FINISH(trust_tmpl, attr, tsize); /* import the trust object onto the token */ object = import_object(tok, sessionOpt, trust_tmpl, tsize); if (object && tok->cache) { nssTokenObjectCache_ImportObject(tok->cache, object, tobjc, trust_tmpl, tsize); } return object; }