// Main int main(int argc, char **argv) { atexit(bye); #ifdef LINUX fl_open_display(); #endif //nouvelle userinterface I=new UserInterface; //créer et centrer le window principal main_window = I->make_window(); center(main_window); //about about = I->make_about(); I->about_button->callback(about_click); //construction des combos //taille automatique qui se trouvent dans taille[] //les ajoutent dans combo { int i=0; while(taille[i].str) { I->combo_taille->add(taille[i].str); i++; } } //sélectionner la première taille automatique I->combo_taille->value(0); //les tailles manuelles I->combo_mesure->add("Mo"); I->combo_mesure->add("Ko"); I->combo_mesure->add("Octet"); I->combo_mesure->value(0); I->taille->value(DEFAULT_TAILLE_MANUELLE); //callback I->btn_quitter->callback(btn_quitter_click); main_window->callback(btn_quitter_click); I->btn_browse_file->callback(btn_browse_file_click); I->btn_browse_dir->callback(btn_browse_dir_click); I->btn_about->callback(show_about); I->btn_split->callback(btn_split_click); I->rassembler->callback(rassembler_click); //les arguments passés au programme get_arguments(argc,argv); //Charger le fichier de configuration... load_config(); //show Fl::visual(FL_DOUBLE|FL_INDEX); { char *_argv[] = {argv[0],0}; main_window->show(1,_argv); } return Fl::run(); }
int main (int argc, char **argv) { logfilepath = getenv ("HOME"); logfilepath = strcat (logfilepath, "/.ooview.log"); load_config(); initscr(); raw(); noecho(); start_color(); keypad(stdscr,TRUE); init_pair(1, COLOR_WHITE, COLOR_BLACK); init_pair(2, COLOR_RED, COLOR_WHITE); init_pair(3, COLOR_BLUE, COLOR_WHITE); init_pair(4, COLOR_BLACK, COLOR_WHITE); bkgd(COLOR_PAIR(1)); curs_set(0); menu_bar = subwin(stdscr,1,COLS,0,0); wbkgd(menu_bar,COLOR_PAIR(2)); waddstr(menu_bar,"File"); wattron(menu_bar, COLOR_PAIR(3)); waddstr(menu_bar,"<F1>"); wattroff(menu_bar, COLOR_PAIR(3)); wmove(menu_bar, 0, 19); waddstr(menu_bar,"View"); wattron(menu_bar, COLOR_PAIR(3)); waddstr(menu_bar,"<F2>"); wattroff(menu_bar, COLOR_PAIR(3)); wmove(menu_bar, 0, 34); waddstr(menu_bar,"Options"); wattron(menu_bar, COLOR_PAIR(3)); waddstr(menu_bar,"<F3>"); wattroff(menu_bar, COLOR_PAIR(3)); wmove(menu_bar, 0, 53); waddstr(menu_bar,"Help"); wattron(menu_bar, COLOR_PAIR(3)); waddstr(menu_bar,"<F4>"); wattroff(menu_bar, COLOR_PAIR(3)); status_bar = subwin(stdscr,1,COLS,LINES-1,0); wbkgd(status_bar,COLOR_PAIR(4)); n_choices[0] = ARRAY_SIZE(file_choices); n_choices[1] = ARRAY_SIZE(view_choices); n_choices[2] = ARRAY_SIZE(opts_choices); n_choices[3] = ARRAY_SIZE(help_choices); file_items = (ITEM **)calloc(n_choices[0] + 1, sizeof(ITEM *)); view_items = (ITEM **)calloc(n_choices[1] + 1, sizeof(ITEM *)); opts_items = (ITEM **)calloc(n_choices[2] + 1, sizeof(ITEM *)); help_items = (ITEM **)calloc(n_choices[3] + 1, sizeof(ITEM *)); for (i=0; i<n_choices[0]; ++i) file_items[i] = new_item(file_choices[i], NULL); for (i=0; i<n_choices[1]; ++i) view_items[i] = new_item(view_choices[i], NULL); for (i=0; i<n_choices[2]; ++i) opts_items[i] = new_item(opts_choices[i], NULL); for (i=0; i<n_choices[3]; ++i) help_items[i] = new_item(help_choices[i], NULL); file_items[n_choices[0]] = (ITEM *)NULL; view_items[n_choices[1]] = (ITEM *)NULL; opts_items[n_choices[2]] = (ITEM *)NULL; help_items[n_choices[3]] = (ITEM *)NULL; file_menu = new_menu((ITEM **)file_items); view_menu = new_menu((ITEM **)view_items); opts_menu = new_menu((ITEM **)opts_items); help_menu = new_menu((ITEM **)help_items); set_menu_mark(file_menu, ""); set_menu_mark(view_menu, ""); set_menu_mark(opts_menu, ""); set_menu_mark(help_menu, ""); init_screen(); if (argc == 2) open_file(argv[1]); while ((c = getch()) != EXIT_KEY) { action_performed = false; switch (c) { case KEY_F(1): cur_menu=1; break; case KEY_F(2): cur_menu=2; break; case KEY_F(3): cur_menu=3; break; case KEY_F(4): cur_menu=4; break; case KEY_UP: if ((file_printed) && (buffer->cur_line > 1)) { int backsteps = 0; int steps; char *tmp; if ((*--cur_char)==NEWLINE) backsteps++; tmp = cur_char - 1; if ((*--cur_char) == NEWLINE) { cur_char = tmp; print_status_bar("yeah"); } else { do { cur_char--; backsteps++; } while (((*cur_char)!=NEWLINE) && (cur_char != buffer->content)); if (backsteps > COLS) { int test; test = backsteps/COLS; steps = (backsteps%COLS); if (test>1) steps += COLS; mvwprintw(status_bar,0,0,"%d",steps); touchwin(status_bar); wrefresh(status_bar); cur_char += backsteps; cur_char -= steps; } } buffer->cur_line--; print_site(buffer->cur_line, buffer->lines); if (cur_char!=buffer->content) print_file(buffer,++cur_char); else print_file(buffer,cur_char); } break; case KEY_DOWN: if ((file_printed) && (buffer->cur_line < buffer->lines)) { int cols=0; while (((*cur_char)!=NEWLINE) && (cols < COLS-1)) { cols++; cur_char++; } buffer->cur_line++; print_site(buffer->cur_line, buffer->lines); print_file(buffer,++cur_char); } break; default: if (meta_win!=NULL) { delwin(meta_win); touchwin(stdscr); refresh(); } } if (cur_menu == 1) { file_win = newwin(8,19,1,0); keypad(file_win,TRUE); box(file_win,0,0); set_menu_win(file_menu, file_win); set_menu_sub(file_menu, derwin(file_win,6,17,1,1)); post_menu(file_menu); while (c = wgetch(file_win)) { if (c == KEY_DOWN) menu_driver(file_menu, REQ_DOWN_ITEM); else if (c == KEY_UP) menu_driver(file_menu, REQ_UP_ITEM); else if (c == KEY_RIGHT) { cur_menu = 2; break; } else if (c == KEY_LEFT) { cur_menu = 4; break; } else if (c == RETURN) { cur_menu = 0; cmd = (char *)item_name(current_item(file_menu)); action_performed = true; break; } else { cur_menu = 0; break; } } unpost_menu(file_menu); touchwin(stdscr); wrefresh(stdscr); } if (cur_menu == 2) { view_win = newwin(6,15,1,19); keypad(view_win,TRUE); box(view_win,0,0); set_menu_win(view_menu, view_win); set_menu_sub(view_menu, derwin(view_win,4,13,1,1)); post_menu(view_menu); while (c = wgetch(view_win)) { if (c == KEY_DOWN) menu_driver(view_menu, REQ_DOWN_ITEM); else if (c == KEY_UP) menu_driver(view_menu, REQ_UP_ITEM); else if (c == KEY_RIGHT) { cur_menu = 3; break; } else if (c == KEY_LEFT) { cur_menu = 1; break; } else if (c == RETURN) { cur_menu = 0; cmd = (char *)item_name(current_item(view_menu)); action_performed = true; break; } else { cur_menu = 0; break; } } unpost_menu(view_menu); touchwin(stdscr); refresh(); } if (cur_menu == 3) { opts_win = newwin(5,19,1,34); keypad(opts_win,TRUE); box(opts_win,0,0); set_menu_win(opts_menu, opts_win); set_menu_sub(opts_menu, derwin(opts_win,3,17,1,1)); post_menu(opts_menu); while (c = wgetch(opts_win)) { if (c == KEY_DOWN) menu_driver(opts_menu, REQ_DOWN_ITEM); else if (c == KEY_UP) menu_driver(opts_menu, REQ_UP_ITEM); else if (c == KEY_RIGHT) { cur_menu = 4; break; } else if (c == KEY_LEFT) { cur_menu = 2; break; } else if (c == RETURN) { cur_menu = 0; cmd = (char *)item_name(current_item(opts_menu)); action_performed = true; break; } else { cur_menu = 0; break; } } unpost_menu(opts_menu); touchwin(stdscr); refresh(); } if (cur_menu == 4) { help_win = newwin(6,17,1,53); keypad(help_win,TRUE); box(help_win,0,0); set_menu_win(help_menu, help_win); set_menu_sub(help_menu, derwin(help_win,4,15,1,1)); post_menu(help_menu); while (c = wgetch(help_win)) { if (c == KEY_DOWN) menu_driver(help_menu, REQ_DOWN_ITEM); else if (c == KEY_UP) menu_driver(help_menu, REQ_UP_ITEM); else if (c == KEY_RIGHT) { cur_menu = 1; break; } else if (c == KEY_LEFT) { cur_menu = 3; break; } else if (c == RETURN) { cur_menu = 0; cmd = (char *)item_name(current_item(help_menu)); action_performed = true; break; } else { cur_menu = 0; break; } } unpost_menu(help_menu); touchwin(stdscr); refresh(); } if (action_performed) { char file[80]; clear_status_bar(); if (!strcmp(cmd,"Open")) { if (file_printed==false) { print_status_bar("Enter a file: "); curs_set(1); echo(); wscanw(status_bar,"%s",file); /* get filename from user */ curs_set(0); noecho(); open_file(file); } else { print_status_bar("Please close current file."); } } if (!strcmp(cmd,"Close")) { if (file_printed) { free(buffer); werase(main_win); init_screen(); wrefresh(main_win); file_printed = false; system("rm -rf /tmp/ooview"); } else { print_status_bar("No open file!"); } } if (!strcmp(cmd,"Reload")) { if (file_printed) { if (strstr(file,".ovd")!=NULL) /* ovd*/ { ovd_file = fopen(file,"r"); if (ovd_file != NULL) { free(buffer); buffer = (struct fileinfo *)malloc(sizeof(struct fileinfo)); main_win = subwin(stdscr,LINES-2,COLS,1,0); get_file_content(ovd_file, file, buffer); fclose(ovd_file); cur_char = buffer->content; print_site(buffer->cur_line, buffer->lines); print_file(buffer,cur_char); file_printed = true; } else { print_status_bar("File does not exist!"); } } else /* else if odt */ { free(buffer); buffer = (struct fileinfo *)malloc(sizeof(struct fileinfo)); main_win= subwin(stdscr,LINES-2,COLS,1,0); open_odt(file,buffer); get_file_meta("/tmp/ooview/meta.xml",buffer); cur_char = buffer->content; print_site(buffer->cur_line, buffer->lines); print_file(buffer,cur_char); file_printed = true; } } else { print_status_bar("No open file!"); } } if (!strcmp(cmd,"Document info")) { if (file_printed) { if (file_type==1) { meta_win = newwin(9,COLS-2,(LINES/2)-5,1); wbkgd(meta_win,COLOR_PAIR(4)); mvwprintw(meta_win,1,1,"Genarator: %s", buffer->generator); mvwprintw(meta_win,2,1,"Initial creator:\t%s", buffer->initial_creator); mvwprintw(meta_win,3,1,"Creation date:\t\t%s", buffer->creation_date); mvwprintw(meta_win,4,1,"Creator:\t\t%s", buffer->creator); mvwprintw(meta_win,5,1,"Date:\t\t\t%s", buffer->date); mvwprintw(meta_win,6,1,"Editing cycles:\t%s", buffer->editing_cycles); mvwprintw(meta_win,7,1,"Editing duration:\t%s", buffer->editing_duration); box(meta_win,0,0); wrefresh(meta_win); touchwin(meta_win); } } else { print_status_bar("No open file!"); } } if (!strcmp(cmd,"OOView homepage")) { char *syscall; syscall=(char *)malloc(strlen(BROWSER)+strlen(HOMEPAGE_URL)+1); sprintf(syscall, "%s %s", BROWSER, HOMEPAGE_URL); system(syscall); free(syscall); if (file_printed) free(buffer); end_curses(); return(0); } if (!strcmp(cmd,"Documentation")) { char *syscall; syscall=(char *)malloc(strlen(BROWSER)+strlen(HOMEPAGE_URL)+1); sprintf(syscall, "%s %s", BROWSER, HOMEPAGE_URL); system(syscall); free(syscall); if (file_printed) free(buffer); end_curses(); return(0); } if (!strcmp(cmd, "About OOView")) print_status_bar("OOView. Visit Homepage for details"); if (!strcmp(cmd, "Copying")) print_status_bar("OOView is under GPL/2 Visit Homepage for details"); if (!strcmp(cmd, "Find")) { if (file_printed) { print_status_bar("Enter string to find: "); char *findit; curs_set(1); echo(); wscanw(status_bar,"%s",findit); /* how to find a string in a string? find it -> set cursor to position */ print_status_bar("Not implemented yet :("); curs_set(0); noecho(); } else { print_status_bar("No open file!"); } } if (!strcmp(cmd, "External Programs")) { char *prompt; /*getting printer command*/ prompt = (char *)malloc((strlen("Enter Printing Command []: ")+strlen(PRINTER))); sprintf(prompt,"Enter Printing Command [%s]: ",PRINTER); print_status_bar(prompt); free(prompt); curs_set(1); echo(); char *newcmd; wscanw(status_bar,"%s",newcmd); curs_set(0); noecho(); print_status_bar(newcmd); /* / getting printer command*/ } if (!strcmp(cmd,"Exit")) { if (file_printed) free(buffer); end_curses(); return 0; } } } if (file_printed) free(buffer); end_curses(); return 0; }
int verify_main(int argc, char **argv) { ENGINE *e = NULL; int i, ret = 1, badarg = 0; char *CApath = NULL, *CAfile = NULL; char *untfile = NULL, *trustfile = NULL, *crlfile = NULL; STACK_OF(X509) * untrusted = NULL, *trusted = NULL; STACK_OF(X509_CRL) * crls = NULL; X509_STORE *cert_ctx = NULL; X509_LOOKUP *lookup = NULL; X509_VERIFY_PARAM *vpm = NULL; #ifndef OPENSSL_NO_ENGINE char *engine = NULL; #endif cert_ctx = X509_STORE_new(); if (cert_ctx == NULL) goto end; X509_STORE_set_verify_cb(cert_ctx, cb); ERR_load_crypto_strings(); apps_startup(); if (bio_err == NULL) if ((bio_err = BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT); if (!load_config(bio_err, NULL)) goto end; argc--; argv++; for (;;) { if (argc >= 1) { if (strcmp(*argv, "-CApath") == 0) { if (argc-- < 1) goto end; CApath = *(++argv); } else if (strcmp(*argv, "-CAfile") == 0) { if (argc-- < 1) goto end; CAfile = *(++argv); } else if (args_verify(&argv, &argc, &badarg, bio_err, &vpm)) { if (badarg) goto end; continue; } else if (strcmp(*argv, "-untrusted") == 0) { if (argc-- < 1) goto end; untfile = *(++argv); } else if (strcmp(*argv, "-trusted") == 0) { if (argc-- < 1) goto end; trustfile = *(++argv); } else if (strcmp(*argv, "-CRLfile") == 0) { if (argc-- < 1) goto end; crlfile = *(++argv); } #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv, "-engine") == 0) { if (--argc < 1) goto end; engine = *(++argv); } #endif else if (strcmp(*argv, "-help") == 0) goto end; else if (strcmp(*argv, "-verbose") == 0) v_verbose = 1; else if (argv[0][0] == '-') goto end; else break; argc--; argv++; } else break; } #ifndef OPENSSL_NO_ENGINE e = setup_engine(bio_err, engine, 0); #endif if (vpm) X509_STORE_set1_param(cert_ctx, vpm); lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file()); if (lookup == NULL) abort(); if (CAfile) { i = X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM); if (!i) { BIO_printf(bio_err, "Error loading file %s\n", CAfile); ERR_print_errors(bio_err); goto end; } } else X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT); lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir()); if (lookup == NULL) abort(); if (CApath) { i = X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM); if (!i) { BIO_printf(bio_err, "Error loading directory %s\n", CApath); ERR_print_errors(bio_err); goto end; } } else X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT); ERR_clear_error(); if (untfile) { untrusted = load_certs(bio_err, untfile, FORMAT_PEM, NULL, e, "untrusted certificates"); if (!untrusted) goto end; } if (trustfile) { trusted = load_certs(bio_err, trustfile, FORMAT_PEM, NULL, e, "trusted certificates"); if (!trusted) goto end; } if (crlfile) { crls = load_crls(bio_err, crlfile, FORMAT_PEM, NULL, e, "other CRLs"); if (!crls) goto end; } ret = 0; if (argc < 1) { if (1 != check(cert_ctx, NULL, untrusted, trusted, crls, e)) ret = -1; } else { for (i = 0; i < argc; i++) if (1 != check(cert_ctx, argv[i], untrusted, trusted, crls, e)) ret = -1; } end: if (ret == 1) { BIO_printf(bio_err, "usage: verify [-verbose] [-CApath path] [-CAfile file] [-purpose purpose] [-crl_check]"); BIO_printf(bio_err, " [-attime timestamp]"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, " [-engine e]"); #endif BIO_printf(bio_err, " cert1 cert2 ...\n"); BIO_printf(bio_err, "recognized usages:\n"); for (i = 0; i < X509_PURPOSE_get_count(); i++) { X509_PURPOSE *ptmp; ptmp = X509_PURPOSE_get0(i); BIO_printf(bio_err, "\t%-10s\t%s\n", X509_PURPOSE_get0_sname(ptmp), X509_PURPOSE_get0_name(ptmp)); } } if (vpm) X509_VERIFY_PARAM_free(vpm); if (cert_ctx != NULL) X509_STORE_free(cert_ctx); sk_X509_pop_free(untrusted, X509_free); sk_X509_pop_free(trusted, X509_free); sk_X509_CRL_pop_free(crls, X509_CRL_free); apps_shutdown(); return (ret < 0 ? 2 : ret); }
int ecparam_main(int argc, char **argv) { EC_GROUP *group = NULL; point_conversion_form_t form = POINT_CONVERSION_UNCOMPRESSED; int new_form = 0; int asn1_flag = OPENSSL_EC_NAMED_CURVE; int new_asn1_flag = 0; char *curve_name = NULL, *inrand = NULL; int list_curves = 0, no_seed = 0, check = 0, badops = 0, text = 0, i, genkey = 0; char *infile = NULL, *outfile = NULL, *prog; BIO *in = NULL, *out = NULL; int informat, outformat, noout = 0, C = 0, ret = 1; char *engine = NULL; BIGNUM *ec_p = NULL, *ec_a = NULL, *ec_b = NULL, *ec_gen = NULL, *ec_order = NULL, *ec_cofactor = NULL; unsigned char *buffer = NULL; signal(SIGPIPE, SIG_IGN); if (bio_err == NULL) if ((bio_err = BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT); if (!load_config(bio_err, NULL)) goto end; informat = FORMAT_PEM; outformat = FORMAT_PEM; prog = argv[0]; argc--; argv++; while (argc >= 1) { if (strcmp(*argv, "-inform") == 0) { if (--argc < 1) goto bad; informat = str2fmt(*(++argv)); } else if (strcmp(*argv, "-outform") == 0) { if (--argc < 1) goto bad; outformat = str2fmt(*(++argv)); } else if (strcmp(*argv, "-in") == 0) { if (--argc < 1) goto bad; infile = *(++argv); } else if (strcmp(*argv, "-out") == 0) { if (--argc < 1) goto bad; outfile = *(++argv); } else if (strcmp(*argv, "-text") == 0) text = 1; else if (strcmp(*argv, "-C") == 0) C = 1; else if (strcmp(*argv, "-check") == 0) check = 1; else if (strcmp(*argv, "-name") == 0) { if (--argc < 1) goto bad; curve_name = *(++argv); } else if (strcmp(*argv, "-list_curves") == 0) list_curves = 1; else if (strcmp(*argv, "-conv_form") == 0) { if (--argc < 1) goto bad; ++argv; new_form = 1; if (strcmp(*argv, "compressed") == 0) form = POINT_CONVERSION_COMPRESSED; else if (strcmp(*argv, "uncompressed") == 0) form = POINT_CONVERSION_UNCOMPRESSED; else if (strcmp(*argv, "hybrid") == 0) form = POINT_CONVERSION_HYBRID; else goto bad; } else if (strcmp(*argv, "-param_enc") == 0) { if (--argc < 1) goto bad; ++argv; new_asn1_flag = 1; if (strcmp(*argv, "named_curve") == 0) asn1_flag = OPENSSL_EC_NAMED_CURVE; else if (strcmp(*argv, "explicit") == 0) asn1_flag = 0; else goto bad; } else if (strcmp(*argv, "-no_seed") == 0) no_seed = 1; else if (strcmp(*argv, "-noout") == 0) noout = 1; else if (strcmp(*argv, "-genkey") == 0) { genkey = 1; } else if (strcmp(*argv, "-rand") == 0) { if (--argc < 1) goto bad; inrand = *(++argv); } else if (strcmp(*argv, "-engine") == 0) { if (--argc < 1) goto bad; engine = *(++argv); } else { BIO_printf(bio_err, "unknown option %s\n", *argv); badops = 1; break; } argc--; argv++; } if (badops) { bad: BIO_printf(bio_err, "%s [options] <infile >outfile\n", prog); BIO_printf(bio_err, "where options are\n"); BIO_printf(bio_err, " -inform arg input format - " "default PEM (DER or PEM)\n"); BIO_printf(bio_err, " -outform arg output format - " "default PEM\n"); BIO_printf(bio_err, " -in arg input file - " "default stdin\n"); BIO_printf(bio_err, " -out arg output file - " "default stdout\n"); BIO_printf(bio_err, " -noout do not print the " "ec parameter\n"); BIO_printf(bio_err, " -text print the ec " "parameters in text form\n"); BIO_printf(bio_err, " -check validate the ec " "parameters\n"); BIO_printf(bio_err, " -C print a 'C' " "function creating the parameters\n"); BIO_printf(bio_err, " -name arg use the " "ec parameters with 'short name' name\n"); BIO_printf(bio_err, " -list_curves prints a list of " "all currently available curve 'short names'\n"); BIO_printf(bio_err, " -conv_form arg specifies the " "point conversion form \n"); BIO_printf(bio_err, " possible values:" " compressed\n"); BIO_printf(bio_err, " " " uncompressed (default)\n"); BIO_printf(bio_err, " " " hybrid\n"); BIO_printf(bio_err, " -param_enc arg specifies the way" " the ec parameters are encoded\n"); BIO_printf(bio_err, " in the asn1 der " "encoding\n"); BIO_printf(bio_err, " possible values:" " named_curve (default)\n"); BIO_printf(bio_err, " " " explicit\n"); BIO_printf(bio_err, " -no_seed if 'explicit'" " parameters are chosen do not" " use the seed\n"); BIO_printf(bio_err, " -genkey generate ec" " key\n"); BIO_printf(bio_err, " -rand file files to use for" " random number input\n"); BIO_printf(bio_err, " -engine e use engine e, " "possibly a hardware device\n"); goto end; } ERR_load_crypto_strings(); in = BIO_new(BIO_s_file()); out = BIO_new(BIO_s_file()); if ((in == NULL) || (out == NULL)) { ERR_print_errors(bio_err); goto end; } if (infile == NULL) BIO_set_fp(in, stdin, BIO_NOCLOSE); else { if (BIO_read_filename(in, infile) <= 0) { perror(infile); goto end; } } if (outfile == NULL) { BIO_set_fp(out, stdout, BIO_NOCLOSE); } else { if (BIO_write_filename(out, outfile) <= 0) { perror(outfile); goto end; } } #ifndef OPENSSL_NO_ENGINE setup_engine(bio_err, engine, 0); #endif if (list_curves) { EC_builtin_curve *curves = NULL; size_t crv_len = 0; size_t n = 0; crv_len = EC_get_builtin_curves(NULL, 0); curves = malloc((int) (sizeof(EC_builtin_curve) * crv_len)); if (curves == NULL) goto end; if (!EC_get_builtin_curves(curves, crv_len)) { free(curves); goto end; } for (n = 0; n < crv_len; n++) { const char *comment; const char *sname; comment = curves[n].comment; sname = OBJ_nid2sn(curves[n].nid); if (comment == NULL) comment = "CURVE DESCRIPTION NOT AVAILABLE"; if (sname == NULL) sname = ""; BIO_printf(out, " %-10s: ", sname); BIO_printf(out, "%s\n", comment); } free(curves); ret = 0; goto end; } if (curve_name != NULL) { int nid; /* * workaround for the SECG curve names secp192r1 and * secp256r1 (which are the same as the curves prime192v1 and * prime256v1 defined in X9.62) */ if (!strcmp(curve_name, "secp192r1")) { BIO_printf(bio_err, "using curve name prime192v1 " "instead of secp192r1\n"); nid = NID_X9_62_prime192v1; } else if (!strcmp(curve_name, "secp256r1")) { BIO_printf(bio_err, "using curve name prime256v1 " "instead of secp256r1\n"); nid = NID_X9_62_prime256v1; } else nid = OBJ_sn2nid(curve_name); if (nid == 0) { BIO_printf(bio_err, "unknown curve name (%s)\n", curve_name); goto end; } group = EC_GROUP_new_by_curve_name(nid); if (group == NULL) { BIO_printf(bio_err, "unable to create curve (%s)\n", curve_name); goto end; } EC_GROUP_set_asn1_flag(group, asn1_flag); EC_GROUP_set_point_conversion_form(group, form); } else if (informat == FORMAT_ASN1) { group = d2i_ECPKParameters_bio(in, NULL); } else if (informat == FORMAT_PEM) { group = PEM_read_bio_ECPKParameters(in, NULL, NULL, NULL); } else { BIO_printf(bio_err, "bad input format specified\n"); goto end; } if (group == NULL) { BIO_printf(bio_err, "unable to load elliptic curve parameters\n"); ERR_print_errors(bio_err); goto end; } if (new_form) EC_GROUP_set_point_conversion_form(group, form); if (new_asn1_flag) EC_GROUP_set_asn1_flag(group, asn1_flag); if (no_seed) { EC_GROUP_set_seed(group, NULL, 0); } if (text) { if (!ECPKParameters_print(out, group, 0)) goto end; } if (check) { if (group == NULL) BIO_printf(bio_err, "no elliptic curve parameters\n"); BIO_printf(bio_err, "checking elliptic curve parameters: "); if (!EC_GROUP_check(group, NULL)) { BIO_printf(bio_err, "failed\n"); ERR_print_errors(bio_err); } else BIO_printf(bio_err, "ok\n"); } if (C) { size_t buf_len = 0, tmp_len = 0; const EC_POINT *point; int is_prime, len = 0; const EC_METHOD *meth = EC_GROUP_method_of(group); if ((ec_p = BN_new()) == NULL || (ec_a = BN_new()) == NULL || (ec_b = BN_new()) == NULL || (ec_gen = BN_new()) == NULL || (ec_order = BN_new()) == NULL || (ec_cofactor = BN_new()) == NULL) { perror("malloc"); goto end; } is_prime = (EC_METHOD_get_field_type(meth) == NID_X9_62_prime_field); if (is_prime) { if (!EC_GROUP_get_curve_GFp(group, ec_p, ec_a, ec_b, NULL)) goto end; } else { /* TODO */ goto end; } if ((point = EC_GROUP_get0_generator(group)) == NULL) goto end; if (!EC_POINT_point2bn(group, point, EC_GROUP_get_point_conversion_form(group), ec_gen, NULL)) goto end; if (!EC_GROUP_get_order(group, ec_order, NULL)) goto end; if (!EC_GROUP_get_cofactor(group, ec_cofactor, NULL)) goto end; if (!ec_p || !ec_a || !ec_b || !ec_gen || !ec_order || !ec_cofactor) goto end; len = BN_num_bits(ec_order); if ((tmp_len = (size_t) BN_num_bytes(ec_p)) > buf_len) buf_len = tmp_len; if ((tmp_len = (size_t) BN_num_bytes(ec_a)) > buf_len) buf_len = tmp_len; if ((tmp_len = (size_t) BN_num_bytes(ec_b)) > buf_len) buf_len = tmp_len; if ((tmp_len = (size_t) BN_num_bytes(ec_gen)) > buf_len) buf_len = tmp_len; if ((tmp_len = (size_t) BN_num_bytes(ec_order)) > buf_len) buf_len = tmp_len; if ((tmp_len = (size_t) BN_num_bytes(ec_cofactor)) > buf_len) buf_len = tmp_len; buffer = (unsigned char *) malloc(buf_len); if (buffer == NULL) { perror("malloc"); goto end; } ecparam_print_var(out, ec_p, "ec_p", len, buffer); ecparam_print_var(out, ec_a, "ec_a", len, buffer); ecparam_print_var(out, ec_b, "ec_b", len, buffer); ecparam_print_var(out, ec_gen, "ec_gen", len, buffer); ecparam_print_var(out, ec_order, "ec_order", len, buffer); ecparam_print_var(out, ec_cofactor, "ec_cofactor", len, buffer); BIO_printf(out, "\n\n"); BIO_printf(out, "EC_GROUP *get_ec_group_%d(void)\n\t{\n", len); BIO_printf(out, "\tint ok=0;\n"); BIO_printf(out, "\tEC_GROUP *group = NULL;\n"); BIO_printf(out, "\tEC_POINT *point = NULL;\n"); BIO_printf(out, "\tBIGNUM *tmp_1 = NULL, *tmp_2 = NULL, " "*tmp_3 = NULL;\n\n"); BIO_printf(out, "\tif ((tmp_1 = BN_bin2bn(ec_p_%d, " "sizeof(ec_p_%d), NULL)) == NULL)\n\t\t" "goto err;\n", len, len); BIO_printf(out, "\tif ((tmp_2 = BN_bin2bn(ec_a_%d, " "sizeof(ec_a_%d), NULL)) == NULL)\n\t\t" "goto err;\n", len, len); BIO_printf(out, "\tif ((tmp_3 = BN_bin2bn(ec_b_%d, " "sizeof(ec_b_%d), NULL)) == NULL)\n\t\t" "goto err;\n", len, len); if (is_prime) { BIO_printf(out, "\tif ((group = EC_GROUP_new_curve_" "GFp(tmp_1, tmp_2, tmp_3, NULL)) == NULL)" "\n\t\tgoto err;\n\n"); } else { /* TODO */ goto end; } BIO_printf(out, "\t/* build generator */\n"); BIO_printf(out, "\tif ((tmp_1 = BN_bin2bn(ec_gen_%d, " "sizeof(ec_gen_%d), tmp_1)) == NULL)" "\n\t\tgoto err;\n", len, len); BIO_printf(out, "\tpoint = EC_POINT_bn2point(group, tmp_1, " "NULL, NULL);\n"); BIO_printf(out, "\tif (point == NULL)\n\t\tgoto err;\n"); BIO_printf(out, "\tif ((tmp_2 = BN_bin2bn(ec_order_%d, " "sizeof(ec_order_%d), tmp_2)) == NULL)" "\n\t\tgoto err;\n", len, len); BIO_printf(out, "\tif ((tmp_3 = BN_bin2bn(ec_cofactor_%d, " "sizeof(ec_cofactor_%d), tmp_3)) == NULL)" "\n\t\tgoto err;\n", len, len); BIO_printf(out, "\tif (!EC_GROUP_set_generator(group, point," " tmp_2, tmp_3))\n\t\tgoto err;\n"); BIO_printf(out, "\n\tok=1;\n"); BIO_printf(out, "err:\n"); BIO_printf(out, "\tif (tmp_1)\n\t\tBN_free(tmp_1);\n"); BIO_printf(out, "\tif (tmp_2)\n\t\tBN_free(tmp_2);\n"); BIO_printf(out, "\tif (tmp_3)\n\t\tBN_free(tmp_3);\n"); BIO_printf(out, "\tif (point)\n\t\tEC_POINT_free(point);\n"); BIO_printf(out, "\tif (!ok)\n"); BIO_printf(out, "\t\t{\n"); BIO_printf(out, "\t\tEC_GROUP_free(group);\n"); BIO_printf(out, "\t\tgroup = NULL;\n"); BIO_printf(out, "\t\t}\n"); BIO_printf(out, "\treturn(group);\n\t}\n"); } if (!noout) { if (outformat == FORMAT_ASN1) i = i2d_ECPKParameters_bio(out, group); else if (outformat == FORMAT_PEM) i = PEM_write_bio_ECPKParameters(out, group); else { BIO_printf(bio_err, "bad output format specified for" " outfile\n"); goto end; } if (!i) { BIO_printf(bio_err, "unable to write elliptic " "curve parameters\n"); ERR_print_errors(bio_err); goto end; } } if (genkey) { EC_KEY *eckey = EC_KEY_new(); if (eckey == NULL) goto end; if (EC_KEY_set_group(eckey, group) == 0) goto end; if (!EC_KEY_generate_key(eckey)) { EC_KEY_free(eckey); goto end; } if (outformat == FORMAT_ASN1) i = i2d_ECPrivateKey_bio(out, eckey); else if (outformat == FORMAT_PEM) i = PEM_write_bio_ECPrivateKey(out, eckey, NULL, NULL, 0, NULL, NULL); else { BIO_printf(bio_err, "bad output format specified " "for outfile\n"); EC_KEY_free(eckey); goto end; } EC_KEY_free(eckey); } ret = 0; end: if (ec_p) BN_free(ec_p); if (ec_a) BN_free(ec_a); if (ec_b) BN_free(ec_b); if (ec_gen) BN_free(ec_gen); if (ec_order) BN_free(ec_order); if (ec_cofactor) BN_free(ec_cofactor); if (buffer) free(buffer); if (in != NULL) BIO_free(in); if (out != NULL) BIO_free_all(out); if (group != NULL) EC_GROUP_free(group); return (ret); }
int main(int argc, char **argv) { int i; int config_loaded = 0; int dont_fork = 0; size_t wanted_stacksize = 0, stacksize = 0; pthread_attr_t attr; // global initialization get_HZ(); // set the name for logging program_name = "netdata"; // parse the arguments for(i = 1; i < argc ; i++) { if(strcmp(argv[i], "-c") == 0 && (i+1) < argc) { if(load_config(argv[i+1], 1) != 1) { error("Cannot load configuration file %s.", argv[i+1]); exit(1); } else { debug(D_OPTIONS, "Configuration loaded from %s.", argv[i+1]); config_loaded = 1; } i++; } else if(strcmp(argv[i], "-df") == 0 && (i+1) < argc) { config_set("global", "debug flags", argv[i+1]); debug_flags = strtoull(argv[i+1], NULL, 0); i++; } else if(strcmp(argv[i], "-p") == 0 && (i+1) < argc) { config_set("global", "port", argv[i+1]); i++; } else if(strcmp(argv[i], "-u") == 0 && (i+1) < argc) { config_set("global", "run as user", argv[i+1]); i++; } else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) { config_set("global", "history", argv[i+1]); i++; } else if(strcmp(argv[i], "-t") == 0 && (i+1) < argc) { config_set("global", "update every", argv[i+1]); i++; } else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) { config_set("global", "host access prefix", argv[i+1]); i++; } else if(strcmp(argv[i], "-stacksize") == 0 && (i+1) < argc) { config_set("global", "pthread stack size", argv[i+1]); i++; } else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) dont_fork = 1; else if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) { i++; strncpy(pidfile, argv[i], FILENAME_MAX); pidfile[FILENAME_MAX] = '\0'; } else if(strcmp(argv[i], "--unittest") == 0) { rrd_update_every = 1; if(run_all_mockup_tests()) exit(1); if(unit_test_storage()) exit(1); fprintf(stderr, "\n\nALL TESTS PASSED\n\n"); exit(0); } else { fprintf(stderr, "Cannot understand option '%s'.\n", argv[i]); fprintf(stderr, "\nUSAGE: %s [-d] [-l LINES_TO_SAVE] [-u UPDATE_TIMER] [-p LISTEN_PORT] [-df debug flags].\n\n", argv[0]); fprintf(stderr, " -c CONFIG FILE the configuration file to load. Default: %s.\n", CONFIG_DIR "/" CONFIG_FILENAME); fprintf(stderr, " -l LINES_TO_SAVE can be from 5 to %d lines in JSON data. Default: %d.\n", RRD_HISTORY_ENTRIES_MAX, RRD_DEFAULT_HISTORY_ENTRIES); fprintf(stderr, " -t UPDATE_TIMER can be from 1 to %d seconds. Default: %d.\n", UPDATE_EVERY_MAX, UPDATE_EVERY); fprintf(stderr, " -p LISTEN_PORT can be from 1 to %d. Default: %d.\n", 65535, LISTEN_PORT); fprintf(stderr, " -u USERNAME can be any system username to run as. Default: none.\n"); fprintf(stderr, " -ch path to access host /proc and /sys when running in a container. Default: empty.\n"); fprintf(stderr, " -nd or -nodeamon to disable forking in the background. Default: unset.\n"); fprintf(stderr, " -df FLAGS debug options. Default: 0x%08llx.\n", debug_flags); fprintf(stderr, " -stacksize BYTES to overwrite the pthread stack size.\n"); fprintf(stderr, " -pidfile FILENAME to save a pid while running.\n"); exit(1); } } if(!config_loaded) load_config(NULL, 0); // prepare configuration environment variables for the plugins setenv("NETDATA_CONFIG_DIR" , config_get("global", "config directory" , CONFIG_DIR) , 1); setenv("NETDATA_PLUGINS_DIR", config_get("global", "plugins directory" , PLUGINS_DIR), 1); setenv("NETDATA_WEB_DIR" , config_get("global", "web files directory", WEB_DIR) , 1); setenv("NETDATA_CACHE_DIR" , config_get("global", "cache directory" , CACHE_DIR) , 1); setenv("NETDATA_LOG_DIR" , config_get("global", "log directory" , LOG_DIR) , 1); setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "") , 1); // avoid extended to stat(/etc/localtime) // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux setenv("TZ", ":/etc/localtime", 0); // cd to /tmp to avoid any plugins writing files at random places if(chdir("/tmp")) error("netdata: ERROR: Cannot cd to /tmp"); char *input_log_file = NULL; char *output_log_file = NULL; char *error_log_file = NULL; char *access_log_file = NULL; char *user = NULL; { char buffer[1024]; // -------------------------------------------------------------------- sprintf(buffer, "0x%08llx", 0ULL); char *flags = config_get("global", "debug flags", buffer); setenv("NETDATA_DEBUG_FLAGS", flags, 1); debug_flags = strtoull(flags, NULL, 0); debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags); #ifndef __FreeBSD__ if(debug_flags != 0) { struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY }; if(setrlimit(RLIMIT_CORE, &rl) != 0) info("Cannot request unlimited core dumps for debugging... Proceeding anyway..."); prctl(PR_SET_DUMPABLE, 1, 0, 0, 0); } #endif /*__FreeBSD__*/ // -------------------------------------------------------------------- #ifdef MADV_MERGEABLE enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm); #else #warning "Kernel memory deduplication (KSM) is not available" #endif // -------------------------------------------------------------------- global_host_prefix = config_get("global", "host access prefix", ""); setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1); // -------------------------------------------------------------------- output_log_file = config_get("global", "debug log", LOG_DIR "/debug.log"); if(strcmp(output_log_file, "syslog") == 0) { output_log_syslog = 1; output_log_file = NULL; } else if(strcmp(output_log_file, "none") == 0) { output_log_syslog = 0; output_log_file = NULL; } else output_log_syslog = 0; // -------------------------------------------------------------------- error_log_file = config_get("global", "error log", LOG_DIR "/error.log"); if(strcmp(error_log_file, "syslog") == 0) { error_log_syslog = 1; error_log_file = NULL; } else if(strcmp(error_log_file, "none") == 0) { error_log_syslog = 0; error_log_file = NULL; // optimization - do not even generate debug log entries } else error_log_syslog = 0; // -------------------------------------------------------------------- access_log_file = config_get("global", "access log", LOG_DIR "/access.log"); if(strcmp(access_log_file, "syslog") == 0) { access_log_syslog = 1; access_log_file = NULL; } else if(strcmp(access_log_file, "none") == 0) { access_log_syslog = 0; access_log_file = NULL; } else access_log_syslog = 0; // -------------------------------------------------------------------- rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode))); // -------------------------------------------------------------------- if(gethostname(buffer, HOSTNAME_MAX) == -1) error("WARNING: Cannot get machine hostname."); hostname = config_get("global", "hostname", buffer); debug(D_OPTIONS, "hostname set to '%s'", hostname); // -------------------------------------------------------------------- rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES); if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) { info("Invalid save lines %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES); rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES; } else { debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries); } // -------------------------------------------------------------------- rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY); if(rrd_update_every < 1 || rrd_update_every > 600) { info("Invalid update timer %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX); rrd_update_every = UPDATE_EVERY; } else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every); // let the plugins know the min update_every { char buf[50]; snprintf(buf, 50, "%d", rrd_update_every); setenv("NETDATA_UPDATE_EVERY", buf, 1); } // -------------------------------------------------------------------- i = pthread_attr_init(&attr); if(i != 0) fatal("pthread_attr_init() failed with code %d.", i); i = pthread_attr_getstacksize(&attr, &stacksize); if(i != 0) fatal("pthread_attr_getstacksize() failed with code %d.", i); else debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize); wanted_stacksize = config_get_number("global", "pthread stack size", stacksize); // -------------------------------------------------------------------- for (i = 0; static_threads[i].name != NULL ; i++) { struct netdata_static_thread *st = &static_threads[i]; if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled); if(st->enabled && st->init_routine) st->init_routine(); } // -------------------------------------------------------------------- user = config_get("global", "run as user" , (getuid() == 0)?NETDATA_USER:""); web_files_uid(); // -------------------------------------------------------------------- listen_backlog = (int) config_get_number("global", "http port listen backlog", LISTEN_BACKLOG); listen_port = (int) config_get_number("global", "port", LISTEN_PORT); if(listen_port < 1 || listen_port > 65535) { info("Invalid listen port %d given. Defaulting to %d.", listen_port, LISTEN_PORT); listen_port = LISTEN_PORT; } else debug(D_OPTIONS, "Listen port set to %d.", listen_port); int ip = 0; char *ipv = config_get("global", "ip version", "any"); if(!strcmp(ipv, "any") || !strcmp(ipv, "both") || !strcmp(ipv, "all")) ip = 0; else if(!strcmp(ipv, "ipv4") || !strcmp(ipv, "IPV4") || !strcmp(ipv, "IPv4") || !strcmp(ipv, "4")) ip = 4; else if(!strcmp(ipv, "ipv6") || !strcmp(ipv, "IPV6") || !strcmp(ipv, "IPv6") || !strcmp(ipv, "6")) ip = 6; else info("Cannot understand ip version '%s'. Assuming 'any'.", ipv); if(ip == 0 || ip == 6) listen_fd = create_listen_socket6(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog); if(listen_fd < 0) { listen_fd = create_listen_socket4(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog); if(listen_fd >= 0 && ip != 4) info("Managed to open an IPv4 socket on port %d.", listen_port); } if(listen_fd < 0) fatal("Cannot listen socket."); } // never become a problem if(nice(20) == -1) error("Cannot lower my CPU priority."); if(become_daemon(dont_fork, 0, user, input_log_file, output_log_file, error_log_file, access_log_file, &access_fd, &stdaccess) == -1) { fatal("Cannot demonize myself."); exit(1); } #ifndef __FreeBSD__ if(debug_flags != 0) { struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY }; if(setrlimit(RLIMIT_CORE, &rl) != 0) info("Cannot request unlimited core dumps for debugging... Proceeding anyway..."); prctl(PR_SET_DUMPABLE, 1, 0, 0, 0); } #endif /*__FreeBSD__*/ if(output_log_syslog || error_log_syslog || access_log_syslog) openlog("netdata", LOG_PID, LOG_DAEMON); info("NetData started on pid %d", getpid()); // catch all signals for (i = 1 ; i < 65 ;i++) { switch(i) { case SIGKILL: // not catchable case SIGSTOP: // not catchable break; case SIGSEGV: case SIGFPE: case SIGCHLD: signal(i, SIG_DFL); break; default: signal(i, sig_handler); break; } } // ------------------------------------------------------------------------ // get default pthread stack size if(stacksize < wanted_stacksize) { i = pthread_attr_setstacksize(&attr, wanted_stacksize); if(i != 0) fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i); else info("Successfully set pthread stacksize to %zu bytes", wanted_stacksize); } // ------------------------------------------------------------------------ // spawn the threads for (i = 0; static_threads[i].name != NULL ; i++) { struct netdata_static_thread *st = &static_threads[i]; if(st->enabled) { st->thread = malloc(sizeof(pthread_t)); if(!st->thread) fatal("Cannot allocate pthread_t memory"); info("Starting thread %s.", st->name); if(pthread_create(st->thread, &attr, st->start_routine, NULL)) error("failed to create new thread for %s.", st->name); else if(pthread_detach(*st->thread)) error("Cannot request detach of newly created %s thread.", st->name); } else info("Not starting thread %s.", st->name); } // for future use - the main thread while(1) { if(netdata_exit != 0) { netdata_exit++; if(netdata_exit > 5) { netdata_cleanup_and_exit(0); exit(0); } } sleep(2); } exit(0); }
//! application entry point int main ( int argc, char *argv[] ) { index_error exitcode; index_data_t index_data; char buffer[64]; signal(SIGINT, intHandler); for (;;) { // let the user know we're running log_message (APP_NAME " started."); // initialize index structure for this program exitcode = index_data_init (&index_data); if ( exitcode != FUNC_OK ) break; // get values from configuration file and command line exitcode = load_config (&index_data); if ( exitcode != FUNC_OK ) break; exitcode = parse_command_line (&index_data, argc, argv); if ( exitcode != FUNC_OK ) break; dbg_message ("mark 6"); // prepare zmq void *context = zmq_ctx_new (); if ( context == NULL ) break; dbg_message ("mark 7"); void *server = zmq_socket (context, ZMQ_REP); if ( server == NULL ) break; dbg_message ("mark 8"); sprintf (buffer, "tcp://*:%d", index_data.port); dbg_message ("mark 81"); if ( zmq_bind (server, buffer) != 0 ) { fprintf (stderr, "Failed to bind to port %d\n", index_data.port); break; } dbg_message ("mark 9"); // let the user know we're running log_message (APP_NAME " listening to port %d.", index_data.port); dbg_message ("mark 10"); // wait for requests and process them while ( exitcode == FUNC_OK ) { int64_t more; size_t more_size = sizeof more; do { //! react to CTRL+C if ( !keep_running ) { log_message ("Exit on user request."); break; } // Create an empty ØMQ message to hold the message part zmq_msg_t part; int rc = zmq_msg_init (&part); INDEX_ASSERT (rc == 0); INDEX_UNUSED (rc); // Block until a message is available to be received from socket rc = zmq_msg_recv (&part, server, 0); if ( rc == -1 ) { rc = zmq_errno(); if ( rc == 4 ) { log_message ("Exit on user request."); } else { err_message ( "code %d while receiving message: %s", zmq_errno(), zmq_strerror(rc)); exitcode = FUNC_GENERIC_ERROR; } break; } // process this message void *data = zmq_msg_data (&part); size_t data_sz = zmq_msg_size (&part); if ( data_sz > 0 ) { INDEX_ASSERT (data != NULL); exitcode = process_request (&index_data, server,data, data_sz); if ( exitcode != FUNC_OK ) { log_message ("Exit on internal error"); break; } } // Determine if more message parts are to follow rc = zmq_getsockopt (server, ZMQ_RCVMORE, &more, &more_size); INDEX_ASSERT (rc == 0); zmq_msg_close (&part); } while (more); if ( !keep_running ) break; } // terminate zmq zmq_close (server); zmq_ctx_destroy (context); break; } log_message (APP_NAME " is being closed."); // terminate the structure index_data_end (&index_data); return exitcode; }
static int send_pptp_start_ctrl_conn_rply(struct pptp_conn_t *conn, int res_code, int err_code) { struct pptp_start_ctrl_conn msg = { .header = PPTP_HEADER_CTRL(PPTP_START_CTRL_CONN_RPLY), .version = htons(PPTP_VERSION), .result_code = res_code, .error_code = err_code, .framing_cap = htonl(3), .bearer_cap = htonl(3), .max_channels = htons(1), .firmware_rev = htons(PPTP_FIRMWARE_VERSION), }; memset(msg.hostname, 0, sizeof(msg.hostname)); strcpy((char*)msg.hostname, PPTP_HOSTNAME); memset(msg.vendor, 0, sizeof(msg.vendor)); strcpy((char*)msg.vendor, PPTP_VENDOR); if (conf_verbose) log_ppp_info2("send [PPTP Start-Ctrl-Conn-Reply <Version %i> <Result %i> <Error %i> <Framing %x> <Bearer %x> <Max-Chan %i>]\n", msg.version, msg.result_code, msg.error_code, ntohl(msg.framing_cap), ntohl(msg.bearer_cap), ntohs(msg.max_channels)); return post_msg(conn, &msg, sizeof(msg)); } static int pptp_start_ctrl_conn_rqst(struct pptp_conn_t *conn) { struct pptp_start_ctrl_conn *msg = (struct pptp_start_ctrl_conn *)conn->in_buf; if (conf_verbose) log_ppp_info2("recv [PPTP Start-Ctrl-Conn-Request <Version %i> <Framing %x> <Bearer %x> <Max-Chan %i>]\n", msg->version, ntohl(msg->framing_cap), ntohl(msg->bearer_cap), ntohs(msg->max_channels)); if (conn->state != STATE_IDLE) { log_ppp_warn("unexpected PPTP_START_CTRL_CONN_RQST\n"); if (send_pptp_start_ctrl_conn_rply(conn, PPTP_CONN_RES_EXISTS, 0)) return -1; return 0; } if (msg->version != htons(PPTP_VERSION)) { log_ppp_warn("PPTP version mismatch: expecting %x, received %s\n", PPTP_VERSION, msg->version); if (send_pptp_start_ctrl_conn_rply(conn, PPTP_CONN_RES_PROTOCOL, 0)) return -1; return 0; } /*if (!(ntohl(msg->framing_cap) & PPTP_FRAME_SYNC)) { log_ppp_warn("connection does not supports sync mode\n"); if (send_pptp_start_ctrl_conn_rply(conn, PPTP_CONN_RES_GE, 0)) return -1; return 0; }*/ if (send_pptp_start_ctrl_conn_rply(conn, PPTP_CONN_RES_SUCCESS, 0)) return -1; triton_timer_mod(&conn->timeout_timer, 0); conn->state = STATE_ESTB; return 0; } static int send_pptp_out_call_rply(struct pptp_conn_t *conn, struct pptp_out_call_rqst *rqst, int call_id, int res_code, int err_code) { struct pptp_out_call_rply msg = { .header = PPTP_HEADER_CTRL(PPTP_OUT_CALL_RPLY), .call_id = htons(call_id), .call_id_peer = rqst->call_id, .result_code = res_code, .error_code = err_code, .cause_code = 0, .speed = rqst->bps_max, .recv_size = rqst->recv_size, .delay = 0, .channel = 0, }; if (conf_verbose) log_ppp_info2("send [PPTP Outgoing-Call-Reply <Call-ID %x> <Peer-Call-ID %x> <Result %i> <Error %i> <Cause %i> <Speed %i> <Window-Size %i> <Delay %i> <Channel %x>]\n", ntohs(msg.call_id), ntohs(msg.call_id_peer), msg.result_code, msg.error_code, ntohs(msg.cause_code), ntohl(msg.speed), ntohs(msg.recv_size), ntohs(msg.delay), ntohl(msg.channel)); return post_msg(conn, &msg, sizeof(msg)); } static int pptp_out_call_rqst(struct pptp_conn_t *conn) { struct pptp_out_call_rqst *msg = (struct pptp_out_call_rqst *)conn->in_buf; struct sockaddr_pppox src_addr, dst_addr; struct sockaddr_in addr; socklen_t addrlen; int pptp_sock; if (conf_verbose) log_ppp_info2("recv [PPTP Outgoing-Call-Request <Call-ID %x> <Call-Serial %x> <Min-BPS %i> <Max-BPS %i> <Bearer %x> <Framing %x> <Window-Size %i> <Delay %i>]\n", ntohs(msg->call_id), ntohs(msg->call_sernum), ntohl(msg->bps_min), ntohl(msg->bps_max), ntohl(msg->bearer), ntohl(msg->framing), ntohs(msg->recv_size), ntohs(msg->delay)); if (conn->state != STATE_ESTB) { log_ppp_warn("unexpected PPTP_OUT_CALL_RQST\n"); if (send_pptp_out_call_rply(conn, msg, 0, PPTP_CALL_RES_GE, PPTP_GE_NOCONN)) return -1; return 0; } memset(&src_addr, 0, sizeof(src_addr)); src_addr.sa_family = AF_PPPOX; src_addr.sa_protocol = PX_PROTO_PPTP; src_addr.sa_addr.pptp.call_id = 0; addrlen = sizeof(addr); getsockname(conn->hnd.fd, (struct sockaddr*)&addr, &addrlen); src_addr.sa_addr.pptp.sin_addr = addr.sin_addr; memset(&dst_addr, 0, sizeof(dst_addr)); dst_addr.sa_family = AF_PPPOX; dst_addr.sa_protocol = PX_PROTO_PPTP; dst_addr.sa_addr.pptp.call_id = htons(msg->call_id); addrlen = sizeof(addr); getpeername(conn->hnd.fd, (struct sockaddr*)&addr, &addrlen); dst_addr.sa_addr.pptp.sin_addr = addr.sin_addr; pptp_sock = socket(AF_PPPOX, SOCK_STREAM, PX_PROTO_PPTP); if (pptp_sock < 0) { log_ppp_error("failed to create PPTP socket (%s)\n", strerror(errno)); return -1; } fcntl(pptp_sock, F_SETFD, fcntl(pptp_sock, F_GETFD) | FD_CLOEXEC); if (bind(pptp_sock, (struct sockaddr*)&src_addr, sizeof(src_addr))) { log_ppp_error("failed to bind PPTP socket (%s)\n", strerror(errno)); close(pptp_sock); return -1; } addrlen = sizeof(src_addr); getsockname(pptp_sock, (struct sockaddr*)&src_addr, &addrlen); if (connect(pptp_sock, (struct sockaddr*)&dst_addr, sizeof(dst_addr))) { log_ppp_error("failed to connect PPTP socket (%s)\n", strerror(errno)); close(pptp_sock); return -1; } if (send_pptp_out_call_rply(conn, msg, src_addr.sa_addr.pptp.call_id, PPTP_CALL_RES_OK, 0)) return -1; conn->call_id = src_addr.sa_addr.pptp.call_id; conn->peer_call_id = msg->call_id; conn->ppp.fd = pptp_sock; conn->ppp.chan_name = _strdup(inet_ntoa(dst_addr.sa_addr.pptp.sin_addr)); triton_event_fire(EV_CTRL_STARTED, &conn->ppp); if (establish_ppp(&conn->ppp)) { close(pptp_sock); //if (send_pptp_stop_ctrl_conn_rqst(conn, 0, 0)) conn->state = STATE_FIN; return -1; } conn->state = STATE_PPP; __sync_sub_and_fetch(&stat_starting, 1); __sync_add_and_fetch(&stat_active, 1); if (conn->timeout_timer.tpd) triton_timer_del(&conn->timeout_timer); if (conf_echo_interval) { conn->echo_timer.period = conf_echo_interval * 1000; triton_timer_add(&conn->ctx, &conn->echo_timer, 0); } return 0; } static int send_pptp_call_disconnect_notify(struct pptp_conn_t *conn, int result) { struct pptp_call_clear_ntfy msg = { .header = PPTP_HEADER_CTRL(PPTP_CALL_CLEAR_NTFY), .call_id = htons(conn->peer_call_id), .result_code = result, .error_code = 0, .cause_code = 0, }; if (conf_verbose) log_ppp_info2("send [PPTP Call-Disconnect-Notify <Call-ID %x> <Result %i> <Error %i> <Cause %i>]\n", ntohs(msg.call_id), msg.result_code, msg.error_code, msg.cause_code); return post_msg(conn, &msg, sizeof(msg)); } static int pptp_call_clear_rqst(struct pptp_conn_t *conn) { struct pptp_call_clear_rqst *rqst = (struct pptp_call_clear_rqst *)conn->in_buf; if (conf_verbose) log_ppp_info2("recv [PPTP Call-Clear-Request <Call-ID %x>]\n", ntohs(rqst->call_id)); if (conn->echo_timer.tpd) triton_timer_del(&conn->echo_timer); if (conn->state == STATE_PPP) { __sync_sub_and_fetch(&stat_active, 1); conn->state = STATE_CLOSE; ppp_terminate(&conn->ppp, TERM_USER_REQUEST, 1); } return send_pptp_call_disconnect_notify(conn, 4); } static int pptp_echo_rqst(struct pptp_conn_t *conn) { struct pptp_echo_rqst *in_msg = (struct pptp_echo_rqst *)conn->in_buf; struct pptp_echo_rply out_msg = { .header = PPTP_HEADER_CTRL(PPTP_ECHO_RPLY), .identifier = in_msg->identifier, .result_code = 1, }; if (conf_verbose) { log_ppp_debug("recv [PPTP Echo-Request <Identifier %x>]\n", in_msg->identifier); log_ppp_debug("send [PPTP Echo-Reply <Identifier %x>]\n", out_msg.identifier); } return post_msg(conn, &out_msg, sizeof(out_msg)); } static int pptp_echo_rply(struct pptp_conn_t *conn) { struct pptp_echo_rply *msg = (struct pptp_echo_rply *)conn->in_buf; if (conf_verbose) log_ppp_debug("recv [PPTP Echo-Reply <Identifier %x>]\n", msg->identifier); /*if (msg->identifier != conn->echo_sent) { log_ppp_warn("pptp:echo: identifier mismatch\n"); //return -1; }*/ conn->echo_sent = 0; return 0; } static void pptp_send_echo(struct triton_timer_t *t) { struct pptp_conn_t *conn = container_of(t, typeof(*conn), echo_timer); struct pptp_echo_rqst msg = { .header = PPTP_HEADER_CTRL(PPTP_ECHO_RQST), }; if (++conn->echo_sent == conf_echo_failure) { log_ppp_warn("pptp: no echo reply\n"); disconnect(conn); return; } conn->echo_sent = random(); msg.identifier = conn->echo_sent; if (conf_verbose) log_ppp_debug("send [PPTP Echo-Request <Identifier %x>]\n", msg.identifier); if (post_msg(conn, &msg, sizeof(msg))) disconnect(conn); } static int process_packet(struct pptp_conn_t *conn) { struct pptp_header *hdr = (struct pptp_header *)conn->in_buf; switch(ntohs(hdr->ctrl_type)) { case PPTP_START_CTRL_CONN_RQST: return pptp_start_ctrl_conn_rqst(conn); case PPTP_STOP_CTRL_CONN_RQST: return pptp_stop_ctrl_conn_rqst(conn); case PPTP_STOP_CTRL_CONN_RPLY: return pptp_stop_ctrl_conn_rply(conn); case PPTP_OUT_CALL_RQST: return pptp_out_call_rqst(conn); case PPTP_ECHO_RQST: return pptp_echo_rqst(conn); case PPTP_ECHO_RPLY: return pptp_echo_rply(conn); case PPTP_CALL_CLEAR_RQST: return pptp_call_clear_rqst(conn); case PPTP_SET_LINK_INFO: if (conf_verbose) log_ppp_info2("recv [PPTP Set-Link-Info]\n"); return 0; default: log_ppp_warn("recv [PPTP Unknown (%x)]\n", ntohs(hdr->ctrl_type)); } return 0; } static int pptp_read(struct triton_md_handler_t *h) { struct pptp_conn_t *conn=container_of(h,typeof(*conn),hnd); struct pptp_header *hdr=(struct pptp_header *)conn->in_buf; int n; while(1) { n = read(h->fd, conn->in_buf + conn->in_size, PPTP_CTRL_SIZE_MAX - conn->in_size); if (n < 0) { if (errno == EINTR) continue; if (errno == EAGAIN) return 0; log_ppp_error("pptp: read: %s\n",strerror(errno)); goto drop; } if (n == 0) { if (conf_verbose) log_ppp_info2("pptp: disconnect by peer\n"); goto drop; } conn->in_size += n; if (conn->in_size >= sizeof(*hdr)) { if (hdr->magic != htonl(PPTP_MAGIC)) { log_ppp_error("pptp: invalid magic\n"); goto drop; } if (ntohs(hdr->length) >= PPTP_CTRL_SIZE_MAX) { log_ppp_error("pptp: message is too long\n"); goto drop; } if (ntohs(hdr->length) > conn->in_size) continue; if (ntohs(hdr->length) <= conn->in_size) { if (ntohs(hdr->length) != PPTP_CTRL_SIZE(ntohs(hdr->ctrl_type))) { log_ppp_error("pptp: invalid message length\n"); goto drop; } if (process_packet(conn)) goto drop; conn->in_size -= ntohs(hdr->length); if (conn->in_size) memmove(conn->in_buf, conn->in_buf + ntohs(hdr->length), conn->in_size); } } } drop: disconnect(conn); return 1; } static int pptp_write(struct triton_md_handler_t *h) { struct pptp_conn_t *conn = container_of(h, typeof(*conn), hnd); int n; while (1) { n = write(h->fd, conn->out_buf+conn->out_pos, conn->out_size-conn->out_pos); if (n < 0) { if (errno == EINTR) continue; if (errno == EAGAIN) n = 0; else { if (errno != EPIPE) { if (conf_verbose) log_ppp_info2("pptp: post_msg: %s\n", strerror(errno)); } disconnect(conn); return 1; } } conn->out_pos += n; if (conn->out_pos == conn->out_size) { conn->out_pos = 0; conn->out_size = 0; triton_md_disable_handler(h, MD_MODE_WRITE); return 0; } } } static void pptp_timeout(struct triton_timer_t *t) { struct pptp_conn_t *conn = container_of(t, typeof(*conn), timeout_timer); disconnect(conn); } static void pptp_close(struct triton_context_t *ctx) { struct pptp_conn_t *conn = container_of(ctx, typeof(*conn), ctx); if (conn->state == STATE_PPP) { __sync_sub_and_fetch(&stat_active, 1); conn->state = STATE_CLOSE; ppp_terminate(&conn->ppp, TERM_ADMIN_RESET, 1); if (send_pptp_call_disconnect_notify(conn, 3)) { triton_context_call(&conn->ctx, (void (*)(void*))disconnect, conn); return; } } else { if (send_pptp_stop_ctrl_conn_rqst(conn, 0)) { triton_context_call(&conn->ctx, (void (*)(void*))disconnect, conn); return; } } if (conn->timeout_timer.tpd) triton_timer_mod(&conn->timeout_timer, 0); else triton_timer_add(ctx, &conn->timeout_timer, 0); } static void ppp_started(struct ppp_t *ppp) { log_ppp_debug("pptp: ppp started\n"); } static void ppp_finished(struct ppp_t *ppp) { struct pptp_conn_t *conn = container_of(ppp, typeof(*conn), ppp); if (conn->state != STATE_CLOSE) { log_ppp_debug("pptp: ppp finished\n"); conn->state = STATE_CLOSE; __sync_sub_and_fetch(&stat_active, 1); if (send_pptp_call_disconnect_notify(conn, 3)) triton_context_call(&conn->ctx, (void (*)(void*))disconnect, conn); else if (send_pptp_stop_ctrl_conn_rqst(conn, 0)) triton_context_call(&conn->ctx, (void (*)(void*))disconnect, conn); else { if (conn->timeout_timer.tpd) triton_timer_mod(&conn->timeout_timer, 0); else triton_timer_add(&conn->ctx, &conn->timeout_timer, 0); } } } //================================== struct pptp_serv_t { struct triton_context_t ctx; struct triton_md_handler_t hnd; }; static int pptp_connect(struct triton_md_handler_t *h) { struct sockaddr_in addr; socklen_t size = sizeof(addr); int sock; struct pptp_conn_t *conn; while(1) { sock = accept(h->fd, (struct sockaddr *)&addr, &size); if (sock < 0) { if (errno == EAGAIN) return 0; log_error("pptp: accept failed: %s\n", strerror(errno)); continue; } if (ppp_shutdown) { close(sock); continue; } if (triton_module_loaded("connlimit") && connlimit_check(cl_key_from_ipv4(addr.sin_addr.s_addr))) { close(sock); return 0; } log_info2("pptp: new connection from %s\n", inet_ntoa(addr.sin_addr)); if (iprange_client_check(addr.sin_addr.s_addr)) { log_warn("pptp: IP is out of client-ip-range, droping connection...\n"); close(sock); continue; } if (fcntl(sock, F_SETFL, O_NONBLOCK)) { log_error("pptp: failed to set nonblocking mode: %s, closing connection...\n", strerror(errno)); close(sock); continue; } conn = mempool_alloc(conn_pool); memset(conn, 0, sizeof(*conn)); conn->hnd.fd = sock; conn->hnd.read = pptp_read; conn->hnd.write = pptp_write; conn->ctx.close = pptp_close; conn->ctx.before_switch = log_switch; conn->in_buf = _malloc(PPTP_CTRL_SIZE_MAX); conn->out_buf = _malloc(PPTP_CTRL_SIZE_MAX); conn->timeout_timer.expire = pptp_timeout; conn->timeout_timer.period = conf_timeout * 1000; conn->echo_timer.expire = pptp_send_echo; conn->ctrl.ctx = &conn->ctx; conn->ctrl.started = ppp_started; conn->ctrl.finished = ppp_finished; conn->ctrl.max_mtu = PPTP_MAX_MTU; conn->ctrl.type = CTRL_TYPE_PPTP; conn->ctrl.name = "pptp"; conn->ctrl.calling_station_id = _malloc(17); conn->ctrl.called_station_id = _malloc(17); u_inet_ntoa(addr.sin_addr.s_addr, conn->ctrl.calling_station_id); getsockname(sock, &addr, &size); u_inet_ntoa(addr.sin_addr.s_addr, conn->ctrl.called_station_id); ppp_init(&conn->ppp); conn->ppp.ctrl = &conn->ctrl; triton_context_register(&conn->ctx, &conn->ppp); triton_md_register_handler(&conn->ctx, &conn->hnd); triton_md_enable_handler(&conn->hnd,MD_MODE_READ); triton_timer_add(&conn->ctx, &conn->timeout_timer, 0); triton_context_wakeup(&conn->ctx); triton_event_fire(EV_CTRL_STARTING, &conn->ppp); __sync_add_and_fetch(&stat_starting, 1); } return 0; } static void pptp_serv_close(struct triton_context_t *ctx) { struct pptp_serv_t *s=container_of(ctx,typeof(*s),ctx); triton_md_unregister_handler(&s->hnd); close(s->hnd.fd); triton_context_unregister(ctx); } static struct pptp_serv_t serv= { .hnd.read = pptp_connect, .ctx.close = pptp_serv_close, .ctx.before_switch = log_switch, }; static int show_stat_exec(const char *cmd, char * const *fields, int fields_cnt, void *client) { cli_send(client, "pptp:\r\n"); cli_sendv(client," starting: %u\r\n", stat_starting); cli_sendv(client," active: %u\r\n", stat_active); return CLI_CMD_OK; } void __export pptp_get_stat(unsigned int **starting, unsigned int **active) { *starting = &stat_starting; *active = &stat_active; } static void load_config(void) { char *opt; opt = conf_get_opt("pptp", "timeout"); if (opt && atoi(opt) > 0) conf_timeout = atoi(opt); opt = conf_get_opt("pptp", "echo-interval"); if (opt && atoi(opt) >= 0) conf_echo_interval = atoi(opt); opt = conf_get_opt("pptp", "echo-failure"); if (opt && atoi(opt) > 0) conf_echo_failure = atoi(opt); opt = conf_get_opt("pptp", "verbose"); if (opt && atoi(opt) > 0) conf_verbose = 1; } static void pptp_init(void) { struct sockaddr_in addr; char *opt; system("modprobe pptp"); serv.hnd.fd = socket(PF_INET, SOCK_STREAM, 0); if (serv.hnd.fd < 0) { log_emerg("pptp: failed to create server socket: %s\n", strerror(errno)); return; } fcntl(serv.hnd.fd, F_SETFD, fcntl(serv.hnd.fd, F_GETFD) | FD_CLOEXEC); addr.sin_family = AF_INET; addr.sin_port = htons(PPTP_PORT); opt = conf_get_opt("pptp", "bind"); if (opt) addr.sin_addr.s_addr = inet_addr(opt); else addr.sin_addr.s_addr = htonl(INADDR_ANY); setsockopt(serv.hnd.fd, SOL_SOCKET, SO_REUSEADDR, &serv.hnd.fd, 4); if (bind (serv.hnd.fd, (struct sockaddr *) &addr, sizeof (addr)) < 0) { log_emerg("pptp: failed to bind socket: %s\n", strerror(errno)); close(serv.hnd.fd); return; } if (listen (serv.hnd.fd, 100) < 0) { log_emerg("pptp: failed to listen socket: %s\n", strerror(errno)); close(serv.hnd.fd); return; } if (fcntl(serv.hnd.fd, F_SETFL, O_NONBLOCK)) { log_emerg("pptp: failed to set nonblocking mode: %s\n", strerror(errno)); close(serv.hnd.fd); return; } conn_pool = mempool_create(sizeof(struct pptp_conn_t)); load_config(); triton_context_register(&serv.ctx, NULL); triton_md_register_handler(&serv.ctx, &serv.hnd); triton_md_enable_handler(&serv.hnd, MD_MODE_READ); triton_context_wakeup(&serv.ctx); cli_register_simple_cmd2(show_stat_exec, NULL, 2, "show", "stat"); triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); } DEFINE_INIT(20, pptp_init);
int MAIN(int argc, char **argv) { ENGINE *e = NULL, *impl = NULL; unsigned char *buf = NULL; int i, err = 1; const EVP_MD *md = NULL, *m; BIO *in = NULL, *inp; BIO *bmd = NULL; BIO *out = NULL; #define PROG_NAME_SIZE 39 char pname[PROG_NAME_SIZE + 1]; int separator = 0; int debug = 0; int keyform = FORMAT_PEM; const char *outfile = NULL, *keyfile = NULL; const char *sigfile = NULL, *randfile = NULL; int out_bin = -1, want_pub = 0, do_verify = 0; EVP_PKEY *sigkey = NULL; unsigned char *sigbuf = NULL; int siglen = 0; char *passargin = NULL, *passin = NULL; #ifndef OPENSSL_NO_ENGINE char *engine = NULL; int engine_impl = 0; #endif char *hmac_key = NULL; char *mac_name = NULL; int non_fips_allow = 0; STACK_OF(OPENSSL_STRING) *sigopts = NULL, *macopts = NULL; apps_startup(); if ((buf = (unsigned char *)OPENSSL_malloc(BUFSIZE)) == NULL) { BIO_printf(bio_err, "out of memory\n"); goto end; } if (bio_err == NULL) if ((bio_err = BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT); if (!load_config(bio_err, NULL)) goto end; /* first check the program name */ program_name(argv[0], pname, sizeof pname); md = EVP_get_digestbyname(pname); argc--; argv++; while (argc > 0) { if ((*argv)[0] != '-') break; if (strcmp(*argv, "-c") == 0) separator = 1; else if (strcmp(*argv, "-r") == 0) separator = 2; else if (strcmp(*argv, "-rand") == 0) { if (--argc < 1) break; randfile = *(++argv); } else if (strcmp(*argv, "-out") == 0) { if (--argc < 1) break; outfile = *(++argv); } else if (strcmp(*argv, "-sign") == 0) { if (--argc < 1) break; keyfile = *(++argv); } else if (!strcmp(*argv, "-passin")) { if (--argc < 1) break; passargin = *++argv; } else if (strcmp(*argv, "-verify") == 0) { if (--argc < 1) break; keyfile = *(++argv); want_pub = 1; do_verify = 1; } else if (strcmp(*argv, "-prverify") == 0) { if (--argc < 1) break; keyfile = *(++argv); do_verify = 1; } else if (strcmp(*argv, "-signature") == 0) { if (--argc < 1) break; sigfile = *(++argv); } else if (strcmp(*argv, "-keyform") == 0) { if (--argc < 1) break; keyform = str2fmt(*(++argv)); } #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv, "-engine") == 0) { if (--argc < 1) break; engine = *(++argv); e = setup_engine(bio_err, engine, 0); } else if (strcmp(*argv, "-engine_impl") == 0) engine_impl = 1; #endif else if (strcmp(*argv, "-hex") == 0) out_bin = 0; else if (strcmp(*argv, "-binary") == 0) out_bin = 1; else if (strcmp(*argv, "-d") == 0) debug = 1; else if (!strcmp(*argv, "-fips-fingerprint")) hmac_key = "etaonrishdlcupfm"; else if (strcmp(*argv, "-non-fips-allow") == 0) non_fips_allow = 1; else if (!strcmp(*argv, "-hmac")) { if (--argc < 1) break; hmac_key = *++argv; } else if (!strcmp(*argv, "-mac")) { if (--argc < 1) break; mac_name = *++argv; } else if (strcmp(*argv, "-sigopt") == 0) { if (--argc < 1) break; if (!sigopts) sigopts = sk_OPENSSL_STRING_new_null(); if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, *(++argv))) break; } else if (strcmp(*argv, "-macopt") == 0) { if (--argc < 1) break; if (!macopts) macopts = sk_OPENSSL_STRING_new_null(); if (!macopts || !sk_OPENSSL_STRING_push(macopts, *(++argv))) break; } else if ((m = EVP_get_digestbyname(&((*argv)[1]))) != NULL) md = m; else break; argc--; argv++; } if (keyfile != NULL && argc > 1) { BIO_printf(bio_err, "Can only sign or verify one file\n"); goto end; } if (do_verify && !sigfile) { BIO_printf(bio_err, "No signature to verify: use the -signature option\n"); goto end; } if ((argc > 0) && (argv[0][0] == '-')) { /* bad option */ BIO_printf(bio_err, "unknown option '%s'\n", *argv); BIO_printf(bio_err, "options are\n"); BIO_printf(bio_err, "-c to output the digest with separating colons\n"); BIO_printf(bio_err, "-r to output the digest in coreutils format\n"); BIO_printf(bio_err, "-d to output debug info\n"); BIO_printf(bio_err, "-hex output as hex dump\n"); BIO_printf(bio_err, "-binary output in binary form\n"); BIO_printf(bio_err, "-hmac arg set the HMAC key to arg\n"); BIO_printf(bio_err, "-non-fips-allow allow use of non FIPS digest\n"); BIO_printf(bio_err, "-sign file sign digest using private key in file\n"); BIO_printf(bio_err, "-verify file verify a signature using public key in file\n"); BIO_printf(bio_err, "-prverify file verify a signature using private key in file\n"); BIO_printf(bio_err, "-keyform arg key file format (PEM or ENGINE)\n"); BIO_printf(bio_err, "-out filename output to filename rather than stdout\n"); BIO_printf(bio_err, "-signature file signature to verify\n"); BIO_printf(bio_err, "-sigopt nm:v signature parameter\n"); BIO_printf(bio_err, "-hmac key create hashed MAC with key\n"); BIO_printf(bio_err, "-mac algorithm create MAC (not neccessarily HMAC)\n"); BIO_printf(bio_err, "-macopt nm:v MAC algorithm parameters or key\n"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, "-engine e use engine e, possibly a hardware device.\n"); #endif EVP_MD_do_all_sorted(list_md_fn, bio_err); goto end; } #ifndef OPENSSL_NO_ENGINE if (engine_impl) impl = e; #endif in = BIO_new(BIO_s_file()); bmd = BIO_new(BIO_f_md()); if ((in == NULL) || (bmd == NULL)) { ERR_print_errors(bio_err); goto end; } if (debug) { BIO_set_callback(in, BIO_debug_callback); /* needed for windows 3.1 */ BIO_set_callback_arg(in, (char *)bio_err); } if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } if (out_bin == -1) { if (keyfile) out_bin = 1; else out_bin = 0; } if (randfile) app_RAND_load_file(randfile, bio_err, 0); if (outfile) { if (out_bin) out = BIO_new_file(outfile, "wb"); else out = BIO_new_file(outfile, "w"); } else { out = BIO_new_fp(stdout, BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } #endif } if (!out) { BIO_printf(bio_err, "Error opening output file %s\n", outfile ? outfile : "(stdout)"); ERR_print_errors(bio_err); goto end; } if ((! !mac_name + ! !keyfile + ! !hmac_key) > 1) { BIO_printf(bio_err, "MAC and Signing key cannot both be specified\n"); goto end; } if (keyfile) { if (want_pub) sigkey = load_pubkey(bio_err, keyfile, keyform, 0, NULL, e, "key file"); else sigkey = load_key(bio_err, keyfile, keyform, 0, passin, e, "key file"); if (!sigkey) { /* * load_[pub]key() has already printed an appropriate message */ goto end; } } if (mac_name) { EVP_PKEY_CTX *mac_ctx = NULL; int r = 0; if (!init_gen_str(bio_err, &mac_ctx, mac_name, impl, 0)) goto mac_end; if (macopts) { char *macopt; for (i = 0; i < sk_OPENSSL_STRING_num(macopts); i++) { macopt = sk_OPENSSL_STRING_value(macopts, i); if (pkey_ctrl_string(mac_ctx, macopt) <= 0) { BIO_printf(bio_err, "MAC parameter error \"%s\"\n", macopt); ERR_print_errors(bio_err); goto mac_end; } } } if (EVP_PKEY_keygen(mac_ctx, &sigkey) <= 0) { BIO_puts(bio_err, "Error generating key\n"); ERR_print_errors(bio_err); goto mac_end; } r = 1; mac_end: if (mac_ctx) EVP_PKEY_CTX_free(mac_ctx); if (r == 0) goto end; } if (non_fips_allow) { EVP_MD_CTX *md_ctx; BIO_get_md_ctx(bmd, &md_ctx); EVP_MD_CTX_set_flags(md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); } if (hmac_key) { sigkey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, impl, (unsigned char *)hmac_key, -1); if (!sigkey) goto end; } if (sigkey) { EVP_MD_CTX *mctx = NULL; EVP_PKEY_CTX *pctx = NULL; int r; if (!BIO_get_md_ctx(bmd, &mctx)) { BIO_printf(bio_err, "Error getting context\n"); ERR_print_errors(bio_err); goto end; } if (do_verify) r = EVP_DigestVerifyInit(mctx, &pctx, md, impl, sigkey); else r = EVP_DigestSignInit(mctx, &pctx, md, impl, sigkey); if (!r) { BIO_printf(bio_err, "Error setting context\n"); ERR_print_errors(bio_err); goto end; } if (sigopts) { char *sigopt; for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) { sigopt = sk_OPENSSL_STRING_value(sigopts, i); if (pkey_ctrl_string(pctx, sigopt) <= 0) { BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt); ERR_print_errors(bio_err); goto end; } } } } /* we use md as a filter, reading from 'in' */ else { EVP_MD_CTX *mctx = NULL; if (!BIO_get_md_ctx(bmd, &mctx)) { BIO_printf(bio_err, "Error getting context\n"); ERR_print_errors(bio_err); goto end; } if (md == NULL) md = EVP_md5(); if (!EVP_DigestInit_ex(mctx, md, impl)) { BIO_printf(bio_err, "Error setting digest %s\n", pname); ERR_print_errors(bio_err); goto end; } } if (sigfile && sigkey) { BIO *sigbio; sigbio = BIO_new_file(sigfile, "rb"); siglen = EVP_PKEY_size(sigkey); sigbuf = OPENSSL_malloc(siglen); if (!sigbio) { BIO_printf(bio_err, "Error opening signature file %s\n", sigfile); ERR_print_errors(bio_err); goto end; } if (!sigbuf) { BIO_printf(bio_err, "Out of memory\n"); ERR_print_errors(bio_err); goto end; } siglen = BIO_read(sigbio, sigbuf, siglen); BIO_free(sigbio); if (siglen <= 0) { BIO_printf(bio_err, "Error reading signature file %s\n", sigfile); ERR_print_errors(bio_err); goto end; } } inp = BIO_push(bmd, in); if (md == NULL) { EVP_MD_CTX *tctx; BIO_get_md_ctx(bmd, &tctx); md = EVP_MD_CTX_md(tctx); } if (argc == 0) { BIO_set_fp(in, stdin, BIO_NOCLOSE); err = do_fp(out, buf, inp, separator, out_bin, sigkey, sigbuf, siglen, NULL, NULL, "stdin", bmd); } else { const char *md_name = NULL, *sig_name = NULL; if (!out_bin) { if (sigkey) { const EVP_PKEY_ASN1_METHOD *ameth; ameth = EVP_PKEY_get0_asn1(sigkey); if (ameth) EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &sig_name, ameth); } if (md) md_name = EVP_MD_name(md); } err = 0; for (i = 0; i < argc; i++) { int r; if (BIO_read_filename(in, argv[i]) <= 0) { perror(argv[i]); err++; continue; } else r = do_fp(out, buf, inp, separator, out_bin, sigkey, sigbuf, siglen, sig_name, md_name, argv[i], bmd); if (r) err = r; (void)BIO_reset(bmd); } } end: if (buf != NULL) { OPENSSL_cleanse(buf, BUFSIZE); OPENSSL_free(buf); } if (in != NULL) BIO_free(in); if (passin) OPENSSL_free(passin); BIO_free_all(out); EVP_PKEY_free(sigkey); if (sigopts) sk_OPENSSL_STRING_free(sigopts); if (macopts) sk_OPENSSL_STRING_free(macopts); if (sigbuf) OPENSSL_free(sigbuf); if (bmd != NULL) BIO_free(bmd); apps_shutdown(); OPENSSL_EXIT(err); }
int MAIN(int argc, char **argv) { ENGINE *e = NULL; char **args; char *host = NULL, *port = NULL, *path = "/"; char *thost = NULL, *tport = NULL, *tpath = NULL; char *reqin = NULL, *respin = NULL; char *reqout = NULL, *respout = NULL; char *signfile = NULL, *keyfile = NULL; char *rsignfile = NULL, *rkeyfile = NULL; char *outfile = NULL; int add_nonce = 1, noverify = 0, use_ssl = -1; STACK_OF(CONF_VALUE) *headers = NULL; OCSP_REQUEST *req = NULL; OCSP_RESPONSE *resp = NULL; OCSP_BASICRESP *bs = NULL; X509 *issuer = NULL, *cert = NULL; X509 *signer = NULL, *rsigner = NULL; EVP_PKEY *key = NULL, *rkey = NULL; BIO *acbio = NULL, *cbio = NULL; BIO *derbio = NULL; BIO *out = NULL; int req_timeout = -1; int req_text = 0, resp_text = 0; long nsec = MAX_VALIDITY_PERIOD, maxage = -1; char *CAfile = NULL, *CApath = NULL; X509_STORE *store = NULL; X509_VERIFY_PARAM *vpm = NULL; STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL; char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL; unsigned long sign_flags = 0, verify_flags = 0, rflags = 0; int ret = 1; int accept_count = -1; int badarg = 0; int badsig = 0; int i; int ignore_err = 0; STACK_OF(OPENSSL_STRING) *reqnames = NULL; STACK_OF(OCSP_CERTID) *ids = NULL; X509 *rca_cert = NULL; char *ridx_filename = NULL; char *rca_filename = NULL; CA_DB *rdb = NULL; int nmin = 0, ndays = -1; const EVP_MD *cert_id_md = NULL, *rsign_md = NULL; if (bio_err == NULL) bio_err = BIO_new_fp(stderr, BIO_NOCLOSE); if (!load_config(bio_err, NULL)) goto end; SSL_load_error_strings(); OpenSSL_add_ssl_algorithms(); args = argv + 1; reqnames = sk_OPENSSL_STRING_new_null(); ids = sk_OCSP_CERTID_new_null(); while (!badarg && *args && *args[0] == '-') { if (!strcmp(*args, "-out")) { if (args[1]) { args++; outfile = *args; } else badarg = 1; } else if (!strcmp(*args, "-timeout")) { if (args[1]) { args++; req_timeout = atol(*args); if (req_timeout < 0) { BIO_printf(bio_err, "Illegal timeout value %s\n", *args); badarg = 1; } } else badarg = 1; } else if (!strcmp(*args, "-url")) { if (thost) OPENSSL_free(thost); if (tport) OPENSSL_free(tport); if (tpath) OPENSSL_free(tpath); if (args[1]) { args++; if (!OCSP_parse_url(*args, &host, &port, &path, &use_ssl)) { BIO_printf(bio_err, "Error parsing URL\n"); badarg = 1; } thost = host; tport = port; tpath = path; } else badarg = 1; } else if (!strcmp(*args, "-host")) { if (args[1]) { args++; host = *args; } else badarg = 1; } else if (!strcmp(*args, "-port")) { if (args[1]) { args++; port = *args; } else badarg = 1; } else if (!strcmp(*args, "-header")) { if (args[1] && args[2]) { if (!X509V3_add_value(args[1], args[2], &headers)) goto end; args += 2; } else badarg = 1; } else if (!strcmp(*args, "-ignore_err")) ignore_err = 1; else if (!strcmp(*args, "-noverify")) noverify = 1; else if (!strcmp(*args, "-nonce")) add_nonce = 2; else if (!strcmp(*args, "-no_nonce")) add_nonce = 0; else if (!strcmp(*args, "-resp_no_certs")) rflags |= OCSP_NOCERTS; else if (!strcmp(*args, "-resp_key_id")) rflags |= OCSP_RESPID_KEY; else if (!strcmp(*args, "-no_certs")) sign_flags |= OCSP_NOCERTS; else if (!strcmp(*args, "-no_signature_verify")) verify_flags |= OCSP_NOSIGS; else if (!strcmp(*args, "-no_cert_verify")) verify_flags |= OCSP_NOVERIFY; else if (!strcmp(*args, "-no_chain")) verify_flags |= OCSP_NOCHAIN; else if (!strcmp(*args, "-no_cert_checks")) verify_flags |= OCSP_NOCHECKS; else if (!strcmp(*args, "-no_explicit")) verify_flags |= OCSP_NOEXPLICIT; else if (!strcmp(*args, "-trust_other")) verify_flags |= OCSP_TRUSTOTHER; else if (!strcmp(*args, "-no_intern")) verify_flags |= OCSP_NOINTERN; else if (!strcmp(*args, "-badsig")) badsig = 1; else if (!strcmp(*args, "-text")) { req_text = 1; resp_text = 1; } else if (!strcmp(*args, "-req_text")) req_text = 1; else if (!strcmp(*args, "-resp_text")) resp_text = 1; else if (!strcmp(*args, "-reqin")) { if (args[1]) { args++; reqin = *args; } else badarg = 1; } else if (!strcmp(*args, "-respin")) { if (args[1]) { args++; respin = *args; } else badarg = 1; } else if (!strcmp(*args, "-signer")) { if (args[1]) { args++; signfile = *args; } else badarg = 1; } else if (!strcmp(*args, "-VAfile")) { if (args[1]) { args++; verify_certfile = *args; verify_flags |= OCSP_TRUSTOTHER; } else badarg = 1; } else if (!strcmp(*args, "-sign_other")) { if (args[1]) { args++; sign_certfile = *args; } else badarg = 1; } else if (!strcmp(*args, "-verify_other")) { if (args[1]) { args++; verify_certfile = *args; } else badarg = 1; } else if (!strcmp(*args, "-CAfile")) { if (args[1]) { args++; CAfile = *args; } else badarg = 1; } else if (!strcmp(*args, "-CApath")) { if (args[1]) { args++; CApath = *args; } else badarg = 1; } else if (args_verify(&args, NULL, &badarg, bio_err, &vpm)) { if (badarg) goto end; continue; } else if (!strcmp(*args, "-validity_period")) { if (args[1]) { args++; nsec = atol(*args); if (nsec < 0) { BIO_printf(bio_err, "Illegal validity period %s\n", *args); badarg = 1; } } else badarg = 1; } else if (!strcmp(*args, "-status_age")) { if (args[1]) { args++; maxage = atol(*args); if (maxage < 0) { BIO_printf(bio_err, "Illegal validity age %s\n", *args); badarg = 1; } } else badarg = 1; } else if (!strcmp(*args, "-signkey")) { if (args[1]) { args++; keyfile = *args; } else badarg = 1; } else if (!strcmp(*args, "-reqout")) { if (args[1]) { args++; reqout = *args; } else badarg = 1; } else if (!strcmp(*args, "-respout")) { if (args[1]) { args++; respout = *args; } else badarg = 1; } else if (!strcmp(*args, "-path")) { if (args[1]) { args++; path = *args; } else badarg = 1; } else if (!strcmp(*args, "-issuer")) { if (args[1]) { args++; X509_free(issuer); issuer = load_cert(bio_err, *args, FORMAT_PEM, NULL, e, "issuer certificate"); if (!issuer) goto end; } else badarg = 1; } else if (!strcmp(*args, "-cert")) { if (args[1]) { args++; X509_free(cert); cert = load_cert(bio_err, *args, FORMAT_PEM, NULL, e, "certificate"); if (!cert) goto end; if (!cert_id_md) cert_id_md = EVP_sha1(); if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids)) goto end; if (!sk_OPENSSL_STRING_push(reqnames, *args)) goto end; } else badarg = 1; } else if (!strcmp(*args, "-serial")) { if (args[1]) { args++; if (!cert_id_md) cert_id_md = EVP_sha1(); if (!add_ocsp_serial(&req, *args, cert_id_md, issuer, ids)) goto end; if (!sk_OPENSSL_STRING_push(reqnames, *args)) goto end; } else badarg = 1; } else if (!strcmp(*args, "-index")) { if (args[1]) { args++; ridx_filename = *args; } else badarg = 1; } else if (!strcmp(*args, "-CA")) { if (args[1]) { args++; rca_filename = *args; } else badarg = 1; } else if (!strcmp(*args, "-nmin")) { if (args[1]) { args++; nmin = atol(*args); if (nmin < 0) { BIO_printf(bio_err, "Illegal update period %s\n", *args); badarg = 1; } } if (ndays == -1) ndays = 0; else badarg = 1; } else if (!strcmp(*args, "-nrequest")) { if (args[1]) { args++; accept_count = atol(*args); if (accept_count < 0) { BIO_printf(bio_err, "Illegal accept count %s\n", *args); badarg = 1; } } else badarg = 1; } else if (!strcmp(*args, "-ndays")) { if (args[1]) { args++; ndays = atol(*args); if (ndays < 0) { BIO_printf(bio_err, "Illegal update period %s\n", *args); badarg = 1; } } else badarg = 1; } else if (!strcmp(*args, "-rsigner")) { if (args[1]) { args++; rsignfile = *args; } else badarg = 1; } else if (!strcmp(*args, "-rkey")) { if (args[1]) { args++; rkeyfile = *args; } else badarg = 1; } else if (!strcmp(*args, "-rother")) { if (args[1]) { args++; rcertfile = *args; } else badarg = 1; } else if (!strcmp(*args, "-rmd")) { if (args[1]) { args++; rsign_md = EVP_get_digestbyname(*args); if (!rsign_md) badarg = 1; } else badarg = 1; } else if ((cert_id_md = EVP_get_digestbyname((*args) + 1)) == NULL) { badarg = 1; } args++; } /* Have we anything to do? */ if (!req && !reqin && !respin && !(port && ridx_filename)) badarg = 1; if (badarg) { BIO_printf(bio_err, "OCSP utility\n"); BIO_printf(bio_err, "Usage ocsp [options]\n"); BIO_printf(bio_err, "where options are\n"); BIO_printf(bio_err, "-out file output filename\n"); BIO_printf(bio_err, "-issuer file issuer certificate\n"); BIO_printf(bio_err, "-cert file certificate to check\n"); BIO_printf(bio_err, "-serial n serial number to check\n"); BIO_printf(bio_err, "-signer file certificate to sign OCSP request with\n"); BIO_printf(bio_err, "-signkey file private key to sign OCSP request with\n"); BIO_printf(bio_err, "-sign_other file additional certificates to include in signed request\n"); BIO_printf(bio_err, "-no_certs don't include any certificates in signed request\n"); BIO_printf(bio_err, "-req_text print text form of request\n"); BIO_printf(bio_err, "-resp_text print text form of response\n"); BIO_printf(bio_err, "-text print text form of request and response\n"); BIO_printf(bio_err, "-reqout file write DER encoded OCSP request to \"file\"\n"); BIO_printf(bio_err, "-respout file write DER encoded OCSP reponse to \"file\"\n"); BIO_printf(bio_err, "-reqin file read DER encoded OCSP request from \"file\"\n"); BIO_printf(bio_err, "-respin file read DER encoded OCSP reponse from \"file\"\n"); BIO_printf(bio_err, "-nonce add OCSP nonce to request\n"); BIO_printf(bio_err, "-no_nonce don't add OCSP nonce to request\n"); BIO_printf(bio_err, "-url URL OCSP responder URL\n"); BIO_printf(bio_err, "-host host:n send OCSP request to host on port n\n"); BIO_printf(bio_err, "-path path to use in OCSP request\n"); BIO_printf(bio_err, "-CApath dir trusted certificates directory\n"); BIO_printf(bio_err, "-CAfile file trusted certificates file\n"); BIO_printf(bio_err, "-trusted_first use locally trusted CA's first when building trust chain\n"); BIO_printf(bio_err, "-no_alt_chains only ever use the first certificate chain found\n"); BIO_printf(bio_err, "-VAfile file validator certificates file\n"); BIO_printf(bio_err, "-validity_period n maximum validity discrepancy in seconds\n"); BIO_printf(bio_err, "-status_age n maximum status age in seconds\n"); BIO_printf(bio_err, "-noverify don't verify response at all\n"); BIO_printf(bio_err, "-verify_other file additional certificates to search for signer\n"); BIO_printf(bio_err, "-trust_other don't verify additional certificates\n"); BIO_printf(bio_err, "-no_intern don't search certificates contained in response for signer\n"); BIO_printf(bio_err, "-no_signature_verify don't check signature on response\n"); BIO_printf(bio_err, "-no_cert_verify don't check signing certificate\n"); BIO_printf(bio_err, "-no_chain don't chain verify response\n"); BIO_printf(bio_err, "-no_cert_checks don't do additional checks on signing certificate\n"); BIO_printf(bio_err, "-port num port to run responder on\n"); BIO_printf(bio_err, "-index file certificate status index file\n"); BIO_printf(bio_err, "-CA file CA certificate\n"); BIO_printf(bio_err, "-rsigner file responder certificate to sign responses with\n"); BIO_printf(bio_err, "-rkey file responder key to sign responses with\n"); BIO_printf(bio_err, "-rother file other certificates to include in response\n"); BIO_printf(bio_err, "-resp_no_certs don't include any certificates in response\n"); BIO_printf(bio_err, "-nmin n number of minutes before next update\n"); BIO_printf(bio_err, "-ndays n number of days before next update\n"); BIO_printf(bio_err, "-resp_key_id identify reponse by signing certificate key ID\n"); BIO_printf(bio_err, "-nrequest n number of requests to accept (default unlimited)\n"); BIO_printf(bio_err, "-<dgst alg> use specified digest in the request\n"); BIO_printf(bio_err, "-timeout n timeout connection to OCSP responder after n seconds\n"); goto end; } if (outfile) out = BIO_new_file(outfile, "w"); else out = BIO_new_fp(stdout, BIO_NOCLOSE); if (!out) { BIO_printf(bio_err, "Error opening output file\n"); goto end; } if (!req && (add_nonce != 2)) add_nonce = 0; if (!req && reqin) { if (!strcmp(reqin, "-")) derbio = BIO_new_fp(stdin, BIO_NOCLOSE); else derbio = BIO_new_file(reqin, "rb"); if (!derbio) { BIO_printf(bio_err, "Error Opening OCSP request file\n"); goto end; } req = d2i_OCSP_REQUEST_bio(derbio, NULL); BIO_free(derbio); if (!req) { BIO_printf(bio_err, "Error reading OCSP request\n"); goto end; } } if (!req && port) { acbio = init_responder(port); if (!acbio) goto end; } if (rsignfile && !rdb) { if (!rkeyfile) rkeyfile = rsignfile; rsigner = load_cert(bio_err, rsignfile, FORMAT_PEM, NULL, e, "responder certificate"); if (!rsigner) { BIO_printf(bio_err, "Error loading responder certificate\n"); goto end; } rca_cert = load_cert(bio_err, rca_filename, FORMAT_PEM, NULL, e, "CA certificate"); if (rcertfile) { rother = load_certs(bio_err, rcertfile, FORMAT_PEM, NULL, e, "responder other certificates"); if (!rother) goto end; } rkey = load_key(bio_err, rkeyfile, FORMAT_PEM, 0, NULL, NULL, "responder private key"); if (!rkey) goto end; } if (acbio) BIO_printf(bio_err, "Waiting for OCSP client connections...\n"); redo_accept: if (acbio) { if (!do_responder(&req, &cbio, acbio, port)) goto end; if (!req) { resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL); send_ocsp_response(cbio, resp); goto done_resp; } } if (!req && (signfile || reqout || host || add_nonce || ridx_filename)) { BIO_printf(bio_err, "Need an OCSP request for this operation!\n"); goto end; } if (req && add_nonce) OCSP_request_add1_nonce(req, NULL, -1); if (signfile) { if (!keyfile) keyfile = signfile; signer = load_cert(bio_err, signfile, FORMAT_PEM, NULL, e, "signer certificate"); if (!signer) { BIO_printf(bio_err, "Error loading signer certificate\n"); goto end; } if (sign_certfile) { sign_other = load_certs(bio_err, sign_certfile, FORMAT_PEM, NULL, e, "signer certificates"); if (!sign_other) goto end; } key = load_key(bio_err, keyfile, FORMAT_PEM, 0, NULL, NULL, "signer private key"); if (!key) goto end; if (!OCSP_request_sign (req, signer, key, NULL, sign_other, sign_flags)) { BIO_printf(bio_err, "Error signing OCSP request\n"); goto end; } } if (req_text && req) OCSP_REQUEST_print(out, req, 0); if (reqout) { if (!strcmp(reqout, "-")) derbio = BIO_new_fp(stdout, BIO_NOCLOSE); else derbio = BIO_new_file(reqout, "wb"); if (!derbio) { BIO_printf(bio_err, "Error opening file %s\n", reqout); goto end; } i2d_OCSP_REQUEST_bio(derbio, req); BIO_free(derbio); } if (ridx_filename && (!rkey || !rsigner || !rca_cert)) { BIO_printf(bio_err, "Need a responder certificate, key and CA for this operation!\n"); goto end; } if (ridx_filename && !rdb) { rdb = load_index(ridx_filename, NULL); if (!rdb) goto end; if (!index_index(rdb)) goto end; } if (rdb) { i = make_ocsp_response(&resp, req, rdb, rca_cert, rsigner, rkey, rsign_md, rother, rflags, nmin, ndays, badsig); if (cbio) send_ocsp_response(cbio, resp); } else if (host) { # ifndef OPENSSL_NO_SOCK resp = process_responder(bio_err, req, host, path, port, use_ssl, headers, req_timeout); if (!resp) goto end; # else BIO_printf(bio_err, "Error creating connect BIO - sockets not supported.\n"); goto end; # endif } else if (respin) { if (!strcmp(respin, "-")) derbio = BIO_new_fp(stdin, BIO_NOCLOSE); else derbio = BIO_new_file(respin, "rb"); if (!derbio) { BIO_printf(bio_err, "Error Opening OCSP response file\n"); goto end; } resp = d2i_OCSP_RESPONSE_bio(derbio, NULL); BIO_free(derbio); if (!resp) { BIO_printf(bio_err, "Error reading OCSP response\n"); goto end; } } else { ret = 0; goto end; } done_resp: if (respout) { if (!strcmp(respout, "-")) derbio = BIO_new_fp(stdout, BIO_NOCLOSE); else derbio = BIO_new_file(respout, "wb"); if (!derbio) { BIO_printf(bio_err, "Error opening file %s\n", respout); goto end; } i2d_OCSP_RESPONSE_bio(derbio, resp); BIO_free(derbio); } i = OCSP_response_status(resp); if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) { BIO_printf(out, "Responder Error: %s (%d)\n", OCSP_response_status_str(i), i); if (ignore_err) goto redo_accept; ret = 0; goto end; } if (resp_text) OCSP_RESPONSE_print(out, resp, 0); /* If running as responder don't verify our own response */ if (cbio) { if (accept_count > 0) accept_count--; /* Redo if more connections needed */ if (accept_count) { BIO_free_all(cbio); cbio = NULL; OCSP_REQUEST_free(req); req = NULL; OCSP_RESPONSE_free(resp); resp = NULL; goto redo_accept; } ret = 0; goto end; } else if (ridx_filename) { ret = 0; goto end; } if (!store) store = setup_verify(bio_err, CAfile, CApath); if (!store) goto end; if (vpm) X509_STORE_set1_param(store, vpm); if (verify_certfile) { verify_other = load_certs(bio_err, verify_certfile, FORMAT_PEM, NULL, e, "validator certificate"); if (!verify_other) goto end; } bs = OCSP_response_get1_basic(resp); if (!bs) { BIO_printf(bio_err, "Error parsing response\n"); goto end; } ret = 0; if (!noverify) { if (req && ((i = OCSP_check_nonce(req, bs)) <= 0)) { if (i == -1) BIO_printf(bio_err, "WARNING: no nonce in response\n"); else { BIO_printf(bio_err, "Nonce Verify error\n"); ret = 1; goto end; } } i = OCSP_basic_verify(bs, verify_other, store, verify_flags); if (i <= 0) { BIO_printf(bio_err, "Response Verify Failure\n"); ERR_print_errors(bio_err); ret = 1; } else BIO_printf(bio_err, "Response verify OK\n"); } if (!print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage)) ret = 1; end: ERR_print_errors(bio_err); X509_free(signer); X509_STORE_free(store); if (vpm) X509_VERIFY_PARAM_free(vpm); EVP_PKEY_free(key); EVP_PKEY_free(rkey); X509_free(issuer); X509_free(cert); X509_free(rsigner); X509_free(rca_cert); free_index(rdb); BIO_free_all(cbio); BIO_free_all(acbio); BIO_free(out); OCSP_REQUEST_free(req); OCSP_RESPONSE_free(resp); OCSP_BASICRESP_free(bs); sk_OPENSSL_STRING_free(reqnames); sk_OCSP_CERTID_free(ids); sk_X509_pop_free(sign_other, X509_free); sk_X509_pop_free(verify_other, X509_free); sk_CONF_VALUE_pop_free(headers, X509V3_conf_free); if (thost) OPENSSL_free(thost); if (tport) OPENSSL_free(tport); if (tpath) OPENSSL_free(tpath); OPENSSL_EXIT(ret); }
int main (int argc, char **argv) { ocConfig conf; pid_t pid, sid; char input_buffer[9]; __android_log_write(ANDROID_LOG_INFO, APPNAME, "Starting service."); if (load_config(&conf) == -1) { __android_log_write(ANDROID_LOG_ERROR, APPNAME, "Unable to load configuration. Stopping."); return 1; } input_buffer[0] = 0; pid = fork(); if (pid < 0) exit(2); if (pid > 0) exit(0); umask(0); sid = setsid(); if (sid < 0) exit(2); if ((chdir("/")) < 0) exit(2); close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); while (1) { if (read_from_file(SYS_WAKE, 6, input_buffer) == -1) { __android_log_write(ANDROID_LOG_ERROR, APPNAME, "Unable to get data from file. Cannot continue."); return 1; } if (strcmp(input_buffer, "awake") == 0) { __android_log_write(ANDROID_LOG_INFO, APPNAME, "Setting awake profile."); if (0 !=set_cpu1_online(1)) __android_log_write(ANDROID_LOG_INFO, APPNAME, "Failed setting awake profile for cpu1."); set_cpu_params(conf.wake_governor, conf.wake_min_freq, conf.wake_max_freq); } input_buffer[0] = '\0'; if (read_from_file(SYS_SLEEP, 9, input_buffer) == -1) { __android_log_write(ANDROID_LOG_ERROR, APPNAME, "Unable to get data from file. Cannot continue."); return 1; } if (strcmp(input_buffer, "sleeping") == 0) { __android_log_write(ANDROID_LOG_INFO, APPNAME, "Setting sleep profile."); set_cpu1_online(0); set_cpu_params(conf.sleep_governor, conf.sleep_min_freq, conf.sleep_max_freq); } input_buffer[0] = '\0'; } return 0; }
int main(int argc, char **argv) { static int verbose = 0, debug = 0, validate = 0; static struct option long_options[] = { {"config", required_argument, NULL, 'c'}, {"validate", no_argument, &validate, 1}, {"debug", no_argument, &debug, 1}, {"version", no_argument, NULL, 'v'}, {"verbose", no_argument, &verbose, 1}, {"get-socketpath", no_argument, NULL, 'p'}, {0, 0, 0, 0} }; /* Signal handling */ signal(SIGCHLD, sigchld_handle); setenv("WLC_DIM", "0", 0); wlc_log_set_handler(wlc_log_handler); /* Changing code earlier than this point requires detailed review */ if (!wlc_init(&interface, argc, argv)) { return 1; } char *config_path = NULL; int c; while (1) { int option_index = 0; c = getopt_long(argc, argv, "CdvVpc:", long_options, &option_index); if (c == -1) { break; } switch (c) { case 0: // Flag break; case 'c': // config config_path = strdup(optarg); break; case 'C': // validate validate = 1; break; case 'd': // debug debug = 1; break; case 'v': // version #if defined SWAY_GIT_VERSION && defined SWAY_GIT_BRANCH && defined SWAY_VERSION_DATE fprintf(stdout, "sway version %s (%s, branch \"%s\")\n", SWAY_GIT_VERSION, SWAY_VERSION_DATE, SWAY_GIT_BRANCH); #else fprintf(stdout, "version not detected\n"); #endif exit(0); break; case 'V': // verbose verbose = 1; break; case 'p': // --get-socketpath // TODO break; } } if (debug) { init_log(L_DEBUG); } else if (verbose || validate) { init_log(L_INFO); } else { init_log(L_ERROR); } if (validate) { bool valid = load_config(config_path); return valid ? 0 : 1; } init_layout(); if (!load_config(config_path)) { sway_log(L_ERROR, "Error(s) loading config!"); } if (config_path) { free(config_path); } ipc_init(); if (!terminate_request) { wlc_run(); } ipc_terminate(); return 0; }
int pxy_setting_init() { int r; config_item *item = calloc(1, sizeof(*item)); if (!item) { E("malloc config_item error"); return -1; } FILE *file = fopen(conf_file, "r"); if (file == NULL) { file = stdin; } while((r = load_config(file,item)) != 0) { if (r == -1) { continue; } if (strcmp(item->name,"log_level") == 0) { setting.log_level = atoi(item->value); log_level = setting.log_level; } if (strcmp(item->name,"log_file") == 0) { int len = strlen(item->value) + 1; strncpy(setting.log_file, item->value, len); if (strcmp(setting.log_file, "stdout") == 0 || strcmp(setting.log_file, "stderr") == 0) { log_file = stdout; } else { log_file = fopen(setting.log_file, "a"); if (NULL == log_file) { log_file = stdout; E("LOG FILE open failed!"); goto ERROR; } fclose(log_file); } } if (strcmp(item->name,"client_port") == 0) setting.client_port= atoi(item->value); if (strcmp(item->name,"backend_port") == 0) setting.backend_port = atoi(item->value); if (strcmp(item->name,"ip") == 0) strcpy(setting.ip, item->value); if (strcmp(item->name,"route_log_level") == 0) { setting.route_log_level = atoi(item->value); route_set_loglevel(setting.route_log_level); } if (strcmp(item->name,"route_log_file") == 0) { strcpy(setting.route_log_file, item->value); } if (strcmp(item->name, "route_server_port") == 0) { setting.route_server_port = atoi(item->value); } if (strcmp(item->name, "flush_log") == 0) { setting.is_flush_log = atoi(item->value); } if (strcmp(item->name, "check_client_alive_time") == 0) { setting.check_client_alive_time = atoi(item->value); } if (strcmp(item->name, "transaction_timeout") == 0) { setting.transaction_timeout = atoi(item->value); } if (strcmp(item->name, "zk_url") == 0) strcpy(setting.zk_url, item->value); if (strcmp(item->name,"dblog_host") == 0) { strcpy(setting.dblog_host, item->value); } if (strcmp(item->name,"dblog_user") == 0) { strcpy(setting.dblog_user, item->value); } if (strcmp(item->name,"dblog_passwd") == 0) { strcpy(setting.dblog_passwd, item->value); } if (strcmp(item->name,"dblog_db") == 0) { strcpy(setting.dblog_db, item->value); } if (strcmp(item->name,"dblog_port") == 0) { setting.dblog_port = atoi(item->value); } memset(item, 0, sizeof(*item)); } free(item); E("setting inited: setting.log_level %d, log_file %s, client_port %d," "backend_port %d, ip %s, route_log_level %d, " "route_log_file %s, route_server_port %d, zk_url %s, " "check_client_alive_time %d, transaction_timeout %d, " "flush_log %d, dblog_host %s, dblog_user %s, " "dblog_passwd %s, dblog_db %s, dblog_port %d", setting.log_level, setting.log_file, setting.client_port, setting.backend_port, setting.ip, setting.route_log_level, setting.route_log_file, setting.route_server_port, setting.zk_url, setting.check_client_alive_time, setting.transaction_timeout, setting.is_flush_log, setting.dblog_host, setting.dblog_user, setting.dblog_passwd, setting.dblog_db, setting.dblog_port); return 0; ERROR: if (file != stdin) { fclose(file); } if (item) { free(item); } return -1; }
int main(int argc, char* argv[]){ int socket_fd; if((socket_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))< 0){ printf("socket error %s\n", strerror(errno)); exit(1); } struct sockaddr_in servaddr; if(!load_config(&servaddr)){ printf("config file error\n"); exit(0); } // servaddr.sin_family = AF_INET; // char* addr = "23.105.194.17"; // if(inet_aton(addr, (struct in_addr*)&servaddr.sin_addr) == 0){ // printf("aton error %s\n", strerror(errno)); // exit(1); // } // servaddr.sin_port = htons(80); if(bind(socket_fd, (const struct sockaddr*)&servaddr, sizeof(servaddr)) < 0){ printf("bind error %s\n", strerror(errno)); exit(1); } if(listen(socket_fd, 100) < 0){ printf("listen error %s\n", strerror(errno)); exit(1); } struct sockaddr_in cliaddr; int size = sizeof(cliaddr); int len; struct sockaddr_in localaddr; len = sizeof(struct sockaddr_in); getsockname(socket_fd, (struct sockaddr*)&localaddr, &len); uint16_t port = ntohs(localaddr.sin_port); char* addr = inet_ntoa(localaddr.sin_addr); printf("addr: %s port: %d\n", addr, port); int page_fd = open("./page/test.html",O_RDONLY); if (page_fd == -1){ printf("page file open error %s\n", strerror(errno)); exit(1); } int file_size = get_file_size(page_fd); void* file_addr = mmap(0, file_size, PROT_READ, MAP_SHARED, page_fd, 0); if(file_addr == MAP_FAILED){ printf("file map error %s\n", strerror(errno)); exit(1); } int max_fd = socket_fd; fd_set readable; FD_ZERO(&readable); FD_SET(socket_fd, &readable); int flags = fcntl(socket_fd, F_GETFL, 0); fcntl(socket_fd, F_SETFL, flags | O_NONBLOCK); // struct fd_list list ; //list.head=NULL; //list.tail = NULL; //list.nodes_count = 0; //add_fd(socket_fd, &list); for(;;){ fd_set temp = readable; if(select(max_fd+1, &readable, NULL, NULL, NULL) < 0){ printf("select error\n"); } int ready_fd; for(ready_fd = 0;ready_fd<=max_fd;ready_fd++){ if(FD_ISSET(ready_fd, &readable)){ break; } } readable = temp; if(ready_fd == socket_fd){ int serv_fd = accept(socket_fd, (struct sockaddr*)&cliaddr, &size); if(serv_fd == -1) continue; FD_SET(serv_fd, &readable); max_fd = serv_fd>max_fd?serv_fd:max_fd; } else { handle_task(ready_fd, file_size, file_addr); FD_CLR(ready_fd, &readable); } } }
int pkcs8_main(int argc, char **argv) { ENGINE *e = NULL; char **args, *infile = NULL, *outfile = NULL; char *passargin = NULL, *passargout = NULL; BIO *in = NULL, *out = NULL; int topk8 = 0; int pbe_nid = -1; const EVP_CIPHER *cipher = NULL; int iter = PKCS12_DEFAULT_ITER; int informat, outformat; int p8_broken = PKCS8_OK; int nocrypt = 0; X509_SIG *p8 = NULL; PKCS8_PRIV_KEY_INFO *p8inf = NULL; EVP_PKEY *pkey = NULL; char pass[50], *passin = NULL, *passout = NULL, *p8pass = NULL; int badarg = 0; int ret = 1; #ifndef OPENSSL_NO_ENGINE char *engine = NULL; #endif if (!load_config(bio_err, NULL)) goto end; informat = FORMAT_PEM; outformat = FORMAT_PEM; ERR_load_crypto_strings(); OpenSSL_add_all_algorithms(); args = argv + 1; while (!badarg && *args && *args[0] == '-') { if (!strcmp(*args, "-v2")) { if (args[1]) { args++; cipher = EVP_get_cipherbyname(*args); if (!cipher) { BIO_printf(bio_err, "Unknown cipher %s\n", *args); badarg = 1; } } else badarg = 1; } else if (!strcmp(*args, "-v1")) { if (args[1]) { args++; pbe_nid = OBJ_txt2nid(*args); if (pbe_nid == NID_undef) { BIO_printf(bio_err, "Unknown PBE algorithm %s\n", *args); badarg = 1; } } else badarg = 1; } else if (!strcmp(*args, "-inform")) { if (args[1]) { args++; informat = str2fmt(*args); } else badarg = 1; } else if (!strcmp(*args, "-outform")) { if (args[1]) { args++; outformat = str2fmt(*args); } else badarg = 1; } else if (!strcmp(*args, "-topk8")) topk8 = 1; else if (!strcmp(*args, "-noiter")) iter = 1; else if (!strcmp(*args, "-nocrypt")) nocrypt = 1; else if (!strcmp(*args, "-nooct")) p8_broken = PKCS8_NO_OCTET; else if (!strcmp(*args, "-nsdb")) p8_broken = PKCS8_NS_DB; else if (!strcmp(*args, "-embed")) p8_broken = PKCS8_EMBEDDED_PARAM; else if (!strcmp(*args, "-passin")) { if (!args[1]) goto bad; passargin = *(++args); } else if (!strcmp(*args, "-passout")) { if (!args[1]) goto bad; passargout = *(++args); } #ifndef OPENSSL_NO_ENGINE else if (strcmp(*args, "-engine") == 0) { if (!args[1]) goto bad; engine = *(++args); } #endif else if (!strcmp(*args, "-in")) { if (args[1]) { args++; infile = *args; } else badarg = 1; } else if (!strcmp(*args, "-out")) { if (args[1]) { args++; outfile = *args; } else badarg = 1; } else badarg = 1; args++; } if (badarg) { bad: BIO_printf(bio_err, "Usage pkcs8 [options]\n"); BIO_printf(bio_err, "where options are\n"); BIO_printf(bio_err, "-in file input file\n"); BIO_printf(bio_err, "-inform X input format (DER or PEM)\n"); BIO_printf(bio_err, "-passin arg input file pass phrase source\n"); BIO_printf(bio_err, "-outform X output format (DER or PEM)\n"); BIO_printf(bio_err, "-out file output file\n"); BIO_printf(bio_err, "-passout arg output file pass phrase source\n"); BIO_printf(bio_err, "-topk8 output PKCS8 file\n"); BIO_printf(bio_err, "-nooct use (nonstandard) no octet format\n"); BIO_printf(bio_err, "-embed use (nonstandard) embedded DSA parameters format\n"); BIO_printf(bio_err, "-nsdb use (nonstandard) DSA Netscape DB format\n"); BIO_printf(bio_err, "-noiter use 1 as iteration count\n"); BIO_printf(bio_err, "-nocrypt use or expect unencrypted private key\n"); BIO_printf(bio_err, "-v2 alg use PKCS#5 v2.0 and cipher \"alg\"\n"); BIO_printf(bio_err, "-v1 obj use PKCS#5 v1.5 and cipher \"alg\"\n"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, " -engine e use engine e, possibly a hardware device.\n"); #endif goto end; } #ifndef OPENSSL_NO_ENGINE e = setup_engine(bio_err, engine, 0); #endif if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } if ((pbe_nid == -1) && !cipher) pbe_nid = NID_pbeWithMD5AndDES_CBC; if (infile) { if (!(in = BIO_new_file(infile, "rb"))) { BIO_printf(bio_err, "Can't open input file %s\n", infile); goto end; } } else in = BIO_new_fp(stdin, BIO_NOCLOSE); if (outfile) { if (!(out = BIO_new_file(outfile, "wb"))) { BIO_printf(bio_err, "Can't open output file %s\n", outfile); goto end; } } else { out = BIO_new_fp(stdout, BIO_NOCLOSE); } if (topk8) { pkey = load_key(bio_err, infile, informat, 1, passin, e, "key"); if (!pkey) goto end; if (!(p8inf = EVP_PKEY2PKCS8_broken(pkey, p8_broken))) { BIO_printf(bio_err, "Error converting key\n"); ERR_print_errors(bio_err); goto end; } if (nocrypt) { if (outformat == FORMAT_PEM) PEM_write_bio_PKCS8_PRIV_KEY_INFO(out, p8inf); else if (outformat == FORMAT_ASN1) i2d_PKCS8_PRIV_KEY_INFO_bio(out, p8inf); else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } } else { if (passout) p8pass = passout; else { p8pass = pass; if (EVP_read_pw_string(pass, sizeof pass, "Enter Encryption Password:"******"Error encrypting key\n"); ERR_print_errors(bio_err); goto end; } if (outformat == FORMAT_PEM) PEM_write_bio_PKCS8(out, p8); else if (outformat == FORMAT_ASN1) i2d_PKCS8_bio(out, p8); else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } } ret = 0; goto end; } if (nocrypt) { if (informat == FORMAT_PEM) p8inf = PEM_read_bio_PKCS8_PRIV_KEY_INFO(in, NULL, NULL, NULL); else if (informat == FORMAT_ASN1) p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(in, NULL); else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } } else { if (informat == FORMAT_PEM) p8 = PEM_read_bio_PKCS8(in, NULL, NULL, NULL); else if (informat == FORMAT_ASN1) p8 = d2i_PKCS8_bio(in, NULL); else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } if (!p8) { BIO_printf(bio_err, "Error reading key\n"); ERR_print_errors(bio_err); goto end; } if (passin) p8pass = passin; else { p8pass = pass; EVP_read_pw_string(pass, sizeof pass, "Enter Password:"******"Error decrypting key\n"); ERR_print_errors(bio_err); goto end; } if (!(pkey = EVP_PKCS82PKEY(p8inf))) { BIO_printf(bio_err, "Error converting key\n"); ERR_print_errors(bio_err); goto end; } if (p8inf->broken) { BIO_printf(bio_err, "Warning: broken key encoding: "); switch (p8inf->broken) { case PKCS8_NO_OCTET: BIO_printf(bio_err, "No Octet String in PrivateKey\n"); break; case PKCS8_EMBEDDED_PARAM: BIO_printf(bio_err, "DSA parameters included in PrivateKey\n"); break; case PKCS8_NS_DB: BIO_printf(bio_err, "DSA public key include in PrivateKey\n"); break; case PKCS8_NEG_PRIVKEY: BIO_printf(bio_err, "DSA private key value is negative\n"); break; default: BIO_printf(bio_err, "Unknown broken type\n"); break; } } if (outformat == FORMAT_PEM) PEM_write_bio_PrivateKey(out, pkey, NULL, NULL, 0, NULL, passout); else if (outformat == FORMAT_ASN1) i2d_PrivateKey_bio(out, pkey); else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } ret = 0; end: X509_SIG_free(p8); PKCS8_PRIV_KEY_INFO_free(p8inf); EVP_PKEY_free(pkey); BIO_free_all(out); BIO_free(in); free(passin); free(passout); return ret; }
static void do_load(void) { switch_mutex_lock(MUTEX); load_config(); switch_mutex_unlock(MUTEX); }
int main(int argc, char** argv){ int i; char buffer[256]; char* tk; FILTERCHAIN* tmp_chn; FILTERCHAIN* del_chn; HARNESS_INSTANCE* hinstance; if(harness_init(argc,argv,&hinstance)){ printf("Error: Initialization failed.\n"); skygw_log_write(LOGFILE_ERROR,"Error: Initialization failed.\n"); skygw_logmanager_done(); skygw_logmanager_exit(); return 1; } if(instance.verbose){ printf("\n\n\tFilter Test Harness\n\n"); } while(instance.running){ printf("Harness> "); memset(buffer,0,256); fgets(buffer,256,stdin); tk = strtok(buffer," \n"); switch(user_input(tk)) { case RUNFILTERS: if(instance.head->next == NULL){ printf("No filters loaded.\n"); break; } if(instance.buffer == NULL){ if(instance.infile<0){ manual_query(); }else{ load_query(); } } route_buffers(); break; case LOAD_FILTER: tk = strtok(NULL," \n"); tmp_chn = load_filter_module(tk); if(!tmp_chn || !load_filter(tmp_chn,instance.conf)){ printf("Error creating filter instance.\n"); skygw_log_write(LOGFILE_ERROR,"Error: Error creating filter instance.\n"); }else{ instance.head = tmp_chn; } break; case DELETE_FILTER: tk = strtok(NULL," \n\0"); tmp_chn = instance.head; del_chn = instance.head; if(tk){ if(strcmp(instance.head->name,tk) == 0){ instance.head = instance.head->next; }else{ while(del_chn->next){ if(strcmp(del_chn->name,tk) == 0){ tmp_chn->next = del_chn->next; break; }else{ tmp_chn = del_chn; del_chn = del_chn->next; } } } if(del_chn && del_chn->next){ printf("Deleted %s.\n",del_chn->name); if(del_chn->instance){ del_chn->instance->freeSession(del_chn->filter,del_chn->session); } free(del_chn->filter); free(del_chn->down); free(del_chn->name); free(del_chn); }else{ printf("No matching filter found.\n"); } } break; case LOAD_CONFIG: tk = strtok(NULL," \n\0"); if(!load_config(tk)){ free_filters(); } break; case SET_INFILE: tk = strtok(NULL," \n\0"); if(instance.infile >= 0){ close(instance.infile); free(instance.infile_name); } if(tk!= NULL){ free_buffers(); instance.infile = open_file(tk,0); if(instance.infile >= 0){ load_query(); instance.infile_name = strdup(tk); if(instance.verbose){ printf("Loaded %d queries from file '%s'\n",instance.buffer_count,instance.infile_name); } } }else{ instance.infile = -1; printf("Queries are read from: command line\n"); } break; case SET_OUTFILE: tk = strtok(NULL," \n\0"); if(instance.outfile >= 0){ close(instance.outfile); free(instance.outfile_name); } if(tk!= NULL){ instance.outfile = open_file(tk,1); if(instance.outfile >= 0){ instance.outfile_name = strdup(tk); printf("Output is logged to: %s\n",tk); } }else{ instance.outfile = -1; printf("Output logging disabled.\n"); } break; case SESS_COUNT: tk = strtok(NULL," \n\0"); free_buffers(); free_filters(); instance.session_count = atoi(tk); printf("Sessions set to: %d\n", instance.session_count); break; case THR_COUNT: instance.running = 0; pthread_mutex_unlock(&instance.work_mtx); for(i = 0;i<instance.thrcount;i++){ pthread_join(instance.thrpool[i],NULL); } pthread_mutex_lock(&instance.work_mtx); instance.running = 1; tk = strtok(NULL," \n\0"); instance.thrcount = atoi(tk); void* t_thr_pool; if(!(t_thr_pool = realloc(instance.thrpool,instance.thrcount * sizeof(pthread_t)))){ printf("Error: Out of memory\n"); skygw_log_write(LOGFILE_ERROR,"Error: Out of memory\n"); instance.running = 0; break; } instance.thrpool = t_thr_pool; int thr_num = 1; for(i = 0;i<instance.thrcount;i++){ pthread_create(&instance.thrpool[i], NULL, (void*)work_buffer, (void*)thr_num++); } printf("Threads set to: %d\n", instance.thrcount); break; case QUIT: instance.running = 0; pthread_mutex_unlock(&instance.work_mtx); for(i = 0;i<instance.thrcount;i++){ pthread_join(instance.thrpool[i],NULL); } break; case UNDEFINED: printf("Command not found, enter \"help\" for a list of commands\n"); break; default: break; } } if(instance.infile >= 0){ close(instance.infile); } if(instance.outfile >= 0){ close(instance.outfile); } free_buffers(); free_filters(); skygw_logmanager_done(); skygw_logmanager_exit(); free(instance.head); return 0; }
void httpd_action(struct evhttp_request *req, void *arg) { struct evbuffer *buf; const char *authorization; char *v; if (!http_password) { LOG(logfile, "http-password not set in config file%s", ""); return; } buf = evbuffer_new(); authorization = evhttp_find_header(req->input_headers, "authorization"); if (!authorization || g_ascii_strncasecmp(authorization, "Basic ", 6) != 0) { evhttp_add_header(req->output_headers, "WWW-Authenticate", "Basic realm=\"Thrashd\""); evhttp_send_reply(req, 401, "Authorization Required", buf); evbuffer_free(buf); return; } gsize decoded_len; guchar *decoded = g_base64_decode(authorization+6, &decoded_len); char *colon = strchr((char*)decoded, ':'); if (!colon || decoded[0] == ':' || strcmp(colon+1, http_password) != 0) { g_free(decoded); evhttp_add_header(req->output_headers, "WWW-Authenticate", "Basic realm=\"Thrashd\""); evhttp_send_reply(req, 401, "Authorization Required", buf); evbuffer_free(buf); return; } struct evkeyvalq args; evhttp_parse_query(req->uri, &args); char *action = (char *)evhttp_find_header(&args, "action"); char *key = (char *)evhttp_find_header(&args, "key"); char *redir = "config.html"; if (!action || !key) { evhttp_clear_headers(&args); g_free(decoded); return; } LOG(logfile, "webaction user:%.*s action:%s key:%s", (int)((char *)colon-(char *)decoded), decoded, action, key); if (strcmp(action, "removeHolddown") == 0) { redir = "holddowns.html"; uint128_t s6addr; blocked_node_t *bnode; inet_pton(AF_INET6, key, s6addr); if ((bnode = g_tree_lookup(current_blocks, &s6addr))) expire_bnode(0, 0, bnode); } else if (strcmp(action, "removeAddr") == 0) { redir = "addrs.html"; qstats_t *stats = g_hash_table_lookup(addr_table, key); if (stats) expire_stats_node(0, 0, stats); } else if (strcmp(action, "blockAddr") == 0) { redir = "addrs.html"; qstats_t *stats = g_hash_table_lookup(addr_table, key); if (stats) block_addr(0, stats->s6addr, "web:blockAddr"); } else if (strcmp(action, "removeUri") == 0) { redir = "uris.html"; qstats_t *stats = g_hash_table_lookup(uri_table, key); if (stats) expire_stats_node(0, 0, stats); } else if (strcmp(action, "blockUri") == 0) { redir = "uris.html"; qstats_t *stats = g_hash_table_lookup(uri_table, key); if (stats) block_addr(0, stats->s6addr, "web:blockUri"); } else if (strcmp(action, "removeHost") == 0) { redir = "hosts.html"; qstats_t *stats = g_hash_table_lookup(host_table, key); if (stats) expire_stats_node(0, 0, stats); } else if (strcmp(action, "blockHost") == 0) { redir = "hosts.html"; qstats_t *stats = g_hash_table_lookup(host_table, key); if (stats) block_addr(0, stats->s6addr, "web:blockHost"); } else if (strcmp(action, "updateurl") == 0) { redir = "config.html"; block_ratio_t *request_uri_ratio = g_hash_table_lookup(uris_ratio_table, key); if (!request_uri_ratio) { request_uri_ratio = malloc(sizeof(block_ratio_t)); g_hash_table_insert(uris_ratio_table, g_strdup(key), request_uri_ratio); request_uri_ratio->num_connections = uri_ratio.num_connections; request_uri_ratio->timelimit = uri_ratio.timelimit; } if ((v = (char *)evhttp_find_header(&args, "hit"))) request_uri_ratio->num_connections = atoi(v); if ((v = (char *)evhttp_find_header(&args, "sec"))) request_uri_ratio->timelimit = atoi(v); } else if (strcmp(action, "reloadconfig") == 0) { redir = "config.html"; load_config(TRUE); } evhttp_add_header(req->output_headers, "Location", redir); evhttp_send_reply(req, 302, "Redirection", buf); evhttp_clear_headers(&args); g_free(decoded); }
static void fsm_init(void) { load_config(); triton_event_register_handler(EV_CONFIG_RELOAD, (triton_event_func)load_config); }
int MAIN(int argc, char **argv) { BN_GENCB cb; # ifndef OPENSSL_NO_ENGINE ENGINE *e = NULL; # endif int ret = 1; int i, num = DEFBITS; long l; const EVP_CIPHER *enc = NULL; unsigned long f4 = RSA_F4; char *outfile = NULL; char *passargout = NULL, *passout = NULL; # ifndef OPENSSL_NO_ENGINE char *engine = NULL; # endif char *inrand = NULL; BIO *out = NULL; BIGNUM *bn = BN_new(); RSA *rsa = NULL; if (!bn) goto err; apps_startup(); BN_GENCB_set(&cb, genrsa_cb, bio_err); if (bio_err == NULL) if ((bio_err = BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT); if (!load_config(bio_err, NULL)) goto err; if ((out = BIO_new(BIO_s_file())) == NULL) { BIO_printf(bio_err, "unable to create BIO for output\n"); goto err; } argv++; argc--; for (;;) { if (argc <= 0) break; if (strcmp(*argv, "-out") == 0) { if (--argc < 1) goto bad; outfile = *(++argv); } else if (strcmp(*argv, "-3") == 0) f4 = 3; else if (strcmp(*argv, "-F4") == 0 || strcmp(*argv, "-f4") == 0) f4 = RSA_F4; # ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv, "-engine") == 0) { if (--argc < 1) goto bad; engine = *(++argv); } # endif else if (strcmp(*argv, "-rand") == 0) { if (--argc < 1) goto bad; inrand = *(++argv); } # ifndef OPENSSL_NO_DES else if (strcmp(*argv, "-des") == 0) enc = EVP_des_cbc(); else if (strcmp(*argv, "-des3") == 0) enc = EVP_des_ede3_cbc(); # endif # ifndef OPENSSL_NO_IDEA else if (strcmp(*argv, "-idea") == 0) enc = EVP_idea_cbc(); # endif # ifndef OPENSSL_NO_SEED else if (strcmp(*argv, "-seed") == 0) enc = EVP_seed_cbc(); # endif # ifndef OPENSSL_NO_AES else if (strcmp(*argv, "-aes128") == 0) enc = EVP_aes_128_cbc(); else if (strcmp(*argv, "-aes192") == 0) enc = EVP_aes_192_cbc(); else if (strcmp(*argv, "-aes256") == 0) enc = EVP_aes_256_cbc(); # endif # ifndef OPENSSL_NO_CAMELLIA else if (strcmp(*argv, "-camellia128") == 0) enc = EVP_camellia_128_cbc(); else if (strcmp(*argv, "-camellia192") == 0) enc = EVP_camellia_192_cbc(); else if (strcmp(*argv, "-camellia256") == 0) enc = EVP_camellia_256_cbc(); # endif else if (strcmp(*argv, "-passout") == 0) { if (--argc < 1) goto bad; passargout = *(++argv); } else break; argv++; argc--; } if ((argc >= 1) && ((sscanf(*argv, "%d", &num) == 0) || (num < 0))) { bad: BIO_printf(bio_err, "usage: genrsa [args] [numbits]\n"); BIO_printf(bio_err, " -des encrypt the generated key with DES in cbc mode\n"); BIO_printf(bio_err, " -des3 encrypt the generated key with DES in ede cbc mode (168 bit key)\n"); # ifndef OPENSSL_NO_IDEA BIO_printf(bio_err, " -idea encrypt the generated key with IDEA in cbc mode\n"); # endif # ifndef OPENSSL_NO_SEED BIO_printf(bio_err, " -seed\n"); BIO_printf(bio_err, " encrypt PEM output with cbc seed\n"); # endif # ifndef OPENSSL_NO_AES BIO_printf(bio_err, " -aes128, -aes192, -aes256\n"); BIO_printf(bio_err, " encrypt PEM output with cbc aes\n"); # endif # ifndef OPENSSL_NO_CAMELLIA BIO_printf(bio_err, " -camellia128, -camellia192, -camellia256\n"); BIO_printf(bio_err, " encrypt PEM output with cbc camellia\n"); # endif BIO_printf(bio_err, " -out file output the key to 'file\n"); BIO_printf(bio_err, " -passout arg output file pass phrase source\n"); BIO_printf(bio_err, " -f4 use F4 (0x10001) for the E value\n"); BIO_printf(bio_err, " -3 use 3 for the E value\n"); # ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, " -engine e use engine e, possibly a hardware device.\n"); # endif BIO_printf(bio_err, " -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR); BIO_printf(bio_err, " load the file (or the files in the directory) into\n"); BIO_printf(bio_err, " the random number generator\n"); goto err; } ERR_load_crypto_strings(); if (!app_passwd(bio_err, NULL, passargout, NULL, &passout)) { BIO_printf(bio_err, "Error getting password\n"); goto err; } # ifndef OPENSSL_NO_ENGINE e = setup_engine(bio_err, engine, 0); # endif if (outfile == NULL) { BIO_set_fp(out, stdout, BIO_NOCLOSE); # ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } # endif } else { if (BIO_write_filename(out, outfile) <= 0) { perror(outfile); goto err; } } if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL && !RAND_status()) { BIO_printf(bio_err, "warning, not much extra random data, consider using the -rand option\n"); } if (inrand != NULL) BIO_printf(bio_err, "%ld semi-random bytes loaded\n", app_RAND_load_files(inrand)); BIO_printf(bio_err, "Generating RSA private key, %d bit long modulus\n", num); # ifdef OPENSSL_NO_ENGINE rsa = RSA_new(); # else rsa = RSA_new_method(e); # endif if (!rsa) goto err; if (!BN_set_word(bn, f4) || !RSA_generate_key_ex(rsa, num, bn, &cb)) goto err; app_RAND_write_file(NULL, bio_err); /* * We need to do the following for when the base number size is < long, * esp windows 3.1 :-(. */ l = 0L; for (i = 0; i < rsa->e->top; i++) { # ifndef SIXTY_FOUR_BIT l <<= BN_BITS4; l <<= BN_BITS4; # endif l += rsa->e->d[i]; } BIO_printf(bio_err, "e is %ld (0x%lX)\n", l, l); { PW_CB_DATA cb_data; cb_data.password = passout; cb_data.prompt_info = outfile; if (!PEM_write_bio_RSAPrivateKey(out, rsa, enc, NULL, 0, (pem_password_cb *)password_callback, &cb_data)) goto err; } ret = 0; err: if (bn) BN_free(bn); if (rsa) RSA_free(rsa); if (out) BIO_free_all(out); if (passout) OPENSSL_free(passout); if (ret != 0) ERR_print_errors(bio_err); apps_shutdown(); OPENSSL_EXIT(ret); }
int MAIN(int argc, char **argv) { DSA *dsa=NULL; int ret=1; char *outfile=NULL; char *inrand=NULL,*dsaparams=NULL; char *passargout = NULL, *passout = NULL; BIO *out=NULL,*in=NULL; const EVP_CIPHER *enc=NULL; #ifndef OPENSSL_NO_ENGINE char *engine=NULL; #endif apps_startup(); if (bio_err == NULL) if ((bio_err=BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err,OPENSSL_TYPE__FILE_STDERR,BIO_NOCLOSE|BIO_FP_TEXT); if (!load_config(bio_err, NULL)) goto end; argv++; argc--; for (;;) { if (argc <= 0) break; if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0) { if (--argc < 1) goto bad; outfile= *(++argv); } else if (TINYCLR_SSL_STRCMP(*argv,"-passout") == 0) { if (--argc < 1) goto bad; passargout= *(++argv); } #ifndef OPENSSL_NO_ENGINE else if (TINYCLR_SSL_STRCMP(*argv,"-engine") == 0) { if (--argc < 1) goto bad; engine= *(++argv); } #endif else if (TINYCLR_SSL_STRCMP(*argv,"-rand") == 0) { if (--argc < 1) goto bad; inrand= *(++argv); } else if (TINYCLR_SSL_STRCMP(*argv,"-") == 0) goto bad; #ifndef OPENSSL_NO_DES else if (TINYCLR_SSL_STRCMP(*argv,"-des") == 0) enc=EVP_des_cbc(); else if (TINYCLR_SSL_STRCMP(*argv,"-des3") == 0) enc=EVP_des_ede3_cbc(); #endif #ifndef OPENSSL_NO_IDEA else if (TINYCLR_SSL_STRCMP(*argv,"-idea") == 0) enc=EVP_idea_cbc(); #endif #ifndef OPENSSL_NO_SEED else if (TINYCLR_SSL_STRCMP(*argv,"-seed") == 0) enc=EVP_seed_cbc(); #endif #ifndef OPENSSL_NO_AES else if (TINYCLR_SSL_STRCMP(*argv,"-aes128") == 0) enc=EVP_aes_128_cbc(); else if (TINYCLR_SSL_STRCMP(*argv,"-aes192") == 0) enc=EVP_aes_192_cbc(); else if (TINYCLR_SSL_STRCMP(*argv,"-aes256") == 0) enc=EVP_aes_256_cbc(); #endif #ifndef OPENSSL_NO_CAMELLIA else if (TINYCLR_SSL_STRCMP(*argv,"-camellia128") == 0) enc=EVP_camellia_128_cbc(); else if (TINYCLR_SSL_STRCMP(*argv,"-camellia192") == 0) enc=EVP_camellia_192_cbc(); else if (TINYCLR_SSL_STRCMP(*argv,"-camellia256") == 0) enc=EVP_camellia_256_cbc(); #endif else if (**argv != '-' && dsaparams == NULL) { dsaparams = *argv; } else goto bad; argv++; argc--; } if (dsaparams == NULL) { bad: BIO_printf(bio_err,"usage: gendsa [args] dsaparam-file\n"); BIO_printf(bio_err," -out file - output the key to 'file'\n"); #ifndef OPENSSL_NO_DES BIO_printf(bio_err," -des - encrypt the generated key with DES in cbc mode\n"); BIO_printf(bio_err," -des3 - encrypt the generated key with DES in ede cbc mode (168 bit key)\n"); #endif #ifndef OPENSSL_NO_IDEA BIO_printf(bio_err," -idea - encrypt the generated key with IDEA in cbc mode\n"); #endif #ifndef OPENSSL_NO_SEED BIO_printf(bio_err," -seed\n"); BIO_printf(bio_err," encrypt PEM output with cbc seed\n"); #endif #ifndef OPENSSL_NO_AES BIO_printf(bio_err," -aes128, -aes192, -aes256\n"); BIO_printf(bio_err," encrypt PEM output with cbc aes\n"); #endif #ifndef OPENSSL_NO_CAMELLIA BIO_printf(bio_err," -camellia128, -camellia192, -camellia256\n"); BIO_printf(bio_err," encrypt PEM output with cbc camellia\n"); #endif #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err," -engine e - use engine e, possibly a hardware device.\n"); #endif BIO_printf(bio_err," -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR); BIO_printf(bio_err," - load the file (or the files in the directory) into\n"); BIO_printf(bio_err," the random number generator\n"); BIO_printf(bio_err," dsaparam-file\n"); BIO_printf(bio_err," - a DSA parameter file as generated by the dsaparam command\n"); goto end; } #ifndef OPENSSL_NO_ENGINE setup_engine(bio_err, engine, 0); #endif if(!app_passwd(bio_err, NULL, passargout, NULL, &passout)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } in=BIO_new(BIO_s_file()); if (!(BIO_read_filename(in,dsaparams))) { TINYCLR_SSL_PERROR(dsaparams); goto end; } if ((dsa=PEM_read_bio_DSAparams(in,NULL,NULL,NULL)) == NULL) { BIO_printf(bio_err,"unable to load DSA parameter file\n"); goto end; } BIO_free(in); in = NULL; out=BIO_new(BIO_s_file()); if (out == NULL) goto end; if (outfile == NULL) { BIO_set_fp(out,OPENSSL_TYPE__FILE_STDOUT,BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } #endif } else { if (BIO_write_filename(out,outfile) <= 0) { TINYCLR_SSL_PERROR(outfile); goto end; } } if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL) { BIO_printf(bio_err,"warning, not much extra random data, consider using the -rand option\n"); } if (inrand != NULL) BIO_printf(bio_err,"%ld semi-random bytes loaded\n", app_RAND_load_files(inrand)); BIO_printf(bio_err,"Generating DSA key, %d bits\n", BN_num_bits(dsa->p)); if (!DSA_generate_key(dsa)) goto end; app_RAND_write_file(NULL, bio_err); if (!PEM_write_bio_DSAPrivateKey(out,dsa,enc,NULL,0,NULL, passout)) goto end; ret=0; end: if (ret != 0) ERR_print_errors(bio_err); if (in != NULL) BIO_free(in); if (out != NULL) BIO_free_all(out); if (dsa != NULL) DSA_free(dsa); if(passout) OPENSSL_free(passout); apps_shutdown(); OPENSSL_EXIT(ret); }
/*! \brief Function which passes through an aliased CLI command to the real one */ static char *cli_alias_passthrough(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { struct cli_alias *alias; struct cli_alias tmp = { .cli_entry.command = e->command, }; char *generator; const char *line; /* Try to find the alias based on the CLI entry */ if (!(alias = ao2_find(cli_aliases, &tmp, OBJ_POINTER))) { return 0; } switch (cmd) { case CLI_INIT: ao2_ref(alias, -1); return NULL; case CLI_GENERATE: line = a->line; line += (strlen(alias->alias)); if (!strncasecmp(alias->alias, alias->real_cmd, strlen(alias->alias))) { generator = NULL; } else if (!ast_strlen_zero(a->word)) { struct ast_str *real_cmd = ast_str_alloca(strlen(alias->real_cmd) + strlen(line) + 1); ast_str_append(&real_cmd, 0, "%s%s", alias->real_cmd, line); generator = ast_cli_generator(ast_str_buffer(real_cmd), a->word, a->n); } else { generator = ast_cli_generator(alias->real_cmd, a->word, a->n); } ao2_ref(alias, -1); return generator; } /* If they gave us extra arguments we need to construct a string to pass in */ if (a->argc != e->args) { struct ast_str *real_cmd = ast_str_alloca(2048); int i; ast_str_append(&real_cmd, 0, "%s", alias->real_cmd); /* Add the additional arguments that have been passed in */ for (i = e->args + 1; i <= a->argc; i++) { ast_str_append(&real_cmd, 0, " %s", a->argv[i - 1]); } ast_cli_command(a->fd, ast_str_buffer(real_cmd)); } else { ast_cli_command(a->fd, alias->real_cmd); } ao2_ref(alias, -1); return CLI_SUCCESS; } /*! \brief CLI Command to display CLI Aliases */ static char *alias_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a) { #define FORMAT "%-50.50s %-50.50s\n" struct cli_alias *alias; struct ao2_iterator i; switch (cmd) { case CLI_INIT: e->command = "cli show aliases"; e->usage = "Usage: cli show aliases\n" " Displays a list of aliased CLI commands.\n"; return NULL; case CLI_GENERATE: return NULL; } ast_cli(a->fd, FORMAT, "Alias Command", "Real Command"); i = ao2_iterator_init(cli_aliases, 0); for (; (alias = ao2_iterator_next(&i)); ao2_ref(alias, -1)) { ast_cli(a->fd, FORMAT, alias->alias, alias->real_cmd); } ao2_iterator_destroy(&i); return CLI_SUCCESS; #undef FORMAT } /*! \brief CLI commands to interact with things */ static struct ast_cli_entry cli_alias[] = { AST_CLI_DEFINE(alias_show, "Show CLI command aliases"), }; /*! \brief Function called to load or reload the configuration file */ static void load_config(int reload) { struct ast_config *cfg = NULL; struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 }; struct cli_alias *alias; struct ast_variable *v, *v1; if (!(cfg = ast_config_load(config_file, config_flags)) || cfg == CONFIG_STATUS_FILEINVALID) { ast_log(LOG_ERROR, "res_clialiases configuration file '%s' not found\n", config_file); return; } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) { return; } /* Destroy any existing CLI aliases */ if (reload) { ao2_callback(cli_aliases, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, alias_unregister_cb, NULL); } for (v = ast_variable_browse(cfg, "general"); v; v = v->next) { if (strcmp(v->name, "template")) { ast_log(LOG_WARNING, "%s is not a correct option in [%s]\n", v->name, "general"); continue; } /* Read in those there CLI aliases */ for (v1 = ast_variable_browse(cfg, v->value); v1; v1 = v1->next) { struct cli_alias *existing = ao2_callback(cli_aliases, 0, alias_name_cb, (char*)v1->name); if (existing) { ast_log(LOG_WARNING, "Alias '%s' could not be unregistered and has been retained\n", existing->alias); ao2_ref(existing, -1); continue; } if (!(alias = ao2_alloc((sizeof(*alias) + strlen(v1->name) + strlen(v1->value) + 2), NULL))) { continue; } alias->alias = ((char *) alias) + sizeof(*alias); alias->real_cmd = ((char *) alias->alias) + strlen(v1->name) + 1; strcpy(alias->alias, v1->name); strcpy(alias->real_cmd, v1->value); alias->cli_entry.handler = cli_alias_passthrough; alias->cli_entry.command = alias->alias; alias->cli_entry.usage = "Aliased CLI Command\n"; if (ast_cli_register(&alias->cli_entry)) { ao2_ref(alias, -1); continue; } ao2_link(cli_aliases, alias); ast_verb(2, "Aliased CLI command '%s' to '%s'\n", v1->name, v1->value); ao2_ref(alias, -1); } } ast_config_destroy(cfg); return; } /*! \brief Function called to reload the module */ static int reload_module(void) { load_config(1); return 0; }
int main(int argc, char *argv[]) { service_location_t service = {0}; const char *host, *parent, *pid_file, *log_file; int i; if (argc < 2) { fprintf(stderr, "Usage: %s <config file>", argv[0]); exit(1); } /* Parse the configuration */ if (strlen(argv[1]) >= PATH_MAX) { LOG_WARN(stderr, "The config file path exceeds PATH_MAX, possibly truncating"); } strncpy(service.config_file, argv[1], PATH_MAX); if (load_config(&service) == false) { LOG_FATAL(stderr, "Failed to load configuration(%s): %s", service.config_file, strerror(errno)); exit(1); } /* Open log file */ log_file = iniparser_getstring(service.config, "main:log_file", MYSERVICES_LOG_FILE); if (strlen(log_file) >= PATH_MAX) { LOG_WARN(stderr, "The log_file path exceeds PATH_MAX, possibly truncating"); } strncpy(service.log_file, log_file, PATH_MAX); if (open_log_file(&service, service.log_file) == false) { LOG_FATAL(stderr, "Failed to open log file: %s", log_file, strerror(errno)); exit(1); } signal(SIGINT, SIG_IGN); signal(SIGKILL, SIG_IGN); if (fork() == 0) { int code; uid_t uid; gid_t gid; signal(SIGINT, SIG_DFL); signal(SIGKILL, SIG_DFL); if (gethostname(service.hostname, HOSTNAME_MAX)) { LOG_FATAL(service.log_fd, "Failed to gethostname: %s", strerror(errno)); exit(1); } /* Initialize service locations */ service_info_init(&(service.info)); if (service_info_parse(&service, &(service.info)) == false) { LOG_FATAL(service.log_fd, "Failed to parse service information"); exit(1); } if (resolve_uid_and_gid(&service, &uid, &gid) == false) { LOG_FATAL(service.log_fd, "Failed to resolve user/group"); exit(1); } pid_file = iniparser_getstring(service.config, "main:pid_file", MYSERVICES_PID_FILE); if (write_pid_file(&service, pid_file, uid, gid) == false) { LOG_FATAL(service.log_fd, "Failed to write pid file"); exit(1); } // Drop privileges and chown pid to the current user if (drop_privileges(uid, gid) == false) { LOG_FATAL(service.log_fd, "Failed to lower privileges: %s", strerror(errno)); exit(1); } fclose(stdin); fclose(stdout); do { /* ZooKeeper client floods the logs with messages if given a chance */ zoo_set_debug_level(0); if (connect_zookeeper(&service, true) == false) { LOG_FATAL(service.log_fd, "Failed to connect"); break; } if (false == run_myservices(&service)) { LOG_FATAL(service.log_fd, "Failed to run MyServices daemon"); break; } } while (0); /* Unlink pid-file */ if (unlink(pid_file) == -1) { LOG_FATAL(service.log_fd, "Failed to remove pid file (%s): %s", pid_file, strerror(errno)); } service_info_deinit(&(service.info)); if (service.config) iniparser_freedict(service.config); if (service.zk) zookeeper_close(service.zk); LOG_INFO(service.log_fd, "Terminating MyServices daemon.."); fclose(service.log_fd); exit(0); } else { signal(SIGINT, SIG_DFL); signal(SIGKILL, SIG_DFL); exit(0); } return 0; }
static int reload(void) { return load_config(1); }
int MAIN(int argc, char **argv) { BIO *in = NULL, *out = NULL; char *infile = NULL, *outfile = NULL, *sigfile = NULL; ENGINE *e = NULL; int pkey_op = EVP_PKEY_OP_SIGN, key_type = KEY_PRIVKEY; int keyform = FORMAT_PEM, peerform = FORMAT_PEM; char badarg = 0, rev = 0; char hexdump = 0, asn1parse = 0; EVP_PKEY_CTX *ctx = NULL; char *passargin = NULL; int keysize = -1; unsigned char *buf_in = NULL, *buf_out = NULL, *sig = NULL; size_t buf_outlen; int buf_inlen = 0, siglen = -1; int ret = 1, rv = -1; argc--; argv++; if (!bio_err) bio_err = BIO_new_fp(stderr, BIO_NOCLOSE); if (!load_config(bio_err, NULL)) goto end; ERR_load_crypto_strings(); OpenSSL_add_all_algorithms(); while (argc >= 1) { if (!strcmp(*argv, "-in")) { if (--argc < 1) badarg = 1; else infile = *(++argv); } else if (!strcmp(*argv, "-out")) { if (--argc < 1) badarg = 1; else outfile = *(++argv); } else if (!strcmp(*argv, "-sigfile")) { if (--argc < 1) badarg = 1; else sigfile = *(++argv); } else if (!strcmp(*argv, "-inkey")) { if (--argc < 1) badarg = 1; else { ctx = init_ctx(&keysize, *(++argv), keyform, key_type, passargin, pkey_op, e); if (!ctx) { BIO_puts(bio_err, "Error initializing context\n"); ERR_print_errors(bio_err); badarg = 1; } } } else if (!strcmp(*argv, "-peerkey")) { if (--argc < 1) badarg = 1; else if (!setup_peer(bio_err, ctx, peerform, *(++argv))) badarg = 1; } else if (!strcmp(*argv, "-passin")) { if (--argc < 1) badarg = 1; else passargin = *(++argv); } else if (strcmp(*argv, "-peerform") == 0) { if (--argc < 1) badarg = 1; else peerform = str2fmt(*(++argv)); } else if (strcmp(*argv, "-keyform") == 0) { if (--argc < 1) badarg = 1; else keyform = str2fmt(*(++argv)); } #ifndef OPENSSL_NO_ENGINE else if (!strcmp(*argv, "-engine")) { if (--argc < 1) badarg = 1; else e = setup_engine(bio_err, *(++argv), 0); } #endif else if (!strcmp(*argv, "-pubin")) key_type = KEY_PUBKEY; else if (!strcmp(*argv, "-certin")) key_type = KEY_CERT; else if (!strcmp(*argv, "-asn1parse")) asn1parse = 1; else if (!strcmp(*argv, "-hexdump")) hexdump = 1; else if (!strcmp(*argv, "-sign")) pkey_op = EVP_PKEY_OP_SIGN; else if (!strcmp(*argv, "-verify")) pkey_op = EVP_PKEY_OP_VERIFY; else if (!strcmp(*argv, "-verifyrecover")) pkey_op = EVP_PKEY_OP_VERIFYRECOVER; else if (!strcmp(*argv, "-rev")) rev = 1; else if (!strcmp(*argv, "-encrypt")) pkey_op = EVP_PKEY_OP_ENCRYPT; else if (!strcmp(*argv, "-decrypt")) pkey_op = EVP_PKEY_OP_DECRYPT; else if (!strcmp(*argv, "-derive")) pkey_op = EVP_PKEY_OP_DERIVE; else if (strcmp(*argv, "-pkeyopt") == 0) { if (--argc < 1) badarg = 1; else if (!ctx) { BIO_puts(bio_err, "-pkeyopt command before -inkey\n"); badarg = 1; } else if (pkey_ctrl_string(ctx, *(++argv)) <= 0) { BIO_puts(bio_err, "parameter setting error\n"); ERR_print_errors(bio_err); goto end; } } else badarg = 1; if (badarg) { usage(); goto end; } argc--; argv++; } if (!ctx) { usage(); goto end; } if (sigfile && (pkey_op != EVP_PKEY_OP_VERIFY)) { BIO_puts(bio_err, "Signature file specified for non verify\n"); goto end; } if (!sigfile && (pkey_op == EVP_PKEY_OP_VERIFY)) { BIO_puts(bio_err, "No signature file specified for verify\n"); goto end; } /* FIXME: seed PRNG only if needed */ app_RAND_load_file(NULL, bio_err, 0); if (pkey_op != EVP_PKEY_OP_DERIVE) { if (infile) { if (!(in = BIO_new_file(infile, "rb"))) { BIO_puts(bio_err, "Error Opening Input File\n"); ERR_print_errors(bio_err); goto end; } } else in = BIO_new_fp(stdin, BIO_NOCLOSE); } if (outfile) { if (!(out = BIO_new_file(outfile, "wb"))) { BIO_printf(bio_err, "Error Creating Output File\n"); ERR_print_errors(bio_err); goto end; } } else { out = BIO_new_fp(stdout, BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } #endif } if (sigfile) { BIO *sigbio = BIO_new_file(sigfile, "rb"); if (!sigbio) { BIO_printf(bio_err, "Can't open signature file %s\n", sigfile); goto end; } siglen = bio_to_mem(&sig, keysize * 10, sigbio); BIO_free(sigbio); if (siglen <= 0) { BIO_printf(bio_err, "Error reading signature data\n"); goto end; } } if (in) { /* Read the input data */ buf_inlen = bio_to_mem(&buf_in, keysize * 10, in); if (buf_inlen <= 0) { BIO_printf(bio_err, "Error reading input Data\n"); exit(1); } if (rev) { size_t i; unsigned char ctmp; size_t l = (size_t)buf_inlen; for (i = 0; i < l / 2; i++) { ctmp = buf_in[i]; buf_in[i] = buf_in[l - 1 - i]; buf_in[l - 1 - i] = ctmp; } } } if (pkey_op == EVP_PKEY_OP_VERIFY) { rv = EVP_PKEY_verify(ctx, sig, (size_t)siglen, buf_in, (size_t)buf_inlen); if (rv == 0) BIO_puts(out, "Signature Verification Failure\n"); else if (rv == 1) BIO_puts(out, "Signature Verified Successfully\n"); if (rv >= 0) goto end; } else { rv = do_keyop(ctx, pkey_op, NULL, (size_t *)&buf_outlen, buf_in, (size_t)buf_inlen); if (rv > 0) { buf_out = OPENSSL_malloc(buf_outlen); if (!buf_out) rv = -1; else rv = do_keyop(ctx, pkey_op, buf_out, (size_t *)&buf_outlen, buf_in, (size_t)buf_inlen); } } if (rv <= 0) { BIO_printf(bio_err, "Public Key operation error\n"); ERR_print_errors(bio_err); goto end; } ret = 0; if (asn1parse) { if (!ASN1_parse_dump(out, buf_out, buf_outlen, 1, -1)) ERR_print_errors(bio_err); } else if (hexdump) BIO_dump(out, (char *)buf_out, buf_outlen); else BIO_write(out, buf_out, buf_outlen); end: if (ctx) EVP_PKEY_CTX_free(ctx); BIO_free(in); BIO_free_all(out); if (buf_in) OPENSSL_free(buf_in); if (buf_out) OPENSSL_free(buf_out); if (sig) OPENSSL_free(sig); return ret; }
int MAIN(int argc, char **argv) { static const char magic[] = "Salted__"; char mbuf[sizeof magic - 1]; char *strbuf = NULL; unsigned char *buff = NULL, *bufsize = NULL; int bsize = BSIZE, verbose = 0; int ret = 1, inl; int nopad = 0; unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH]; unsigned char salt[PKCS5_SALT_LEN]; char *str = NULL, *passarg = NULL, *pass = NULL; char *hkey = NULL, *hiv = NULL, *hsalt = NULL; char *md = NULL; int enc = 1, printkey = 0, i, base64 = 0; #ifdef ZLIB int do_zlib = 0; BIO *bzl = NULL; #endif int debug = 0, olb64 = 0, nosalt = 0; const EVP_CIPHER *cipher = NULL, *c; EVP_CIPHER_CTX *ctx = NULL; char *inf = NULL, *outf = NULL; BIO *in = NULL, *out = NULL, *b64 = NULL, *benc = NULL, *rbio = NULL, *wbio = NULL; #define PROG_NAME_SIZE 39 char pname[PROG_NAME_SIZE + 1]; #ifndef OPENSSL_NO_ENGINE char *engine = NULL; #endif const EVP_MD *dgst = NULL; int non_fips_allow = 0; apps_startup(); if (bio_err == NULL) if ((bio_err = BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT); if (!load_config(bio_err, NULL)) goto end; /* first check the program name */ program_name(argv[0], pname, sizeof pname); if (strcmp(pname, "base64") == 0) base64 = 1; #ifdef ZLIB if (strcmp(pname, "zlib") == 0) do_zlib = 1; #endif cipher = EVP_get_cipherbyname(pname); #ifdef ZLIB if (!do_zlib && !base64 && (cipher == NULL) && (strcmp(pname, "enc") != 0)) #else if (!base64 && (cipher == NULL) && (strcmp(pname, "enc") != 0)) #endif { BIO_printf(bio_err, "%s is an unknown cipher\n", pname); goto bad; } argc--; argv++; while (argc >= 1) { if (strcmp(*argv, "-e") == 0) enc = 1; else if (strcmp(*argv, "-in") == 0) { if (--argc < 1) goto bad; inf = *(++argv); } else if (strcmp(*argv, "-out") == 0) { if (--argc < 1) goto bad; outf = *(++argv); } else if (strcmp(*argv, "-pass") == 0) { if (--argc < 1) goto bad; passarg = *(++argv); } #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv, "-engine") == 0) { if (--argc < 1) goto bad; engine = *(++argv); } #endif else if (strcmp(*argv, "-d") == 0) enc = 0; else if (strcmp(*argv, "-p") == 0) printkey = 1; else if (strcmp(*argv, "-v") == 0) verbose = 1; else if (strcmp(*argv, "-nopad") == 0) nopad = 1; else if (strcmp(*argv, "-salt") == 0) nosalt = 0; else if (strcmp(*argv, "-nosalt") == 0) nosalt = 1; else if (strcmp(*argv, "-debug") == 0) debug = 1; else if (strcmp(*argv, "-P") == 0) printkey = 2; else if (strcmp(*argv, "-A") == 0) olb64 = 1; else if (strcmp(*argv, "-a") == 0) base64 = 1; else if (strcmp(*argv, "-base64") == 0) base64 = 1; #ifdef ZLIB else if (strcmp(*argv, "-z") == 0) do_zlib = 1; #endif else if (strcmp(*argv, "-bufsize") == 0) { if (--argc < 1) goto bad; bufsize = (unsigned char *)*(++argv); } else if (strcmp(*argv, "-k") == 0) { if (--argc < 1) goto bad; str = *(++argv); } else if (strcmp(*argv, "-kfile") == 0) { static char buf[128]; FILE *infile; char *file; if (--argc < 1) goto bad; file = *(++argv); infile = fopen(file, "r"); if (infile == NULL) { BIO_printf(bio_err, "unable to read key from '%s'\n", file); goto bad; } buf[0] = '\0'; if (!fgets(buf, sizeof buf, infile)) { BIO_printf(bio_err, "unable to read key from '%s'\n", file); goto bad; } fclose(infile); i = strlen(buf); if ((i > 0) && ((buf[i - 1] == '\n') || (buf[i - 1] == '\r'))) buf[--i] = '\0'; if ((i > 0) && ((buf[i - 1] == '\n') || (buf[i - 1] == '\r'))) buf[--i] = '\0'; if (i < 1) { BIO_printf(bio_err, "zero length password\n"); goto bad; } str = buf; } else if (strcmp(*argv, "-K") == 0) { if (--argc < 1) goto bad; hkey = *(++argv); } else if (strcmp(*argv, "-S") == 0) { if (--argc < 1) goto bad; hsalt = *(++argv); } else if (strcmp(*argv, "-iv") == 0) { if (--argc < 1) goto bad; hiv = *(++argv); } else if (strcmp(*argv, "-md") == 0) { if (--argc < 1) goto bad; md = *(++argv); } else if (strcmp(*argv, "-non-fips-allow") == 0) non_fips_allow = 1; else if ((argv[0][0] == '-') && ((c = EVP_get_cipherbyname(&(argv[0][1]))) != NULL)) { cipher = c; } else if (strcmp(*argv, "-none") == 0) cipher = NULL; else { BIO_printf(bio_err, "unknown option '%s'\n", *argv); bad: BIO_printf(bio_err, "options are\n"); BIO_printf(bio_err, "%-14s input file\n", "-in <file>"); BIO_printf(bio_err, "%-14s output file\n", "-out <file>"); BIO_printf(bio_err, "%-14s pass phrase source\n", "-pass <arg>"); BIO_printf(bio_err, "%-14s encrypt\n", "-e"); BIO_printf(bio_err, "%-14s decrypt\n", "-d"); BIO_printf(bio_err, "%-14s base64 encode/decode, depending on encryption flag\n", "-a/-base64"); BIO_printf(bio_err, "%-14s passphrase is the next argument\n", "-k"); BIO_printf(bio_err, "%-14s passphrase is the first line of the file argument\n", "-kfile"); BIO_printf(bio_err, "%-14s the next argument is the md to use to create a key\n", "-md"); BIO_printf(bio_err, "%-14s from a passphrase. One of md2, md5, sha or sha1\n", ""); BIO_printf(bio_err, "%-14s salt in hex is the next argument\n", "-S"); BIO_printf(bio_err, "%-14s key/iv in hex is the next argument\n", "-K/-iv"); BIO_printf(bio_err, "%-14s print the iv/key (then exit if -P)\n", "-[pP]"); BIO_printf(bio_err, "%-14s buffer size\n", "-bufsize <n>"); BIO_printf(bio_err, "%-14s disable standard block padding\n", "-nopad"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, "%-14s use engine e, possibly a hardware device.\n", "-engine e"); #endif BIO_printf(bio_err, "Cipher Types\n"); OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, show_ciphers, bio_err); BIO_printf(bio_err, "\n"); goto end; } argc--; argv++; } #ifndef OPENSSL_NO_ENGINE setup_engine(bio_err, engine, 0); #endif if (cipher && EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) { BIO_printf(bio_err, "AEAD ciphers not supported by the enc utility\n"); goto end; } if (cipher && (EVP_CIPHER_mode(cipher) == EVP_CIPH_XTS_MODE)) { BIO_printf(bio_err, "Ciphers in XTS mode are not supported by the enc utility\n"); goto end; } if (md && (dgst = EVP_get_digestbyname(md)) == NULL) { BIO_printf(bio_err, "%s is an unsupported message digest type\n", md); goto end; } if (dgst == NULL) { #ifndef OPENSSL_NO_GMSSL dgst = EVP_sm3(); #else dgst = EVP_md5(); #endif } if (bufsize != NULL) { unsigned long n; for (n = 0; *bufsize; bufsize++) { i = *bufsize; if ((i <= '9') && (i >= '0')) n = n * 10 + i - '0'; else if (i == 'k') { n *= 1024; bufsize++; break; } } if (*bufsize != '\0') { BIO_printf(bio_err, "invalid 'bufsize' specified.\n"); goto end; } /* It must be large enough for a base64 encoded line */ if (base64 && n < 80) n = 80; bsize = (int)n; if (verbose) BIO_printf(bio_err, "bufsize=%d\n", bsize); } strbuf = OPENSSL_malloc(SIZE); buff = (unsigned char *)OPENSSL_malloc(EVP_ENCODE_LENGTH(bsize)); if ((buff == NULL) || (strbuf == NULL)) { BIO_printf(bio_err, "OPENSSL_malloc failure %ld\n", (long)EVP_ENCODE_LENGTH(bsize)); goto end; } in = BIO_new(BIO_s_file()); out = BIO_new(BIO_s_file()); if ((in == NULL) || (out == NULL)) { ERR_print_errors(bio_err); goto end; } if (debug) { BIO_set_callback(in, BIO_debug_callback); BIO_set_callback(out, BIO_debug_callback); BIO_set_callback_arg(in, (char *)bio_err); BIO_set_callback_arg(out, (char *)bio_err); } if (inf == NULL) { #ifndef OPENSSL_NO_SETVBUF_IONBF if (bufsize != NULL) setvbuf(stdin, (char *)NULL, _IONBF, 0); #endif /* ndef OPENSSL_NO_SETVBUF_IONBF */ BIO_set_fp(in, stdin, BIO_NOCLOSE); } else { if (BIO_read_filename(in, inf) <= 0) { perror(inf); goto end; } } if (!str && passarg) { if (!app_passwd(bio_err, passarg, NULL, &pass, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } str = pass; } if ((str == NULL) && (cipher != NULL) && (hkey == NULL)) { for (;;) { char buf[200]; BIO_snprintf(buf, sizeof buf, "enter %s %s password:"******"encryption" : "decryption"); strbuf[0] = '\0'; i = EVP_read_pw_string((char *)strbuf, SIZE, buf, enc); if (i == 0) { if (strbuf[0] == '\0') { ret = 1; goto end; } str = strbuf; break; } if (i < 0) { BIO_printf(bio_err, "bad password read\n"); goto end; } } } if (outf == NULL) { BIO_set_fp(out, stdout, BIO_NOCLOSE); #ifndef OPENSSL_NO_SETVBUF_IONBF if (bufsize != NULL) setvbuf(stdout, (char *)NULL, _IONBF, 0); #endif /* ndef OPENSSL_NO_SETVBUF_IONBF */ #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } #endif } else { if (BIO_write_filename(out, outf) <= 0) { perror(outf); goto end; } } rbio = in; wbio = out; #ifdef ZLIB if (do_zlib) { if ((bzl = BIO_new(BIO_f_zlib())) == NULL) goto end; if (enc) wbio = BIO_push(bzl, wbio); else rbio = BIO_push(bzl, rbio); } #endif if (base64) { if ((b64 = BIO_new(BIO_f_base64())) == NULL) goto end; if (debug) { BIO_set_callback(b64, BIO_debug_callback); BIO_set_callback_arg(b64, (char *)bio_err); } if (olb64) BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); if (enc) wbio = BIO_push(b64, wbio); else rbio = BIO_push(b64, rbio); } if (cipher != NULL) { /* * Note that str is NULL if a key was passed on the command line, so * we get no salt in that case. Is this a bug? */ if (str != NULL) { /* * Salt handling: if encrypting generate a salt and write to * output BIO. If decrypting read salt from input BIO. */ unsigned char *sptr; if (nosalt) sptr = NULL; else { if (enc) { if (hsalt) { if (!set_hex(hsalt, salt, sizeof salt)) { BIO_printf(bio_err, "invalid hex salt value\n"); goto end; } } else if (RAND_pseudo_bytes(salt, sizeof salt) < 0) goto end; /* * If -P option then don't bother writing */ if ((printkey != 2) && (BIO_write(wbio, magic, sizeof magic - 1) != sizeof magic - 1 || BIO_write(wbio, (char *)salt, sizeof salt) != sizeof salt)) { BIO_printf(bio_err, "error writing output file\n"); goto end; } } else if (BIO_read(rbio, mbuf, sizeof mbuf) != sizeof mbuf || BIO_read(rbio, (unsigned char *)salt, sizeof salt) != sizeof salt) { BIO_printf(bio_err, "error reading input file\n"); goto end; } else if (memcmp(mbuf, magic, sizeof magic - 1)) { BIO_printf(bio_err, "bad magic number\n"); goto end; } sptr = salt; } EVP_BytesToKey(cipher, dgst, sptr, (unsigned char *)str, strlen(str), 1, key, iv); /* * zero the complete buffer or the string passed from the command * line bug picked up by Larry J. Hughes Jr. <*****@*****.**> */ if (str == strbuf) OPENSSL_cleanse(str, SIZE); else OPENSSL_cleanse(str, strlen(str)); } if (hiv != NULL) { int siz = EVP_CIPHER_iv_length(cipher); if (siz == 0) { BIO_printf(bio_err, "warning: iv not use by this cipher\n"); } else if (!set_hex(hiv, iv, sizeof iv)) { BIO_printf(bio_err, "invalid hex iv value\n"); goto end; } } if ((hiv == NULL) && (str == NULL) && EVP_CIPHER_iv_length(cipher) != 0) { /* * No IV was explicitly set and no IV was generated during * EVP_BytesToKey. Hence the IV is undefined, making correct * decryption impossible. */ BIO_printf(bio_err, "iv undefined\n"); goto end; } if ((hkey != NULL) && !set_hex(hkey, key, EVP_CIPHER_key_length(cipher))) { BIO_printf(bio_err, "invalid hex key value\n"); goto end; } if ((benc = BIO_new(BIO_f_cipher())) == NULL) goto end; /* * Since we may be changing parameters work on the encryption context * rather than calling BIO_set_cipher(). */ BIO_get_cipher_ctx(benc, &ctx); if (non_fips_allow) EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPH_FLAG_NON_FIPS_ALLOW); if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_name(cipher)); ERR_print_errors(bio_err); goto end; } if (nopad) EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_name(cipher)); ERR_print_errors(bio_err); goto end; } if (debug) { BIO_set_callback(benc, BIO_debug_callback); BIO_set_callback_arg(benc, (char *)bio_err); } if (printkey) { if (!nosalt) { printf("salt="); for (i = 0; i < (int)sizeof(salt); i++) printf("%02X", salt[i]); printf("\n"); } if (cipher->key_len > 0) { printf("key="); for (i = 0; i < cipher->key_len; i++) printf("%02X", key[i]); printf("\n"); } if (cipher->iv_len > 0) { printf("iv ="); for (i = 0; i < cipher->iv_len; i++) printf("%02X", iv[i]); printf("\n"); } if (printkey == 2) { ret = 0; goto end; } } } /* Only encrypt/decrypt as we write the file */ if (benc != NULL) wbio = BIO_push(benc, wbio); for (;;) { inl = BIO_read(rbio, (char *)buff, bsize); if (inl <= 0) break; if (BIO_write(wbio, (char *)buff, inl) != inl) { BIO_printf(bio_err, "error writing output file\n"); goto end; } } if (!BIO_flush(wbio)) { BIO_printf(bio_err, "bad decrypt\n"); goto end; } ret = 0; if (verbose) { BIO_printf(bio_err, "bytes read :%8ld\n", BIO_number_read(in)); BIO_printf(bio_err, "bytes written:%8ld\n", BIO_number_written(out)); } end: ERR_print_errors(bio_err); if (strbuf != NULL) OPENSSL_free(strbuf); if (buff != NULL) OPENSSL_free(buff); if (in != NULL) BIO_free(in); if (out != NULL) BIO_free_all(out); if (benc != NULL) BIO_free(benc); if (b64 != NULL) BIO_free(b64); #ifdef ZLIB if (bzl != NULL) BIO_free(bzl); #endif if (pass) OPENSSL_free(pass); apps_shutdown(); OPENSSL_EXIT(ret); }
int MAIN(int argc, char **argv) { ENGINE *e = NULL; unsigned char *buf=NULL; int i,err=0; const EVP_MD *md=NULL,*m; BIO *in=NULL,*inp; BIO *bmd=NULL; BIO *out = NULL; const char *name; #define PROG_NAME_SIZE 39 char pname[PROG_NAME_SIZE+1]; int separator=0; int debug=0; int keyform=FORMAT_PEM; const char *outfile = NULL, *keyfile = NULL; const char *sigfile = NULL, *randfile = NULL; int out_bin = -1, want_pub = 0, do_verify = 0; EVP_PKEY *sigkey = NULL; unsigned char *sigbuf = NULL; int siglen = 0; char *passargin = NULL, *passin = NULL; #ifndef OPENSSL_NO_ENGINE char *engine=NULL; #endif char *hmac_key=NULL; apps_startup(); if ((buf=(unsigned char *)OPENSSL_malloc(BUFSIZE)) == NULL) { BIO_printf(bio_err,"out of memory\n"); goto end; } if (bio_err == NULL) if ((bio_err=BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT); if (!load_config(bio_err, NULL)) goto end; /* first check the program name */ program_name(argv[0],pname,sizeof pname); md=EVP_get_digestbyname(pname); argc--; argv++; while (argc > 0) { if ((*argv)[0] != '-') break; if (strcmp(*argv,"-c") == 0) separator=1; else if (strcmp(*argv,"-rand") == 0) { if (--argc < 1) break; randfile=*(++argv); } else if (strcmp(*argv,"-out") == 0) { if (--argc < 1) break; outfile=*(++argv); } else if (strcmp(*argv,"-sign") == 0) { if (--argc < 1) break; keyfile=*(++argv); } else if (!strcmp(*argv,"-passin")) { if (--argc < 1) break; passargin=*++argv; } else if (strcmp(*argv,"-verify") == 0) { if (--argc < 1) break; keyfile=*(++argv); want_pub = 1; do_verify = 1; } else if (strcmp(*argv,"-prverify") == 0) { if (--argc < 1) break; keyfile=*(++argv); do_verify = 1; } else if (strcmp(*argv,"-signature") == 0) { if (--argc < 1) break; sigfile=*(++argv); } else if (strcmp(*argv,"-keyform") == 0) { if (--argc < 1) break; keyform=str2fmt(*(++argv)); } #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv,"-engine") == 0) { if (--argc < 1) break; engine= *(++argv); } #endif else if (strcmp(*argv,"-hex") == 0) out_bin = 0; else if (strcmp(*argv,"-binary") == 0) out_bin = 1; else if (strcmp(*argv,"-d") == 0) debug=1; else if (!strcmp(*argv,"-hmac")) { if (--argc < 1) break; hmac_key=*++argv; } else if ((m=EVP_get_digestbyname(&((*argv)[1]))) != NULL) md=m; else break; argc--; argv++; } if (md == NULL) md=EVP_md5(); if(do_verify && !sigfile) { BIO_printf(bio_err, "No signature to verify: use the -signature option\n"); err = 1; goto end; } if ((argc > 0) && (argv[0][0] == '-')) /* bad option */ { BIO_printf(bio_err,"unknown option '%s'\n",*argv); BIO_printf(bio_err,"options are\n"); BIO_printf(bio_err,"-c to output the digest with separating colons\n"); BIO_printf(bio_err,"-d to output debug info\n"); BIO_printf(bio_err,"-hex output as hex dump\n"); BIO_printf(bio_err,"-binary output in binary form\n"); BIO_printf(bio_err,"-sign file sign digest using private key in file\n"); BIO_printf(bio_err,"-verify file verify a signature using public key in file\n"); BIO_printf(bio_err,"-prverify file verify a signature using private key in file\n"); BIO_printf(bio_err,"-keyform arg key file format (PEM or ENGINE)\n"); BIO_printf(bio_err,"-signature file signature to verify\n"); BIO_printf(bio_err,"-binary output in binary form\n"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err,"-engine e use engine e, possibly a hardware device.\n"); #endif BIO_printf(bio_err,"-%-14s to use the %s message digest algorithm (default)\n", LN_md5,LN_md5); BIO_printf(bio_err,"-%-14s to use the %s message digest algorithm\n", LN_md4,LN_md4); BIO_printf(bio_err,"-%-14s to use the %s message digest algorithm\n", LN_md2,LN_md2); #ifndef OPENSSL_NO_SHA BIO_printf(bio_err,"-%-14s to use the %s message digest algorithm\n", LN_sha1,LN_sha1); BIO_printf(bio_err,"-%-14s to use the %s message digest algorithm\n", LN_sha,LN_sha); #ifndef OPENSSL_NO_SHA256 BIO_printf(bio_err,"-%-14s to use the %s message digest algorithm\n", LN_sha224,LN_sha224); BIO_printf(bio_err,"-%-14s to use the %s message digest algorithm\n", LN_sha256,LN_sha256); #endif #ifndef OPENSSL_NO_SHA512 BIO_printf(bio_err,"-%-14s to use the %s message digest algorithm\n", LN_sha384,LN_sha384); BIO_printf(bio_err,"-%-14s to use the %s message digest algorithm\n", LN_sha512,LN_sha512); #endif #endif BIO_printf(bio_err,"-%-14s to use the %s message digest algorithm\n", LN_mdc2,LN_mdc2); BIO_printf(bio_err,"-%-14s to use the %s message digest algorithm\n", LN_ripemd160,LN_ripemd160); err=1; goto end; } #ifndef OPENSSL_NO_ENGINE e = setup_engine(bio_err, engine, 0); #endif in=BIO_new(BIO_s_file()); bmd=BIO_new(BIO_f_md()); if (debug) { BIO_set_callback(in,BIO_debug_callback); /* needed for windows 3.1 */ BIO_set_callback_arg(in,(char *)bio_err); } if(!app_passwd(bio_err, passargin, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } if ((in == NULL) || (bmd == NULL)) { ERR_print_errors(bio_err); goto end; } if(out_bin == -1) { if(keyfile) out_bin = 1; else out_bin = 0; } if(randfile) app_RAND_load_file(randfile, bio_err, 0); if(outfile) { if(out_bin) out = BIO_new_file(outfile, "wb"); else out = BIO_new_file(outfile, "w"); } else { out = BIO_new_fp(stdout, BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } #endif } if(!out) { BIO_printf(bio_err, "Error opening output file %s\n", outfile ? outfile : "(stdout)"); ERR_print_errors(bio_err); goto end; } if(keyfile) { if (want_pub) sigkey = load_pubkey(bio_err, keyfile, keyform, 0, NULL, e, "key file"); else sigkey = load_key(bio_err, keyfile, keyform, 0, passin, e, "key file"); if (!sigkey) { /* load_[pub]key() has already printed an appropriate message */ goto end; } } if(sigfile && sigkey) { BIO *sigbio; sigbio = BIO_new_file(sigfile, "rb"); siglen = EVP_PKEY_size(sigkey); sigbuf = OPENSSL_malloc(siglen); if(!sigbio) { BIO_printf(bio_err, "Error opening signature file %s\n", sigfile); ERR_print_errors(bio_err); goto end; } siglen = BIO_read(sigbio, sigbuf, siglen); BIO_free(sigbio); if(siglen <= 0) { BIO_printf(bio_err, "Error reading signature file %s\n", sigfile); ERR_print_errors(bio_err); goto end; } } /* we use md as a filter, reading from 'in' */ if (!BIO_set_md(bmd,md)) { BIO_printf(bio_err, "Error setting digest %s\n", pname); ERR_print_errors(bio_err); goto end; } inp=BIO_push(bmd,in); if (argc == 0) { BIO_set_fp(in,stdin,BIO_NOCLOSE); err=do_fp(out, buf,inp,separator, out_bin, sigkey, sigbuf, siglen,"","(stdin)",bmd,hmac_key); } else { name=OBJ_nid2sn(md->type); for (i=0; i<argc; i++) { char *tmp,*tofree=NULL; int r; if (BIO_read_filename(in,argv[i]) <= 0) { perror(argv[i]); err++; continue; } if(!out_bin) { size_t len = strlen(name)+strlen(argv[i])+(hmac_key ? 5 : 0)+5; tmp=tofree=OPENSSL_malloc(len); BIO_snprintf(tmp,len,"%s%s(%s)= ", hmac_key ? "HMAC-" : "",name,argv[i]); } else tmp=""; r=do_fp(out,buf,inp,separator,out_bin,sigkey,sigbuf, siglen,tmp,argv[i],bmd,hmac_key); if(r) err=r; if(tofree) OPENSSL_free(tofree); (void)BIO_reset(bmd); } } end: if (buf != NULL) { OPENSSL_cleanse(buf,BUFSIZE); OPENSSL_free(buf); } if (in != NULL) BIO_free(in); if (passin) OPENSSL_free(passin); BIO_free_all(out); EVP_PKEY_free(sigkey); if(sigbuf) OPENSSL_free(sigbuf); if (bmd != NULL) BIO_free(bmd); apps_shutdown(); OPENSSL_EXIT(err); }
int MAIN(int argc, char **argv) { ENGINE *e = NULL; int ret = 1; DSA *dsa = NULL; int i, badops = 0; const EVP_CIPHER *enc = NULL; BIO *in = NULL, *out = NULL; int informat, outformat, text = 0, noout = 0; int pubin = 0, pubout = 0; char *infile, *outfile, *prog; char *engine; char *passargin = NULL, *passargout = NULL; char *passin = NULL, *passout = NULL; int modulus = 0; int pvk_encr = 2; apps_startup(); if (bio_err == NULL) if ((bio_err = BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT); if (!load_config(bio_err, NULL)) goto end; engine = NULL; infile = NULL; outfile = NULL; informat = FORMAT_PEM; outformat = FORMAT_PEM; prog = argv[0]; argc--; argv++; while (argc >= 1) { if (strcmp(*argv, "-inform") == 0) { if (--argc < 1) goto bad; informat = str2fmt(*(++argv)); } else if (strcmp(*argv, "-outform") == 0) { if (--argc < 1) goto bad; outformat = str2fmt(*(++argv)); } else if (strcmp(*argv, "-in") == 0) { if (--argc < 1) goto bad; infile = *(++argv); } else if (strcmp(*argv, "-out") == 0) { if (--argc < 1) goto bad; outfile = *(++argv); } else if (strcmp(*argv, "-passin") == 0) { if (--argc < 1) goto bad; passargin = *(++argv); } else if (strcmp(*argv, "-passout") == 0) { if (--argc < 1) goto bad; passargout = *(++argv); } # ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv, "-engine") == 0) { if (--argc < 1) goto bad; engine = *(++argv); } # endif else if (strcmp(*argv, "-pvk-strong") == 0) pvk_encr = 2; else if (strcmp(*argv, "-pvk-weak") == 0) pvk_encr = 1; else if (strcmp(*argv, "-pvk-none") == 0) pvk_encr = 0; else if (strcmp(*argv, "-noout") == 0) noout = 1; else if (strcmp(*argv, "-text") == 0) text = 1; else if (strcmp(*argv, "-modulus") == 0) modulus = 1; else if (strcmp(*argv, "-pubin") == 0) pubin = 1; else if (strcmp(*argv, "-pubout") == 0) pubout = 1; else if ((enc = EVP_get_cipherbyname(&(argv[0][1]))) == NULL) { BIO_printf(bio_err, "unknown option %s\n", *argv); badops = 1; break; } argc--; argv++; } if (badops) { bad: BIO_printf(bio_err, "%s [options] <infile >outfile\n", prog); BIO_printf(bio_err, "where options are\n"); BIO_printf(bio_err, " -inform arg input format - DER or PEM\n"); BIO_printf(bio_err, " -outform arg output format - DER or PEM\n"); BIO_printf(bio_err, " -in arg input file\n"); BIO_printf(bio_err, " -passin arg input file pass phrase source\n"); BIO_printf(bio_err, " -out arg output file\n"); BIO_printf(bio_err, " -passout arg output file pass phrase source\n"); # ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, " -engine e use engine e, possibly a hardware device.\n"); # endif BIO_printf(bio_err, " -des encrypt PEM output with cbc des\n"); BIO_printf(bio_err, " -des3 encrypt PEM output with ede cbc des using 168 bit key\n"); # ifndef OPENSSL_NO_IDEA BIO_printf(bio_err, " -idea encrypt PEM output with cbc idea\n"); # endif # ifndef OPENSSL_NO_AES BIO_printf(bio_err, " -aes128, -aes192, -aes256\n"); BIO_printf(bio_err, " encrypt PEM output with cbc aes\n"); # endif # ifndef OPENSSL_NO_CAMELLIA BIO_printf(bio_err, " -camellia128, -camellia192, -camellia256\n"); BIO_printf(bio_err, " encrypt PEM output with cbc camellia\n"); # endif # ifndef OPENSSL_NO_SEED BIO_printf(bio_err, " -seed encrypt PEM output with cbc seed\n"); # endif BIO_printf(bio_err, " -text print the key in text\n"); BIO_printf(bio_err, " -noout don't print key out\n"); BIO_printf(bio_err, " -modulus print the DSA public value\n"); goto end; } ERR_load_crypto_strings(); e = setup_engine(bio_err, engine, 0); if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } in = BIO_new(BIO_s_file()); out = BIO_new(BIO_s_file()); if ((in == NULL) || (out == NULL)) { ERR_print_errors(bio_err); goto end; } if (infile == NULL) BIO_set_fp(in, stdin, BIO_NOCLOSE); else { if (BIO_read_filename(in, infile) <= 0) { perror(infile); goto end; } } BIO_printf(bio_err, "read DSA key\n"); { EVP_PKEY *pkey; if (pubin) pkey = load_pubkey(bio_err, infile, informat, 1, passin, e, "Public Key"); else pkey = load_key(bio_err, infile, informat, 1, passin, e, "Private Key"); if (pkey) { dsa = EVP_PKEY_get1_DSA(pkey); EVP_PKEY_free(pkey); } } if (dsa == NULL) { BIO_printf(bio_err, "unable to load Key\n"); ERR_print_errors(bio_err); goto end; } if (outfile == NULL) { BIO_set_fp(out, stdout, BIO_NOCLOSE); # ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } # endif } else { if (BIO_write_filename(out, outfile) <= 0) { perror(outfile); goto end; } } if (text) if (!DSA_print(out, dsa, 0)) { perror(outfile); ERR_print_errors(bio_err); goto end; } if (modulus) { fprintf(stdout, "Public Key="); BN_print(out, dsa->pub_key); fprintf(stdout, "\n"); } if (noout) goto end; BIO_printf(bio_err, "writing DSA key\n"); if (outformat == FORMAT_ASN1) { if (pubin || pubout) i = i2d_DSA_PUBKEY_bio(out, dsa); else i = i2d_DSAPrivateKey_bio(out, dsa); } else if (outformat == FORMAT_PEM) { if (pubin || pubout) i = PEM_write_bio_DSA_PUBKEY(out, dsa); else i = PEM_write_bio_DSAPrivateKey(out, dsa, enc, NULL, 0, NULL, passout); # if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_NO_RC4) } else if (outformat == FORMAT_MSBLOB || outformat == FORMAT_PVK) { EVP_PKEY *pk; pk = EVP_PKEY_new(); EVP_PKEY_set1_DSA(pk, dsa); if (outformat == FORMAT_PVK) i = i2b_PVK_bio(out, pk, pvk_encr, 0, passout); else if (pubin || pubout) i = i2b_PublicKey_bio(out, pk); else i = i2b_PrivateKey_bio(out, pk); EVP_PKEY_free(pk); # endif } else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (i <= 0) { BIO_printf(bio_err, "unable to write private key\n"); ERR_print_errors(bio_err); } else ret = 0; end: if (in != NULL) BIO_free(in); if (out != NULL) BIO_free_all(out); if (dsa != NULL) DSA_free(dsa); release_engine(e); if (passin) OPENSSL_free(passin); if (passout) OPENSSL_free(passout); apps_shutdown(); OPENSSL_EXIT(ret); }
int crl_main(int argc, char **argv) { unsigned long nmflag = 0; X509_CRL *x = NULL; char *CAfile = NULL, *CApath = NULL; int ret = 1, i, num, badops = 0; BIO *out = NULL; int informat, outformat; char *infile = NULL, *outfile = NULL; int hash = 0, issuer = 0, lastupdate = 0, nextupdate = 0, noout = 0, text = 0; #ifndef OPENSSL_NO_MD5 int hash_old = 0; #endif int fingerprint = 0, crlnumber = 0; const char **pp; X509_STORE *store = NULL; X509_STORE_CTX ctx; X509_LOOKUP *lookup = NULL; X509_OBJECT xobj; EVP_PKEY *pkey; int do_ver = 0; const EVP_MD *md_alg, *digest = EVP_sha1(); if (!load_config(bio_err, NULL)) goto end; if (bio_out == NULL) if ((bio_out = BIO_new(BIO_s_file())) != NULL) { BIO_set_fp(bio_out, stdout, BIO_NOCLOSE); } informat = FORMAT_PEM; outformat = FORMAT_PEM; argc--; argv++; num = 0; while (argc >= 1) { #ifdef undef if (strcmp(*argv, "-p") == 0) { if (--argc < 1) goto bad; if (!args_from_file(++argv, Nargc, Nargv)) { goto end; } } #endif if (strcmp(*argv, "-inform") == 0) { if (--argc < 1) goto bad; informat = str2fmt(*(++argv)); } else if (strcmp(*argv, "-outform") == 0) { if (--argc < 1) goto bad; outformat = str2fmt(*(++argv)); } else if (strcmp(*argv, "-in") == 0) { if (--argc < 1) goto bad; infile = *(++argv); } else if (strcmp(*argv, "-out") == 0) { if (--argc < 1) goto bad; outfile = *(++argv); } else if (strcmp(*argv, "-CApath") == 0) { if (--argc < 1) goto bad; CApath = *(++argv); do_ver = 1; } else if (strcmp(*argv, "-CAfile") == 0) { if (--argc < 1) goto bad; CAfile = *(++argv); do_ver = 1; } else if (strcmp(*argv, "-verify") == 0) do_ver = 1; else if (strcmp(*argv, "-text") == 0) text = 1; else if (strcmp(*argv, "-hash") == 0) hash = ++num; #ifndef OPENSSL_NO_MD5 else if (strcmp(*argv, "-hash_old") == 0) hash_old = ++num; #endif else if (strcmp(*argv, "-nameopt") == 0) { if (--argc < 1) goto bad; if (!set_name_ex(&nmflag, *(++argv))) goto bad; } else if (strcmp(*argv, "-issuer") == 0) issuer = ++num; else if (strcmp(*argv, "-lastupdate") == 0) lastupdate = ++num; else if (strcmp(*argv, "-nextupdate") == 0) nextupdate = ++num; else if (strcmp(*argv, "-noout") == 0) noout = ++num; else if (strcmp(*argv, "-fingerprint") == 0) fingerprint = ++num; else if (strcmp(*argv, "-crlnumber") == 0) crlnumber = ++num; else if ((md_alg = EVP_get_digestbyname(*argv + 1))) { /* ok */ digest = md_alg; } else { BIO_printf(bio_err, "unknown option %s\n", *argv); badops = 1; break; } argc--; argv++; } if (badops) { bad: for (pp = crl_usage; (*pp != NULL); pp++) BIO_printf(bio_err, "%s", *pp); goto end; } ERR_load_crypto_strings(); x = load_crl(infile, informat); if (x == NULL) { goto end; } if (do_ver) { store = X509_STORE_new(); lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); if (lookup == NULL) goto end; if (!X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM)) X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT); lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()); if (lookup == NULL) goto end; if (!X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM)) X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT); ERR_clear_error(); if (!X509_STORE_CTX_init(&ctx, store, NULL, NULL)) { BIO_printf(bio_err, "Error initialising X509 store\n"); goto end; } i = X509_STORE_get_by_subject(&ctx, X509_LU_X509, X509_CRL_get_issuer(x), &xobj); if (i <= 0) { BIO_printf(bio_err, "Error getting CRL issuer certificate\n"); goto end; } pkey = X509_get_pubkey(xobj.data.x509); X509_OBJECT_free_contents(&xobj); if (!pkey) { BIO_printf(bio_err, "Error getting CRL issuer public key\n"); goto end; } i = X509_CRL_verify(x, pkey); EVP_PKEY_free(pkey); if (i < 0) goto end; if (i == 0) BIO_printf(bio_err, "verify failure\n"); else BIO_printf(bio_err, "verify OK\n"); } if (num) { for (i = 1; i <= num; i++) { if (issuer == i) { print_name(bio_out, "issuer=", X509_CRL_get_issuer(x), nmflag); } if (crlnumber == i) { ASN1_INTEGER *crlnum; crlnum = X509_CRL_get_ext_d2i(x, NID_crl_number, NULL, NULL); BIO_printf(bio_out, "crlNumber="); if (crlnum) { i2a_ASN1_INTEGER(bio_out, crlnum); ASN1_INTEGER_free(crlnum); } else BIO_puts(bio_out, "<NONE>"); BIO_printf(bio_out, "\n"); } if (hash == i) { BIO_printf(bio_out, "%08lx\n", X509_NAME_hash(X509_CRL_get_issuer(x))); } #ifndef OPENSSL_NO_MD5 if (hash_old == i) { BIO_printf(bio_out, "%08lx\n", X509_NAME_hash_old(X509_CRL_get_issuer(x))); } #endif if (lastupdate == i) { BIO_printf(bio_out, "lastUpdate="); ASN1_TIME_print(bio_out, X509_CRL_get_lastUpdate(x)); BIO_printf(bio_out, "\n"); } if (nextupdate == i) { BIO_printf(bio_out, "nextUpdate="); if (X509_CRL_get_nextUpdate(x)) ASN1_TIME_print(bio_out, X509_CRL_get_nextUpdate(x)); else BIO_printf(bio_out, "NONE"); BIO_printf(bio_out, "\n"); } if (fingerprint == i) { int j; unsigned int n; unsigned char md[EVP_MAX_MD_SIZE]; if (!X509_CRL_digest(x, digest, md, &n)) { BIO_printf(bio_err, "out of memory\n"); goto end; } BIO_printf(bio_out, "%s Fingerprint=", OBJ_nid2sn(EVP_MD_type(digest))); for (j = 0; j < (int) n; j++) { BIO_printf(bio_out, "%02X%c", md[j], (j + 1 == (int)n) ? '\n' : ':'); } } } } out = BIO_new(BIO_s_file()); if (out == NULL) { ERR_print_errors(bio_err); goto end; } if (outfile == NULL) { BIO_set_fp(out, stdout, BIO_NOCLOSE); } else { if (BIO_write_filename(out, outfile) <= 0) { perror(outfile); goto end; } } if (text) X509_CRL_print(out, x); if (noout) { ret = 0; goto end; } if (outformat == FORMAT_ASN1) i = (int) i2d_X509_CRL_bio(out, x); else if (outformat == FORMAT_PEM) i = PEM_write_bio_X509_CRL(out, x); else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (!i) { BIO_printf(bio_err, "unable to write CRL\n"); goto end; } ret = 0; end: BIO_free_all(out); BIO_free_all(bio_out); bio_out = NULL; X509_CRL_free(x); if (store) { X509_STORE_CTX_cleanup(&ctx); X509_STORE_free(store); } return (ret); }
int main() { /* Variables */ int fd; int stdout_fileno; char *username; char *home; char *conf_file_name; /* Initialize variables */ afterlist = ul_create(8); beforelist = ul_create(8); stdout_fileno = fileno(stdout); /* Get our username */ struct passwd *p = getpwuid(getuid()); if(p == NULL) fatalperror("getpwuid"); /* warning - username will now point to a static area, subsequent getpwuid calls may overwite it */ username = p->pw_name; /* Get our home directory */ home = getenv("HOME"); if(home == NULL) fatalerror("$HOME is not set.\n"); conf_file_name = malloc(strlen(home) + 1 + strlen(conf_file_basename) + 1); strcpy(conf_file_name, home); strcat(conf_file_name, "/"); strcat(conf_file_name, conf_file_basename); /* Set up atexit */ atexit(free_mem_on_exit); /* Read conf file */ config = load_config(conf_file_name); /* If we are supposed to print a user list upon startup, do it now, before fork()ing */ if(config->initialshow) { struct userlist *ls = ul_create(8); ul_populate(ls); ul_sort(ls); if(ls->array[0] == NULL) { printf("No users logged in.\n"); } else { printf("Users logged in: "); for(int i = 0; ls->array[i] != NULL; i++) { if(i > 0 && !strcmp(ls->array[i], ls->array[i-1])) continue; printf("%s, ", ls->array[i]); } printf("\b\b \n"); } ul_free(ls); } /* If we aren't supposed to listen to INs *or* OUTs, no point in continuing */ if(!config->listen_ins && !config->listen_outs) exit(EXIT_SUCCESS); /* If we are forking, fork() and then exit the parent */ if(config->forking) { pid_t pid = fork(); if(pid > 0) exit(0); else if(pid == -1) fatalperror("fork"); /* This setpgid() call changes the process-group ID so 'w' reports the shell (not us!) as the current command */ setpgid(getpid(),getpid()); /* Close stdin, and hang up the TTY, since we really can't access them from the "background" */ close(STDIN_FILENO); vhangup(); } /* Set up child-reaping for login-command */ signal(SIGCHLD, SIG_IGN); /* Start and setup inotify */ fd = inotify_init(); if(fd < 0) fatalperror("inotify_init"); if(inotify_add_watch(fd, _PATH_UTMP, IN_MODIFY) < 0) fatalperror("inotify_add_watch"); while(1) { ul_populate(beforelist); /* If we are fork()ing, we want to monitor stdout, which requires us to use select() with a timeout */ if(config->forking) { watch_and_wait(fd, stdout_fileno); } struct inotify_event evt; if(read(fd, &evt, sizeof(struct inotify_event)) < 0) fatalperror("read"); ul_populate(afterlist); int firstlen = ul_count(beforelist); int secondlen = ul_count(afterlist); if(firstlen == secondlen) { continue; } else if(firstlen > secondlen) { char *r = ul_subtract(beforelist, afterlist); if(r == NULL) continue; if(!strcmp(r, username)) continue; if(config->listen_outs) on_logout(r); } else { char *r = ul_subtract(afterlist, beforelist); if(r == NULL) continue; if(!strcmp(r, username)) continue; if(config->listen_ins) on_login(r); } if(config->oneshot) { exit(0); } } exit(SUCCESS); }
int gendh_main(int argc, char **argv) { BN_GENCB cb; DH *dh = NULL; int ret = 1, num = DEFBITS; int g = 2; char *outfile = NULL; #ifndef OPENSSL_NO_ENGINE char *engine = NULL; #endif BIO *out = NULL; BN_GENCB_set(&cb, dh_cb, bio_err); if (!load_config(bio_err, NULL)) goto end; argv++; argc--; for (;;) { if (argc <= 0) break; if (strcmp(*argv, "-out") == 0) { if (--argc < 1) goto bad; outfile = *(++argv); } else if (strcmp(*argv, "-2") == 0) g = 2; /* * else if (strcmp(*argv,"-3") == 0) g=3; */ else if (strcmp(*argv, "-5") == 0) g = 5; #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv, "-engine") == 0) { if (--argc < 1) goto bad; engine = *(++argv); } #endif else break; argv++; argc--; } if ((argc >= 1) && ((sscanf(*argv, "%d", &num) == 0) || (num < 0))) { bad: BIO_printf(bio_err, "usage: gendh [args] [numbits]\n"); BIO_printf(bio_err, " -out file - output the key to 'file\n"); BIO_printf(bio_err, " -2 - use 2 as the generator value\n"); /* * BIO_printf(bio_err," -3 - use 3 as the generator * value\n"); */ BIO_printf(bio_err, " -5 - use 5 as the generator value\n"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, " -engine e - use engine e, possibly a hardware device.\n"); #endif goto end; } #ifndef OPENSSL_NO_ENGINE setup_engine(bio_err, engine, 0); #endif out = BIO_new(BIO_s_file()); if (out == NULL) { ERR_print_errors(bio_err); goto end; } if (outfile == NULL) { BIO_set_fp(out, stdout, BIO_NOCLOSE); } else { if (BIO_write_filename(out, outfile) <= 0) { perror(outfile); goto end; } } BIO_printf(bio_err, "Generating DH parameters, %d bit long safe prime, generator %d\n", num, g); BIO_printf(bio_err, "This is going to take a long time\n"); if (((dh = DH_new()) == NULL) || !DH_generate_parameters_ex(dh, num, g, &cb)) goto end; if (!PEM_write_bio_DHparams(out, dh)) goto end; ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); if (out != NULL) BIO_free_all(out); if (dh != NULL) DH_free(dh); return (ret); }