void SC_ASIYA::write_report(string TGT, string REF, string METRIC, double sys_score, const vector<double> &doc_scores, const vector<double> &seg_scores) { MetricScore m; m.sys_score = sys_score; m.doc_scores = doc_scores; m.seg_scores = seg_scores; write_report(TGT, REF, METRIC, m); }
t_log::t_log() { log_disabled = false; log_report_disabled = false; inform_user = false; sema_logview = NULL; thr_logview = NULL; log_filename = DIR_HOME; log_filename += "/"; log_filename += DIR_USER; log_filename += "/"; log_filename += LOG_FILENAME; // If there is a previous log file, then move that to the .old file // before zapping the current log file. (void)move_current_to_old(); log_stream = new ofstream(log_filename.c_str()); if (!*log_stream) { log_disabled = true; string err = TRANSLATE("Failed to create log file %1 ."); err = replace_first(err, "%1", log_filename); err += "\nLogging is now disabled."; if (ui) ui->cb_show_msg(err, MSG_WARNING); return; } string s = PRODUCT_NAME; s += ' '; s += PRODUCT_VERSION; s += ", "; s += PRODUCT_DATE; write_report(s, "t_log::t_log"); string options_built = sys_config->get_options_built(); if (!options_built.empty()) { s = "Built with support for: "; s += options_built; write_report(s, "t_log::t_log"); } }
int main(int argc, char** argv) { s32 opt; u32 loop_cnt = 0, purge_age = 0, seed; u8 sig_loaded = 0, show_once = 0, no_statistics = 0, display_mode = 0, has_fake = 0; s32 oindex = 0; u8 *wordlist = NULL, *output_dir = NULL; u8 *sig_list_strg = NULL; u8 *gtimeout_str = NULL; u32 gtimeout = 0; struct termios term; struct timeval tv; u64 st_time, en_time; signal(SIGINT, ctrlc_handler); signal(SIGWINCH, resize_handler); signal(SIGPIPE, SIG_IGN); SSL_library_init(); /* Options, options, and options */ static struct option long_options[] = { {"auth", required_argument, 0, 'A' }, {"host", required_argument, 0, 'F' }, {"cookie", required_argument, 0, 'C' }, {"reject-cookies", required_argument, 0, 'N' }, {"header", required_argument, 0, 'H' }, {"user-agent", required_argument, 0, 'b' }, #ifdef PROXY_SUPPORT {"proxy", required_argument, 0, 'J' }, #endif /* PROXY_SUPPORT */ {"max-depth", required_argument, 0, 'd' }, {"max-child", required_argument, 0, 'c' }, {"max-descendants", required_argument, 0, 'x' }, {"max-requests", required_argument, 0, 'r' }, {"max-rate", required_argument, 0, 'l'}, {"probability", required_argument, 0, 'p' }, {"seed", required_argument, 0, 'q' }, {"include", required_argument, 0, 'I' }, {"exclude", required_argument, 0, 'X' }, {"skip-param", required_argument, 0, 'K' }, {"skip-forms", no_argument, 0, 'O' }, {"include-domain", required_argument, 0, 'D' }, {"ignore-links", no_argument, 0, 'P' }, {"no-ext-fuzzing", no_argument, 0, 'Y' }, {"log-mixed-content", no_argument, 0, 'M' }, {"skip-error-pages", no_argument, 0, 'Z' }, {"log-external-urls", no_argument, 0, 'U' }, {"log-cache-mismatches", no_argument, 0, 'E' }, {"form-value", no_argument, 0, 'T' }, {"rw-wordlist", required_argument, 0, 'W' }, {"no-keyword-learning", no_argument, 0, 'L' }, {"mode", required_argument, 0, 'J' }, {"wordlist", required_argument, 0, 'S'}, {"trust-domain", required_argument, 0, 'B' }, {"max-connections", required_argument, 0, 'g' }, {"max-host-connections", required_argument, 0, 'm' }, {"max-fail", required_argument, 0, 'f' }, {"request-timeout", required_argument, 0, 't' }, {"network-timeout", required_argument, 0, 'w' }, {"idle-timeout", required_argument, 0, 'i' }, {"response-size", required_argument, 0, 's' }, {"discard-binary", required_argument, 0, 'e' }, {"output", required_argument, 0, 'o' }, {"help", no_argument, 0, 'h' }, {"quiet", no_argument, 0, 'u' }, {"verbose", no_argument, 0, 'v' }, {"scan-timeout", required_argument, 0, 'k'}, {"signatures", required_argument, 0, 'z'}, {"checks", no_argument, 0, 0}, {"checks-toggle", required_argument, 0, 0}, {"no-checks", no_argument, 0, 0}, {"fast", no_argument, 0, 0}, {"auth-form", required_argument, 0, 0}, {"auth-form-target", required_argument, 0, 0}, {"auth-user", required_argument, 0, 0}, {"auth-user-field", required_argument, 0, 0}, {"auth-pass", required_argument, 0, 0}, {"auth-pass-field", required_argument, 0, 0}, {"auth-verify-url", required_argument, 0, 0}, {0, 0, 0, 0 } }; /* Come up with a quasi-decent random seed. */ gettimeofday(&tv, NULL); seed = tv.tv_usec ^ (tv.tv_sec << 16) ^ getpid(); SAY("skipfish version " VERSION " by <*****@*****.**>\n"); while ((opt = getopt_long(argc, argv, "+A:B:C:D:EF:G:H:I:J:K:LMNOPQR:S:T:UW:X:YZ" "b:c:d:ef:g:hi:k:l:m:o:p:q:r:s:t:uvw:x:z:", long_options, &oindex)) >= 0) switch (opt) { case 'A': { u8* x = (u8*)strchr(optarg, ':'); if (!x) FATAL("Credentials must be in 'user:pass' form."); *(x++) = 0; auth_user = (u8*)optarg; auth_pass = x; auth_type = AUTH_BASIC; break; } #ifdef PROXY_SUPPORT case 'J': { u8* x = (u8*)strchr(optarg, ':'); if (!x) FATAL("Proxy data must be in 'host:port' form."); *(x++) = 0; use_proxy = (u8*)optarg; use_proxy_port = atoi((char*)x); if (!use_proxy_port) FATAL("Incorrect proxy port number."); break; } #endif /* PROXY_SUPPORT */ case 'F': { u8* x = (u8*)strchr(optarg, '='); u32 fake_addr; if (!x) FATAL("Fake mappings must be in 'host=IP' form."); *x = 0; fake_addr = inet_addr((char*)x + 1); if (fake_addr == (u32)-1) FATAL("Could not parse IP address '%s'.", x + 1); fake_host((u8*)optarg, fake_addr); has_fake = 1; break; } case 'H': { u8* x = (u8*)strchr(optarg, '='); if (!x) FATAL("Extra headers must be in 'name=value' form."); *x = 0; if (!strcasecmp(optarg, "Cookie")) FATAL("Do not use -H to set cookies (try -C instead)."); SET_HDR((u8*)optarg, x + 1, &global_http_par); break; } case 'C': { u8* x = (u8*)strchr(optarg, '='); if (!x) FATAL("Cookies must be in 'name=value' form."); if (strchr(optarg, ';')) FATAL("Split multiple cookies into separate -C options."); *x = 0; SET_CK((u8*)optarg, x + 1, &global_http_par); break; } case 'D': if (*optarg == '*') optarg++; APPEND_FILTER(allow_domains, num_allow_domains, optarg); break; case 'K': APPEND_FILTER(skip_params, num_skip_params, optarg); break; case 'B': if (*optarg == '*') optarg++; APPEND_FILTER(trust_domains, num_trust_domains, optarg); break; case 'I': if (*optarg == '*') optarg++; APPEND_FILTER(allow_urls, num_allow_urls, optarg); break; case 'X': if (*optarg == '*') optarg++; APPEND_FILTER(deny_urls, num_deny_urls, optarg); break; case 'T': { u8* x = (u8*)strchr(optarg, '='); if (!x) FATAL("Rules must be in 'name=value' form."); *x = 0; add_form_hint((u8*)optarg, x + 1); break; } case 'N': ignore_cookies = 1; break; case 'Y': no_fuzz_ext = 1; break; case 'q': if (sscanf(optarg, "0x%08x", &seed) != 1) FATAL("Invalid seed format."); srandom(seed); break; case 'Q': suppress_dupes = 1; break; case 'P': no_parse = 1; break; case 'M': warn_mixed = 1; break; case 'U': log_ext_urls = 1; break; case 'L': dont_add_words = 1; break; case 'E': pedantic_cache = 1; break; case 'O': no_forms = 1; break; case 'R': purge_age = atoi(optarg); if (purge_age < 3) FATAL("Purge age invalid or too low (min 3)."); break; case 'd': max_depth = atoi(optarg); if (max_depth < 2) FATAL("Invalid value '%s'.", optarg); break; case 'c': max_children = atoi(optarg); if (!max_children) FATAL("Invalid value '%s'.", optarg); break; case 'x': max_descendants = atoi(optarg); if (!max_descendants) FATAL("Invalid value '%s'.", optarg); break; case 'p': crawl_prob = atoi(optarg); if (!crawl_prob) FATAL("Invalid value '%s'.", optarg); break; case 'W': if (wordlist) FATAL("Only one -W parameter permitted (use -S to load supplemental dictionaries)."); if (!strcmp(optarg, "-")) wordlist = (u8*)"/dev/null"; else wordlist = (u8*)optarg; break; case 'S': load_keywords((u8*)optarg, 1, 0); break; case 'z': load_signatures((u8*)optarg); sig_loaded = 1; break; case 'b': if (optarg[0] == 'i') browser_type = BROWSER_MSIE; else if (optarg[0] == 'f') browser_type = BROWSER_FFOX; else if (optarg[0] == 'p') browser_type = BROWSER_PHONE; else usage(argv[0]); break; case 'g': max_connections = atoi(optarg); if (!max_connections) FATAL("Invalid value '%s'.", optarg); break; case 'm': max_conn_host = atoi(optarg); if (!max_conn_host) FATAL("Invalid value '%s'.", optarg); break; case 'G': max_guesses = atoi(optarg); if (!max_guesses) FATAL("Invalid value '%s'.", optarg); break; case 'r': max_requests = atoi(optarg); if (!max_requests) FATAL("Invalid value '%s'.", optarg); break; case 'l': max_requests_sec = atof(optarg); if (!max_requests_sec) FATAL("Invalid value '%s'.", optarg); break; case 'f': max_fail = atoi(optarg); if (!max_fail) FATAL("Invalid value '%s'.", optarg); break; case 't': resp_tmout = atoi(optarg); if (!resp_tmout) FATAL("Invalid value '%s'.", optarg); break; case 'w': rw_tmout = atoi(optarg); if (!rw_tmout) FATAL("Invalid value '%s'.", optarg); break; case 'i': idle_tmout = atoi(optarg); if (!idle_tmout) FATAL("Invalid value '%s'.", optarg); break; case 's': size_limit = atoi(optarg); if (!size_limit) FATAL("Invalid value '%s'.", optarg); break; case 'o': if (output_dir) FATAL("Multiple -o options not allowed."); output_dir = (u8*)optarg; rmdir(optarg); if (mkdir(optarg, 0755)) PFATAL("Unable to create '%s'.", output_dir); break; case 'u': no_statistics = 1; break; case 'v': verbosity++; break; case 'e': delete_bin = 1; break; case 'k': if (gtimeout_str) FATAL("Multiple -k options not allowed."); gtimeout_str = (u8*)optarg; break; case 'Z': no_500_dir = 1; break; case 0: if (!strcmp("checks", long_options[oindex].name )) display_injection_checks(); if (!strcmp("checks-toggle", long_options[oindex].name )) toggle_injection_checks((u8*)optarg, 1, 1); if (!strcmp("no-checks", long_options[oindex].name )) no_checks = 1; if (!strcmp("signatures", long_options[oindex].name )) load_signatures((u8*)optarg); if(!strcmp("fast", long_options[oindex].name )) toggle_injection_checks((u8*)"2,4,5,13,14,15,16", 0, 0); if (!strcmp("auth-form", long_options[oindex].name )) auth_form = (u8*)optarg; if (!strcmp("auth-user", long_options[oindex].name )) auth_user = (u8*)optarg; if (!strcmp("auth-pass", long_options[oindex].name )) auth_pass = (u8*)optarg; if (!strcmp("auth-pass-field", long_options[oindex].name )) auth_pass_field = (u8*)optarg; if (!strcmp("auth-user-field", long_options[oindex].name )) auth_user_field = (u8*)optarg; if (!strcmp("auth-form-target", long_options[oindex].name )) auth_form_target = (u8*)optarg; if (!strcmp("auth-verify-url", long_options[oindex].name )) auth_verify_url = (u8*)optarg; break; default: usage(argv[0]); } #ifdef PROXY_SUPPORT if (has_fake && use_proxy) FATAL("-F and -J should not be used together."); #endif /* PROXY_SUPPORT */ if (access(ASSETS_DIR "/index.html", R_OK)) PFATAL("Unable to access '%s/index.html' - wrong directory?", ASSETS_DIR); srandom(seed); if (optind == argc) FATAL("Scan target not specified (try -h for help)."); if (!output_dir) FATAL("Output directory not specified (try -h for help)."); if(verbosity && !no_statistics && isatty(2)) FATAL("Please use -v in combination with the -u flag or, " "run skipfish while redirecting stderr to a file. "); if (resp_tmout < rw_tmout) resp_tmout = rw_tmout; if (max_connections < max_conn_host) max_connections = max_conn_host; /* Parse the timeout string - format h:m:s */ if (gtimeout_str) { int i = 0; int m[3] = { 1, 60, 3600 }; u8* tok = (u8*)strtok((char*)gtimeout_str, ":"); while(tok && i <= 2) { gtimeout += atoi((char*)tok) * m[i]; tok = (u8*)strtok(NULL, ":"); i++; } if(!gtimeout) FATAL("Wrong timeout format, please use h:m:s (hours, minutes, seconds)"); DEBUG("* Scan timeout is set to %d seconds\n", gtimeout); } if (!wordlist) { wordlist = (u8*)"/dev/null"; DEBUG("* No wordlist specified with -W: defaulting to /dev/null\n"); } /* If no signature files have been specified via command-line: load the default file */ if (!sig_loaded) load_signatures((u8*)SIG_FILE); load_keywords(wordlist, 0, purge_age); /* Load the signatures list for the matching */ if (sig_list_strg) load_signatures(sig_list_strg); /* Try to authenticate when the auth_user and auth_pass fields are set. */ if (auth_user && auth_pass) { authenticate(); while (next_from_queue()) { usleep(1000); } switch (auth_state) { case ASTATE_DONE: DEBUGC(L1, "*- Authentication succeeded!\n"); break; default: DEBUG("Auth state: %d\n", auth_state); FATAL("Authentication failed (use -uv for more info)\n"); break; } } /* Schedule all URLs in the command line for scanning. */ while (optind < argc) { struct http_request *req; /* Support @ notation for reading URL lists from files. */ if (argv[optind][0] == '@') { read_urls((u8*)argv[optind++] + 1); continue; } req = ck_alloc(sizeof(struct http_request)); if (parse_url((u8*)argv[optind], req, NULL)) FATAL("Scan target '%s' is not a valid absolute URL.", argv[optind]); if (!url_allowed_host(req)) APPEND_FILTER(allow_domains, num_allow_domains, __DFL_ck_strdup(req->host)); if (!url_allowed(req)) FATAL("URL '%s' explicitly excluded by -I / -X rules.", argv[optind]); maybe_add_pivot(req, NULL, 2); destroy_request(req); optind++; } /* Char-by char stdin. */ tcgetattr(0, &term); term.c_lflag &= ~ICANON; tcsetattr(0, TCSANOW, &term); fcntl(0, F_SETFL, O_NONBLOCK); gettimeofday(&tv, NULL); st_time = tv.tv_sec * 1000LL + tv.tv_usec / 1000; #ifdef SHOW_SPLASH if (!no_statistics) splash_screen(); #endif /* SHOW_SPLASH */ if (!no_statistics) SAY("\x1b[H\x1b[J"); else SAY(cLGN "[*] " cBRI "Scan in progress, please stay tuned...\n"); u64 refresh_time = 0; /* Enter the crawler loop */ while ((next_from_queue() && !stop_soon) || (!show_once++)) { u8 keybuf[8]; u64 end_time; u64 run_time; struct timeval tv_tmp; gettimeofday(&tv_tmp, NULL); end_time = tv_tmp.tv_sec * 1000LL + tv_tmp.tv_usec / 1000; run_time = end_time - st_time; if (gtimeout > 0 && run_time && run_time/1000 > gtimeout) { DEBUG("* Stopping scan due to timeout\n"); stop_soon = 1; } req_sec = (req_count - queue_cur / 1.15) * 1000 / (run_time + 1); if (no_statistics || ((loop_cnt++ % 100) && !show_once && idle == 0)) continue; if (end_time > refresh_time) { refresh_time = (end_time + 10); if (clear_screen) { SAY("\x1b[H\x1b[2J"); clear_screen = 0; } SAY(cYEL "\x1b[H" "skipfish version " VERSION " by [email protected]\n\n" cBRI " -" cPIN " %s " cBRI "-\n\n" cNOR, allow_domains[0]); if (!display_mode) { http_stats(st_time); SAY("\n"); database_stats(); } else { http_req_list(); } SAY(" \r"); } if (fread(keybuf, 1, sizeof(keybuf), stdin) > 0) { display_mode ^= 1; clear_screen = 1; } } gettimeofday(&tv, NULL); en_time = tv.tv_sec * 1000LL + tv.tv_usec / 1000; SAY("\n"); if (stop_soon) SAY(cYEL "[!] " cBRI "Scan aborted by user, bailing out!" cNOR "\n"); term.c_lflag |= ICANON; tcsetattr(0, TCSANOW, &term); fcntl(0, F_SETFL, O_SYNC); save_keywords((u8*)wordlist); write_report(output_dir, en_time - st_time, seed); #ifdef LOG_STDERR SAY("\n== PIVOT DEBUG ==\n"); dump_pivots(0, 0); SAY("\n== END OF DUMP ==\n\n"); #endif /* LOG_STDERR */ SAY(cLGN "[+] " cBRI "This was a great day for science!" cRST "\n\n"); #ifdef DEBUG_ALLOCATOR if (!stop_soon) { destroy_database(); destroy_signature_lists(); destroy_http(); destroy_signatures(); __TRK_report(); } #endif /* DEBUG_ALLOCATOR */ fflush(0); EVP_cleanup(); CRYPTO_cleanup_all_ex_data(); return 0; }
int main(int argc, char **argv) { int i, n; static struct option const long_opts[] = { {"out", required_argument, NULL, 1}, {"report", required_argument, NULL, 2}, {"dotasref", no_argument, NULL, 3}, {"help", no_argument, NULL, 0}, {"version", no_argument, NULL, 4}, {"export_uncov", no_argument, NULL, 5} }; bool help = FALSE; bool report_version = FALSE; while ((n = getopt_long(argc, argv, "1:2:304", long_opts, NULL)) >= 0) { switch (n) { case 1 : outfile = strdup(optarg); break; case 2 : report = strdup(optarg); break; case 3 : dotasref = TRUE; break; case 0 : help = TRUE; break; case 4 : report_version = TRUE; break; case 5 : export_uncover = TRUE; break; default : return 1; } if ( help ) return usage(); if ( report_version ) return show_version(); } n = argc - optind; if ( n > 1 ) errabort("only accept one input vcf"); if ( export_uncover == TRUE && outfile == FALSE) { warnings("export uncove region only used with option --out"); export_uncover = FALSE; } char * input; if ( n == 0 ) input = strdup("-"); else input = strdup(argv[optind]); htsFile * fp = read_vcf_file(input); enum htsExactFormat fmt = hts_get_format(fp)->format; if ( fmt != vcf && fmt != bcf ) errabort("This is not a VCF/BCF file : %s", input); bcf_hdr_t * hdr = bcf_hdr_read(fp); int n_samples = bcf_hdr_nsamples(hdr); if ( n_samples != 2 ) errabort("the input VCF/BCF file must contain only two samples! %d", n_samples); LOG("Using sample %s as ref ...", hdr->samples[0]); LOG("Using sample %s as test ...", hdr->samples[1]); uint32_t matrix[4][4] = { {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0} }; bcf1_t * v = bcf_init1(); kstring_t str = { 0, 0, 0 }; uint32_t line = 0; htsFile *out = NULL; if ( outfile && !check_filename(outfile) ) out = hts_open(outfile, mode); if ( out != NULL ) bcf_hdr_write(out, hdr); while ( bcf_read1(fp, hdr, v) >= 0 ) { bcf_unpack(v, BCF_UN_STR|BCF_UN_FMT); int k; str.l = 0; int tag_id = bcf_hdr_id2int(hdr, BCF_DT_ID, "GT"); if ( !bcf_hdr_idinfo_exists(hdr, BCF_HL_FMT, tag_id) ) warnings("There is no 'GT' in the header!"); for ( i = 0; i < v->n_fmt; ++i ) if ( v->d.fmt[i].id == tag_id ) break; if ( i == v->n_fmt ) { vcf_format1(hdr, v, &str); LOG("There is no tag GT in this line : %s", str.s); continue; } corr_t xy[2] = { {-1, -2, -2}, {-1, -2, -2} }; bcf_fmt_t * fmt = &v->d.fmt[i]; for ( i = 0; i < 2; ++i ) { int corr = i; if ( fmt == NULL ) { if ( dotasref == TRUE ) xy[corr].alt = ALT_IS_REF; else xy[corr].alt = ALT_IS_UNC; continue; } int last = -2; uint8_t *d = (uint8_t*)((char*)fmt->p + fmt->size*i); for ( k = 0; k < fmt->n && d[k] != (uint8_t)bcf_int8_vector_end; ++k ) { int curr = d[k]>>1; if ( last != curr ) { if ( curr ) { if ( last == -2 ) xy[corr].alt = curr > 1 ? ALT_IS_HOM : ALT_IS_REF; else xy[corr].alt = ALT_IS_HET; } else { xy[corr].alt = dotasref == TRUE ? ALT_IS_REF : ALT_IS_UNC; } } else { if ( curr ) { xy[corr].alt = curr > 1 ? ALT_IS_HOM : ALT_IS_REF; } else { xy[corr].alt = dotasref == TRUE ? ALT_IS_REF : ALT_IS_UNC; } } if (last == -2 ) { xy[corr].min = xy[corr].max = curr; } else { if ( curr < xy[corr].min ) xy[corr].min = curr; else if ( curr > xy[corr].max ) xy[corr].max = curr; } last = curr; } } matrix[xy[0].alt][xy[1].alt]++; if ( xy[0].alt != xy[1].alt && out != NULL) { if ( xy[0].alt == ALT_IS_UNC || xy[1].alt == ALT_IS_UNC ) { if ( export_uncover == TRUE ) { str.l = 0; vcf_format1(hdr, v, &str); vcf_write(out, hdr, v); } } else { str.l = 0; vcf_format1(hdr, v, &str); vcf_write(out, hdr, v); } } if ( xy[0].alt == ALT_IS_HET && xy[1].alt == ALT_IS_HET && (xy[0].min != xy[1].min || xy[0].max != xy[1].max ) ) { bias++; matrix[ALT_IS_HET][ALT_IS_HET]--; if ( out != NULL ) { str.l = 0; vcf_format1(hdr, v, &str); vcf_write(out, hdr, v); } } line++; } if ( out ) hts_close(out); if ( str.m ) free(str.s); write_report(matrix, hdr); bcf_hdr_destroy(hdr); free(input); bcf_destroy1(v); if ( outfile ) free(outfile); if ( report ) free(report); if ( hts_close(fp) ) warnings("hts_close returned non-zero status: %s", input); return 0; }
void t_log::write_report(const string &report, const string &func_name) { write_report(report, func_name, LOG_NORMAL, LOG_INFO); }
/** * Sleeps in millisecond increments. * * @param milliseconds number of milliseconds to sleep for. */ void millisleep(long milliseconds) { // convert millis to seconds and nanos long seconds = (long) (milliseconds / 1000L); long nanos = (milliseconds - seconds * 1000) * 1000000; struct timespec ts = { .tv_sec = (size_t) seconds, .tv_nsec = nanos }; nanosleep(&ts, NULL); } void write_report(char* report, FILE* file) { // send key if (fwrite(report, (size_t) 1, sizeof(report), file) != sizeof(report)) err(ERR_CANNOT_WRITE_HID, false, true); fflush(file); // send empty key memset(report, 0x0, 8); if (fwrite(report, (size_t) 1, sizeof(report), file) != sizeof(report)) err(ERR_CANNOT_WRITE_HID, false, true); fflush(file); } uint32_t map_escape(const char *token) { if (!strcmp(token, "ALT")) return ALT; else if (!strcmp(token, "BACKSPACE")) return BACKSPACE; else if (!strcmp(token, "CONTROL")) return CONTROL; else if (!strcmp(token, "CTRL")) return CONTROL; else if (!strcmp(token, "DELETE")) return DELETE; else if (!strcmp(token, "ESCAPE")) return ESCAPE; else if (!strcmp(token, "END")) return END; else if (!strcmp(token, "GUI") || !strcmp(token, "WINDOWS")) return GUI; else if (!strcmp(token, "HOME")) return HOME; else if (!strcmp(token, "INSERT")) return INSERT; else if (!strcmp(token, "DOWNARROW") || !strcmp(token, "DOWN")) return DARROW; else if (!strcmp(token, "UPARROW") || !strcmp(token, "UP")) return UARROW; else if (!strcmp(token, "LEFTARROW") || !strcmp(token, "LEFT")) return LARROW; else if (!strcmp(token, "RIGHTARROW") || !strcmp(token, "RIGHT")) return RARROW; else if (!strcmp(token, "ENTER")) return ENTER; else if (!strcmp(token, "SPACE")) return SPACE; else if (!strcmp(token, "PRINTSCREEN")) return PRNTSCRN; else if (!strcmp(token, "SCROLLLOCK")) return SCRLLCK; else if (!strcmp(token, "MENU")) return MENU; else if (!strcmp(token, "APP")) return MENU; else if (!strcmp(token, "SHIFT")) return SHIFT; else if (!strcmp(token, "TAB")) return TAB; else if (!strcmp(token, "CAPSLOCK")) return CAPSLOCK; else if (!strcmp(token, "PAUSE")) return PAUSE; else if (!strcmp(token, "NUMLOCK")) return NUMLOCK; else if (!strcmp(token, "PAGEDOWN")) return PAGEDOWN; else if (!strcmp(token, "PAGEUP")) return PAGEUP; else if (!strcmp(token, "CLEAR")) return CLEAR; else if (!strcmp(token, "F1")) return F1; else if (!strcmp(token, "F2")) return F2; else if (!strcmp(token, "F3")) return F3; else if (!strcmp(token, "F4")) return F4; else if (!strcmp(token, "F5")) return F5; else if (!strcmp(token, "F6")) return F6; else if (!strcmp(token, "F7")) return F7; else if (!strcmp(token, "F8")) return F8; else if (!strcmp(token, "F9")) return F9; else if (!strcmp(token, "F10")) return F10; else if (!strcmp(token, "F11")) return F11; else if (!strcmp(token, "F12")) return F12; else return 0; } /* State variables for parser */ long defdelay = 0; /** * Parses an ArmoryDuckyScript, generates HID reports * accordingly and writes them to the output file. * * @param scriptfile FILE pointer to script file * @param outfile FILE pointer to write generated reports to. */ void parse(FILE* scriptfile, FILE* file) { char report[8]; char line[501]; char *command; // loop over lines in file while (fgets(line, sizeof(line), scriptfile)) { if (strlen(line) > 1) printf("%s", line); command = strtok(line, " \n"); if (command == NULL || !strcmp(command, "REM") || !strcmp(command, "#")) continue; // clear HID report memset(report, 0x0, sizeof(report)); if (!strcmp(command, "DEFAULT_DELAY") || !strcmp(command, "DEFAULTDELAY")) { if (sscanf(strtok(NULL, " "), "%ld", &defdelay) == 0) err(ERR_INVALID_TOKEN, false, false); continue; } if (!strcmp(command, "DELAY")) { int delay = 0; if (sscanf(strtok(NULL, " \n"), "%d", &delay) == 0) { err(ERR_INVALID_TOKEN, false, false); continue; } millisleep(delay); } else if (!strcmp(command, "STRING")) { char *str = strtok(NULL, "\n"); if (str == NULL) { err(ERR_INVALID_TOKEN, false, false); continue; } // send each character one by one int index = 0; while (index < strlen(str)) { uint32_t codepoint = 0; // read next UTF-8 char if(!(codepoint = getCodepoint(str, &index))) err(ERR_BAD_UNICODE, false, true); if (make_hid_report(report, 0, 1, codepoint)) { char *prefix = "No mapping for character:"; char *message = malloc(strlen(prefix) + 16); sprintf(message, "%s %c (U+%04x)", prefix, codepoint, codepoint); err(message, false, false); free(message); continue; } write_report(report, file); } } else if (!strcmp(command, "SIMUL")) { // parse up to six arguments to be sent simultaneously uint32_t simuls[6]; char *param = NULL; bool escapes_done = false, invalid = false; int i = 0, num_escapes = 0; for (; i < sizeof(simuls); i++) { param = strtok(NULL, " \n"); if (param == NULL) break; int index = 0; uint32_t nextCodepoint = getCodepoint(param, &index); // if the token is a single character, save and move on if (index == strlen(param)) { simuls[i] = nextCodepoint; escapes_done = true; } // if it's not a single character, it should be an escape token else { char esc; if (escapes_done || (esc = map_escape(param)) == 0) { invalid = true; break; } // add to report and move on simuls[i] = esc; num_escapes++; } } // skip line if invalid token was encountered if (invalid) { err(ERR_INVALID_TOKEN, false, false); continue; } make_hid_report_arr(report, num_escapes, i, simuls); write_report(report, file); } // if it wasn't anything else, try to map token to an escape else { char esc = map_escape(command); if (esc == 0) { err(ERR_INVALID_TOKEN, false, false); continue; } make_hid_report(report, 1, 1, esc); write_report(report, file); } millisleep(defdelay); } }
int main(int argc, char *argv[]) { static char report[1024]; printf("PJSIP Performance Measurement Tool v%s\n" "(c)2006 pjsip.org\n\n", PJ_VERSION); if (create_app() != 0) return 1; if (init_options(argc, argv) != 0) return 1; if (init_sip() != 0) return 1; if (init_media() != 0) return 1; pj_log_set_level(app.log_level); if (app.log_level > 4) { pjsip_endpt_register_module(app.sip_endpt, &msg_logger); } /* Misc infos */ if (app.client.dst_uri.slen != 0) { if (app.client.method.id == PJSIP_INVITE_METHOD) { if (app.client.stateless) { PJ_LOG(3,(THIS_FILE, "Info: --stateless option makes no sense for INVITE," " ignored.")); } } } if (app.client.dst_uri.slen) { /* Client mode */ pj_status_t status; char test_type[64]; unsigned msec_req, msec_res; unsigned i; /* Get the job name */ if (app.client.method.id == PJSIP_INVITE_METHOD) { pj_ansi_strcpy(test_type, "INVITE calls"); } else if (app.client.stateless) { pj_ansi_sprintf(test_type, "stateless %.*s requests", (int)app.client.method.name.slen, app.client.method.name.ptr); } else { pj_ansi_sprintf(test_type, "stateful %.*s requests", (int)app.client.method.name.slen, app.client.method.name.ptr); } printf("Sending %d %s to '%.*s' with %d maximum outstanding jobs, please wait..\n", app.client.job_count, test_type, (int)app.client.dst_uri.slen, app.client.dst_uri.ptr, app.client.job_window); for (i=0; i<app.thread_count; ++i) { status = pj_thread_create(app.pool, NULL, &client_thread, (void*)(long)i, 0, 0, &app.thread[i]); if (status != PJ_SUCCESS) { app_perror(THIS_FILE, "Unable to create thread", status); return 1; } } for (i=0; i<app.thread_count; ++i) { pj_thread_join(app.thread[i]); app.thread[i] = NULL; } if (app.client.last_completion.sec) { pj_time_val duration; duration = app.client.last_completion; PJ_TIME_VAL_SUB(duration, app.client.first_request); msec_res = PJ_TIME_VAL_MSEC(duration); } else { msec_res = app.client.timeout * 1000; } if (msec_res == 0) msec_res = 1; if (app.client.requests_sent.sec) { pj_time_val duration; duration = app.client.requests_sent; PJ_TIME_VAL_SUB(duration, app.client.first_request); msec_req = PJ_TIME_VAL_MSEC(duration); } else { msec_req = app.client.timeout * 1000; } if (msec_req == 0) msec_req = 1; if (app.client.job_submitted < app.client.job_count) puts("\ntimed-out!\n"); else puts("\ndone.\n"); pj_ansi_snprintf( report, sizeof(report), "Total %d %s sent in %d ms at rate of %d/sec\n" "Total %d responses receieved in %d ms at rate of %d/sec:", app.client.job_submitted, test_type, msec_req, app.client.job_submitted * 1000 / msec_req, app.client.total_responses, msec_res, app.client.total_responses*1000/msec_res); write_report(report); /* Print detailed response code received */ pj_ansi_sprintf(report, "\nDetailed responses received:"); write_report(report); for (i=0; i<PJ_ARRAY_SIZE(app.client.response_codes); ++i) { const pj_str_t *reason; if (app.client.response_codes[i] == 0) continue; reason = pjsip_get_status_text(i); pj_ansi_snprintf( report, sizeof(report), " - %d responses: %7d (%.*s)", i, app.client.response_codes[i], (int)reason->slen, reason->ptr); write_report(report); } /* Total responses and rate */ pj_ansi_snprintf( report, sizeof(report), " ------\n" " TOTAL responses: %7d (rate=%d/sec)\n", app.client.total_responses, app.client.total_responses*1000/msec_res); write_report(report); pj_ansi_sprintf(report, "Maximum outstanding job: %d", app.client.stat_max_window); write_report(report); } else { /* Server mode */ char s[10], *unused; pj_status_t status; unsigned i; puts("pjsip-perf started in server-mode"); printf("Receiving requests on the following URIs:\n" " sip:0@%.*s:%d%s for stateless handling\n" " sip:1@%.*s:%d%s for stateful handling\n" " sip:2@%.*s:%d%s for call handling\n", (int)app.local_addr.slen, app.local_addr.ptr, app.local_port, (app.use_tcp ? ";transport=tcp" : ""), (int)app.local_addr.slen, app.local_addr.ptr, app.local_port, (app.use_tcp ? ";transport=tcp" : ""), (int)app.local_addr.slen, app.local_addr.ptr, app.local_port, (app.use_tcp ? ";transport=tcp" : "")); printf("INVITE with non-matching user part will be handled call-statefully\n"); for (i=0; i<app.thread_count; ++i) { status = pj_thread_create(app.pool, NULL, &server_thread, (void*)(long)i, 0, 0, &app.thread[i]); if (status != PJ_SUCCESS) { app_perror(THIS_FILE, "Unable to create thread", status); return 1; } } puts("\nPress <ENTER> to quit\n"); fflush(stdout); unused = fgets(s, sizeof(s), stdin); PJ_UNUSED_ARG(unused); app.thread_quit = PJ_TRUE; for (i=0; i<app.thread_count; ++i) { pj_thread_join(app.thread[i]); app.thread[i] = NULL; } puts(""); } destroy_app(); return 0; }
// be careful to avoid using any non-trivial C runtime functions here! // C runtime structures may be already corrupted and unusable at this point. LONG WINAPI Sys_ExceptionFilter(LPEXCEPTION_POINTERS exceptionInfo) { STACKFRAME64 stackFrame; PEXCEPTION_RECORD exception; PCONTEXT context; DWORD64 pc; SYMBOL_INFO *symbol; int count, ret, i; DWORD64 offset; BYTE buffer[sizeof(SYMBOL_INFO) + 256 - 1]; IMAGEHLP_MODULE64 moduleInfo; char path[MAX_PATH]; char execdir[MAX_PATH]; HMODULE moduleHandle; SYSTEMTIME systemTime; OSVERSIONINFO vinfo; DWORD len; LONG action; // give previous filter a chance to handle this exception if (prevExceptionFilter) { action = prevExceptionFilter(exceptionInfo); if (action != EXCEPTION_CONTINUE_SEARCH) { return action; } } // debugger present? not our business if (IsDebuggerPresent()) { return EXCEPTION_CONTINUE_SEARCH; } // called from different thread? not our business if (GetCurrentThread() != mainProcessThread) { return EXCEPTION_CONTINUE_SEARCH; } #if USE_CLIENT Win_Shutdown(); #endif ret = MessageBox(NULL, PRODUCT " has encountered an unhandled " "exception and needs to be terminated.\n" "Would you like to generate a crash report?", CRASH_TITLE, MB_ICONERROR | MB_YESNO #if !USE_CLIENT | MB_SERVICE_NOTIFICATION #endif ); if (ret == IDNO) { return EXCEPTION_EXECUTE_HANDLER; } #define LL(x) \ do { \ moduleHandle = LoadLibrary(x); \ if (!moduleHandle) { \ return EXCEPTION_CONTINUE_SEARCH; \ } \ } while(0) #define GPA(x, y) \ do { \ p##y = (x)GetProcAddress(moduleHandle, #y); \ if (!p##y) { \ return EXCEPTION_CONTINUE_SEARCH; \ } \ } while(0) LL("dbghelp.dll"); GPA(SETSYMOPTIONS, SymSetOptions); GPA(SYMGETMODULEINFO64, SymGetModuleInfo64); GPA(SYMCLEANUP, SymCleanup); GPA(SYMINITIALIZE, SymInitialize); GPA(ENUMERATELOADEDMODULES64, EnumerateLoadedModules64); GPA(STACKWALK64, StackWalk64); GPA(SYMFROMADDR, SymFromAddr); GPA(SYMFUNCTIONTABLEACCESS64, SymFunctionTableAccess64); GPA(SYMGETMODULEBASE64, SymGetModuleBase64); LL("version.dll"); GPA(GETFILEVERSIONINFOA, GetFileVersionInfoA); GPA(VERQUERYVALUEA, VerQueryValueA); LL("shell32.dll"); GPA(SHELLEXECUTEA, ShellExecuteA); // get base directory to save crash dump to len = GetModuleFileName(NULL, execdir, sizeof(execdir)); if (!len || len >= sizeof(execdir)) { return EXCEPTION_CONTINUE_SEARCH; } while (--len) { if (execdir[len] == '\\') { break; } } if (!len || len + 24 >= MAX_PATH) { return EXCEPTION_CONTINUE_SEARCH; } execdir[len] = 0; CopyMemory(path, execdir, len); CopyMemory(path + len, "\\Q2PRO_CrashReportXX.txt", 25); for (i = 0; i < 100; i++) { path[len + 18] = '0' + i / 10; path[len + 19] = '0' + i % 10; crashReport = CreateFile( path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (crashReport != INVALID_HANDLE_VALUE) { break; } if (GetLastError() != ERROR_FILE_EXISTS) { MessageBox(NULL, "Couldn't create crash report. " "Base directory is not writable.", CRASH_TITLE, MB_ICONERROR); return EXCEPTION_EXECUTE_HANDLER; } } if (i == 100) { MessageBox(NULL, "Couldn't create crash report. " "All report slots are full.\n" "Please remove existing reports from base directory.", CRASH_TITLE, MB_ICONERROR); return EXCEPTION_EXECUTE_HANDLER; } pSymSetOptions( SYMOPT_LOAD_ANYTHING | SYMOPT_DEBUG | SYMOPT_FAIL_CRITICAL_ERRORS); processHandle = GetCurrentProcess(); threadHandle = GetCurrentThread(); pSymInitialize(processHandle, execdir, TRUE); GetSystemTime(&systemTime); write_report( "Crash report generated %s %u %u, %02u:%02u:%02u UTC\r\n", monthNames[(systemTime.wMonth - 1) % 12], systemTime.wDay, systemTime.wYear, systemTime.wHour, systemTime.wMinute, systemTime.wSecond); write_report( "by " APPLICATION " " VERSION ", built " __DATE__", " __TIME__ "\r\n"); vinfo.dwOSVersionInfoSize = sizeof(vinfo); if (GetVersionEx(&vinfo)) { write_report( "\r\nWindows version: %u.%u (build %u) %s\r\n", vinfo.dwMajorVersion, vinfo.dwMinorVersion, vinfo.dwBuildNumber, vinfo.szCSDVersion); } else { write_report("GetVersionEx failed with error %#x\r\n", GetLastError()); } // oh no, dbghelp is not backwards and forwards compatible // why in hell is it different from other windows DLLs? for (i = 0; i < 4; i++) { len = tryModuleSizes[i]; if (i && len >= sizeof(moduleInfo)) { continue; } moduleInfo.SizeOfStruct = len; if (pSymGetModuleInfo64( processHandle, (DWORD64)((INT_PTR)hGlobalInstance), &moduleInfo)) { moduleInfoSize = len; if (i) { write_report( "Module info size is %u (not %u)\r\n", len, tryModuleSizes[0]); } break; } } if (i == 4) { // bad luck write_report("SymGetModuleInfo64 is f****d up :("); moduleInfoSize = sizeof(moduleInfo); } CopyMemory(faultyModuleName, "unknown", 8); exception = exceptionInfo->ExceptionRecord; context = exceptionInfo->ContextRecord; #ifdef _WIN64 pc = context->Rip; #else pc = (DWORD64)context->Eip; #endif write_report("\r\nLoaded modules:\r\n"); ret = pEnumerateLoadedModules64( processHandle, enum_modules_callback, &pc ); if (!ret) { write_report("EnumerateLoadedModules64 failed with error %#x\r\n", GetLastError()); } write_report("\r\nException information:\r\n"); write_report("Code: %#08x\r\n", exception->ExceptionCode); write_report("Address: %"PRIxx" (%s)\r\n", WORDxx(pc), faultyModuleName); write_report("\r\nThread context:\r\n"); #ifdef _WIN64 write_report("RIP: %"PRIxx64" RBP: %"PRIxx64" RSP: %"PRIxx64"\r\n", context->Rip, context->Rbp, context->Rsp); write_report("RAX: %"PRIxx64" RBX: %"PRIxx64" RCX: %"PRIxx64"\r\n", context->Rax, context->Rbx, context->Rcx); write_report("RDX: %"PRIxx64" RSI: %"PRIxx64" RDI: %"PRIxx64"\r\n", context->Rdx, context->Rsi, context->Rdi); write_report("R8 : %"PRIxx64" R9 : %"PRIxx64" R10: %"PRIxx64"\r\n", context->R8, context->R9, context->R10); write_report("R11: %"PRIxx64" R12: %"PRIxx64" R13: %"PRIxx64"\r\n", context->R11, context->R12, context->R13); write_report("R14: %"PRIxx64" R15: %"PRIxx64"\r\n", context->R14, context->R15); #else write_report("EIP: %"PRIxx32" EBP: %"PRIxx32" ESP: %"PRIxx32"\r\n", context->Eip, context->Ebp, context->Esp); write_report("EAX: %"PRIxx32" EBX: %"PRIxx32" ECX: %"PRIxx32"\r\n", context->Eax, context->Ebx, context->Ecx); write_report("EDX: %"PRIxx32" ESI: %"PRIxx32" EDI: %"PRIxx32"\r\n", context->Edx, context->Esi, context->Edi); #endif ZeroMemory(&stackFrame, sizeof(stackFrame)); #ifdef _WIN64 stackFrame.AddrPC.Offset = context->Rip; stackFrame.AddrFrame.Offset = context->Rbp; stackFrame.AddrStack.Offset = context->Rsp; #else stackFrame.AddrPC.Offset = context->Eip; stackFrame.AddrFrame.Offset = context->Ebp; stackFrame.AddrStack.Offset = context->Esp; #endif stackFrame.AddrPC.Mode = AddrModeFlat; stackFrame.AddrFrame.Mode = AddrModeFlat; stackFrame.AddrStack.Mode = AddrModeFlat; write_report("\r\nStack trace:\r\n"); count = 0; symbol = (SYMBOL_INFO *)buffer; symbol->SizeOfStruct = sizeof(SYMBOL_INFO); symbol->MaxNameLen = 256; while (pStackWalk64( #ifdef _WIN64 IMAGE_FILE_MACHINE_AMD64, #else IMAGE_FILE_MACHINE_I386, #endif processHandle, threadHandle, &stackFrame, context, NULL, pSymFunctionTableAccess64, pSymGetModuleBase64, NULL)) { write_report( "%d: %"PRIxx" %"PRIxx" %"PRIxx" %"PRIxx" ", count, WORDxx(stackFrame.Params[0]), WORDxx(stackFrame.Params[1]), WORDxx(stackFrame.Params[2]), WORDxx(stackFrame.Params[3])); moduleInfo.SizeOfStruct = moduleInfoSize; if (pSymGetModuleInfo64( processHandle, stackFrame.AddrPC.Offset, &moduleInfo)) { if (moduleInfo.SymType != SymNone && moduleInfo.SymType != SymExport && pSymFromAddr( processHandle, stackFrame.AddrPC.Offset, &offset, symbol)) { write_report("%s!%s+%"PRIxx32"\r\n", moduleInfo.ModuleName, symbol->Name, (DWORD32)offset); } else { write_report("%s!%"PRIxx"\r\n", moduleInfo.ModuleName, WORDxx(stackFrame.AddrPC.Offset)); } } else { write_report("%"PRIxx"\r\n", WORDxx(stackFrame.AddrPC.Offset)); } count++; } CloseHandle(crashReport); pSymCleanup(processHandle); pShellExecuteA(NULL, "open", path, NULL, execdir, SW_SHOW); return EXCEPTION_EXECUTE_HANDLER; }
STATIC BOOL CALLBACK enum_modules_callback( PCSTR ModuleName, DWORD64 ModuleBase, ULONG ModuleSize, PVOID UserContext) { IMAGEHLP_MODULE64 moduleInfo; DWORD64 pc = *(DWORD64 *)UserContext; BYTE buffer[4096]; PBYTE data; UINT numBytes; VS_FIXEDFILEINFO *info; char version[64]; char *symbols, *star; int len; BOOL ret; len = lstrlen(ModuleName); if (len >= MAX_PATH) { return TRUE; } if (pGetFileVersionInfoA(ModuleName, 0, sizeof(buffer), buffer) && pVerQueryValueA(buffer, "\\", (LPVOID *)&data, &numBytes) && numBytes >= sizeof(*info)) { info = (VS_FIXEDFILEINFO *)data; wsprintf(version, "%u.%u.%u.%u", HIWORD(info->dwFileVersionMS), LOWORD(info->dwFileVersionMS), HIWORD(info->dwFileVersionLS), LOWORD(info->dwFileVersionLS)); } else { CopyMemory(version, "unknown", 8); } moduleInfo.SizeOfStruct = moduleInfoSize; ret = pSymGetModuleInfo64( processHandle, ModuleBase, &moduleInfo); if (ret) { ModuleName = moduleInfo.ModuleName; switch (moduleInfo.SymType) { case SymNone: symbols = "none"; break; case SymCoff: symbols = "COFF"; break; case SymPdb: symbols = "PDB"; break; case SymExport: symbols = "export"; break; case SymVirtual: symbols = "virtual"; break; default: symbols = "unknown"; break; } } else { write_report("SymGetModuleInfo64 failed with error %#x\r\n", GetLastError()); symbols = "failed"; } if (pc >= ModuleBase && pc < ModuleBase + ModuleSize) { CopyMemory(faultyModuleName, ModuleName, len + 1); star = " *"; } else { star = ""; } write_report( "%"PRIxx" %"PRIxx" %s (version %s, symbols %s)%s\r\n", WORDxx(ModuleBase), WORDxx(ModuleBase + ModuleSize), ModuleName, version, symbols, star); return TRUE; }