auth::auth(context& ctx) : curve_allow_any(false), terminated(false), verbose(false) { auto zap_auth_server = [this] (socket * pipe, context& auth_ctx) -> bool { // spawn ZAP handler socket zap_handler(auth_ctx, socket_type::reply); try { zap_handler.bind(zap_endpoint_); pipe->send(signal::ok); } catch (zmq_internal_exception const&) { // by returning false here, the actor will send signal::ko // this will make the actor constructor throw. // we could also to the ourselves: pipe->send(signal::ko);) return false; } auth_poller.add(*pipe); auth_poller.add(zap_handler); while (!terminated && auth_poller.poll()) { if (auth_poller.has_input(zap_handler)) { authenticate(zap_handler); } if (auth_poller.has_input(*pipe)) { handle_command(*pipe); } } zap_handler.unbind(zap_endpoint_); return true; }; // Start ZAP Authentication Server std::cout << "auth: Starting ZAP Authentication Server" << std::endl; authenticator = std::make_shared<actor>(std::bind(zap_auth_server, std::placeholders::_1, std::ref(ctx))); }
void check_remote_auth(void) { #define SANESTRING 80 char stringuser[BUF_MAX] = { 0 }; if (username == NULL) { printf("\nUsername: "******"%s@%s's password: ", username, hostname); char *stringpass = getpass(echo_to_screen); if (strlen(stringpass) == 0) { exit( 1 << 3); } password = strdup(stringpass); authenticate(); }
bool OAuthClient::initialize(){ cout << "Initialize" << endl; if(consumer!=0) {delete consumer; consumer = NULL;} if(client!=0) {delete client; client = NULL;} //Get the Consumer Key and Secret from Evimed config consumerKey = pevimedConfig.get<string>("evimed.consumerKey"); consumerSecret = pevimedConfig.get<string>("evimed.consumerSecret"); consumer = new Consumer(consumerKey, consumerSecret); //Try to get the OAuth key and secret from User config oauth_key = puserConfig.get<string>("user.oauth_key", ""); oauth_secret = puserConfig.get<string>("user.oauth_secret", ""); //Try to get User Information emailAddress = puserConfig.get<string>("user.emailAddress", ""); if(initClient(oauth_key, oauth_secret)) { authenticated = authenticate(); return true; } return false; }
void passwd_authenticate (PasswdHandler *passwd_handler, const char *current_password, PasswdCallback cb, const gpointer user_data) { GError *error = NULL; /* Don't stop if we've already started chaging password */ if (passwd_handler->changing_password) return; /* Clear data from possible previous attempts to change password */ passwd_handler->new_password = NULL; passwd_handler->chpasswd_cb = NULL; passwd_handler->chpasswd_cb_data = NULL; g_queue_foreach (passwd_handler->backend_stdin_queue, (GFunc) g_free, NULL); g_queue_clear (passwd_handler->backend_stdin_queue); passwd_handler->current_password = current_password; passwd_handler->auth_cb = cb; passwd_handler->auth_cb_data = user_data; /* Spawn backend */ stop_passwd (passwd_handler); if (!spawn_passwd (passwd_handler, &error)) { g_warning ("%s", error->message); g_error_free (error); return; } authenticate (passwd_handler); /* Our IO watcher should now handle the rest */ }
int main(int argc, char *argv[]) { int fd; /* Descriptor del FIFO */ int len; /* Bytes leídos del FIFO */ char buf[PIPE_BUF]; mode_t mode = 0666; if ((mkfifo("fifo1", mode)) < 0) { perror("mkfifo"); exit(EXIT_FAILURE); } /* Apertura del FIFO de sólo lectura */ if ((fd = open("fifo1", O_RDONLY)) < 0) { perror("open"); exit(EXIT_FAILURE); } read(fd,buf,PIPE_BUF - 1); close(fd); int retval; char *user, *pass; if(argc == 3) { user = argv[1]; pass = strdup(argv[2]); } else { fprintf(stderr, "Usage: login [username] [password]\n"); exit(1); } return authenticate("system-auth", user, pass, buf); }
void ci_connect(struct ci_connection *con) { int sock; int con_res; error_t err; struct sockaddr_in* server = calloc(1, sizeof(*server)); sock = socket(AF_INET, SOCK_STREAM, 0); if (sock == -1) perror("Creating socket"); err = resolve_hostname(con->server.host, &con->server.ip); if (err != E_SUCCESS) { fprintf(stderr, "%s: %s\n", "Error connecting to IRC server", err_desc[err].message); exit(1); } server->sin_addr.s_addr = inet_addr(con->server.ip); server->sin_port = htons((uint16_t)con->server.port); server->sin_family = AF_INET; con_res = connect(sock, (struct sockaddr*)server, sizeof(*server)); if (con_res == -1) perror("Connecting to server"); err = authenticate(sock, (struct sockaddr*)server, con); if (err != E_SUCCESS) { fprintf(stderr, "%s: %s\n", "Error connecting to IRC server", err_desc[err].message); exit(1); } /* Start infinite loop */ communicate(sock, (struct sockaddr*)server); }
/* * For a description of the AIX authentication API, see * http://publib16.boulder.ibm.com/doc_link/en_US/a_doc_lib/libs/basetrf1/authenticate.htm */ int sudo_aix_verify(struct passwd *pw, char *prompt, sudo_auth *auth) { char *pass, *message = NULL; int result = 1, reenter = 0; int rval = AUTH_SUCCESS; debug_decl(sudo_aix_verify, SUDO_DEBUG_AUTH) do { pass = auth_getpass(prompt, def_passwd_timeout * 60, SUDO_CONV_PROMPT_ECHO_OFF); if (pass == NULL) break; efree(message); message = NULL; result = authenticate(pw->pw_name, pass, &reenter, &message); memset_s(pass, SUDO_CONV_REPL_MAX, 0, strlen(pass)); prompt = message; } while (reenter); if (result != 0) { /* Display error message, if any. */ if (message != NULL) { struct sudo_conv_message msg; struct sudo_conv_reply repl; memset(&msg, 0, sizeof(msg)); msg.msg_type = SUDO_CONV_ERROR_MSG; msg.msg = message; memset(&repl, 0, sizeof(repl)); sudo_conv(1, &msg, &repl); } rval = pass ? AUTH_FAILURE : AUTH_INTR; } efree(message); debug_return_int(rval); }
/*-----------------*/ void MICLOCK_SETcmd(void *tag, void *msgv, int *size) { char errmsg[200]; char msg[80]; int rc,rc2=0; int nwclocktag, msglen; sprintf(errmsg, "MICLOCK_SETcmd: tag:%d size:%d msg:%5.5s", *(int *)tag, *size, (char *)msgv); prtLog(errmsg); /* pydim client: msg not finished by 0x0 ! -that's why strncmp() used below... if(*size >=2) { msg[*size]='\0'; // with python client ok //if(msg[*size-2]=='\n') { msg[*size-2]='\0'; } else { msg[*size-1]='\0'; }; }; */ msglen= *size; strncpy(msg, (char *)msgv, msglen); msg[msglen]='\0'; rc= authenticate(""); rc2=1; //rc2= authenticate("oerjan/"); //rc=0; if((rc!=0) and (rc2!=0) ) { //sprintf(errmsg, "Only trigger/oerjan user can change the clock"); prtLog(errmsg); sprintf(errmsg, "Only alidcscom779 can request the change of the clock"); prtLog(errmsg); return; }; if(strncmp(msg,"qq", 2)==0) ds_stop(); if(strncmp(msg,"BEAM1", 5)==0) { nwclocktag=1; } else if(strncmp(msg,"BEAM2", 5)==0) { nwclocktag=2; } else if(strncmp(msg,"REF", 3)==0) { nwclocktag=3; } else if(strncmp(msg,"LOCAL", 5)==0) { nwclocktag=4; } else { sprintf(errmsg, "bad clock request:%s ignored.\n", msg); prtLog(errmsg); return; }; getclocknow(); if(clocktag==nwclocktag) { sprintf(errmsg, "clock request:%s ignored (already set).\n", msg); prtLog(errmsg); return; }; checkstartthread(nwclocktag); }
//nparams: user_ip -> fd -> buf -> count return_type sRead(int nparams, arg_type* a) { if (nparams != 4) { r.return_val = NULL; r.return_size = 0; return r; } char *user_ip = (char *)a->arg_val; int fd = (int)a->next->arg_val; void *buf = (void *)a->next->next->arg_val; int count = (int)a->next->next->next->arg_val; if (authenticate(user_ip) == 0) { return error_val; } int bytesRead = -1; OpenedFile *op_current = op_head; while(op_current != NULL){ if (op_current->fd == fd) { if (op_current->ip == user_ip) { bytesRead = read(fd, buf, count); r.return_val = (void *)bytesRead; r.return_size = sizeof(int); return r; } else { return error_val; } } op_current = op_current->next; } return error_val; }
void server::handle_change_passphrase(const server::request& req) { const config& cpass = req.cfg; if(read_only_) { LOG_CS << "in read-only mode, request to change passphrase denied\n"; send_error("Cannot change passphrase: The server is currently in read-only mode.", req.sock); return; } config& campaign = get_campaign(cpass["name"]); if(!campaign) { send_error("No add-on with that name exists.", req.sock); } else if(!authenticate(campaign, cpass["passphrase"])) { send_error("Your old passphrase was incorrect.", req.sock); } else if(cpass["new_passphrase"].empty()) { send_error("No new passphrase was supplied.", req.sock); } else { set_passphrase(campaign, cpass["new_passphrase"]); write_config(); send_message("Passphrase changed.", req.sock); } }
INT32 _pmdExternClient::authenticate( const CHAR *username, const CHAR *password ) { INT32 rc = SDB_OK ; CHAR *pBuffer = NULL ; INT32 buffSize = 0 ; rc = msgBuildAuthMsg( &pBuffer, &buffSize, username, password, 0 ) ; if ( rc ) { PD_LOG( PDERROR, "Failed to build auth msg, rc: %d", rc ) ; goto error ; } rc = authenticate( (MsgHeader*)pBuffer ) ; done: if ( pBuffer ) { SDB_OSS_FREE( pBuffer ) ; pBuffer = NULL ; } return rc ; error: goto done ; }
int delmessages(sqlite3 *db, const char *user, const char *passwd) { int authrc = authenticate(db, user, passwd); if (authrc > 0) { fprintf(stderr, "Can't authenticate, result = %d.\n", authrc); return authrc; } const char *zSql = "DELETE FROM messages WHERE recipient = ?"; sqlite3_stmt *stmt = NULL; int rc; sqlite3_prepare_v2(db, zSql, -1, &stmt, NULL); sqlite3_bind_text(stmt, 1, user, -1, SQLITE_STATIC); rc = sqlite3_step(stmt); if (rc != SQLITE_DONE) { fprintf(stderr, "Error deleting messages for user %s.\n", user); return 1; } sqlite3_finalize(stmt); return 0; }
int RASocket::svc(void) { //! Subnegotiation may differ per client - do not react on it subnegotiate(); if (send("Authentication required\r\n") == -1) return -1; if (authenticate() == -1) { (void) send("Authentication failed\r\n"); return -1; } // send motd if (send(std::string(sWorld->GetMotd()) + "\r\n") == -1) return -1; for (;;) { // show prompt const char* tc_prompt = "SF> "; if (size_t(peer().send(tc_prompt, strlen(tc_prompt))) != strlen(tc_prompt)) return -1; std::string line; if (recv_line(line) == -1) return -1; if (process_command(line) == -1) return -1; } return 0; }
/* Deauths and re-associates a MAC address with the AP. Returns 0 on failure, 1 for success. */ int reassociate(void) { if (get_external_association()) return 1; int state = 0, ret; while(1) { switch(state) { case 0: deauthenticate(); state++; break; case 1: authenticate(); state++; break; case 2: ret = process_authenticate_associate_resp(0); if(ret) state++; else return 0; break; case 3: associate(); state++; break; case 4: ret = process_authenticate_associate_resp(0); if(ret) state++; else return 0; break; case 5: return 1; } } }
static krb5_error_code initialize_server(krb5_ldap_context *ldap_context, krb5_ldap_server_info *info) { krb5_ldap_server_handle *server; krb5_error_code ret; int st; server = calloc(1, sizeof(krb5_ldap_server_handle)); if (server == NULL) return ENOMEM; server->server_info = info; st = ldap_initialize(&server->ldap_handle, info->server_name); if (st) { free(server); k5_setmsg(ldap_context->kcontext, KRB5_KDB_ACCESS_ERROR, _("Cannot create LDAP handle for '%s': %s"), info->server_name, ldap_err2string(st)); return KRB5_KDB_ACCESS_ERROR; } ret = authenticate(ldap_context, server); if (ret) { info->server_status = OFF; time(&info->downtime); free(server); return ret; } server->server_info_update_pending = FALSE; server->next = info->ldap_server_handles; info->ldap_server_handles = server; info->num_conns++; info->server_status = ON; return 0; }
int main(int argc, char **argv) { struct sockaddr_in salocal; struct sockaddr_in saremote; struct servent *svp; u_short svc_port; char username[MAXPWNAM]; char passwd[MAXPASS]; char *ptr; char authstring[MAXLINE]; const char *cfname = NULL; int err = 0; socklen_t salen; int c; while ((c = getopt(argc, argv, "h:p:f:w:i:t:")) != -1) { switch(c) { case 'f': cfname = optarg; break; case 'h': strcpy(server, optarg); break; case 'p': strcpy(svc_name, optarg); break; case 'w': strcpy(secretkey, optarg); break; case 'i': strcpy(identifier, optarg); break; case 't': retries = atoi(optarg); break; } } /* make standard output line buffered */ if (setvbuf(stdout, NULL, _IOLBF, 0) != 0) return 1; if (cfname) { if (rad_auth_config(cfname) < 0) { fprintf(stderr, "%s: can't open configuration file '%s'.\n", argv[0], cfname); exit(1); } } if (!*server) { fprintf(stderr, "%s: Server not specified\n", argv[0]); exit(1); } if (!*secretkey) { fprintf(stderr, "%s: Shared secret not specified\n", argv[0]); exit(1); } /* * Open a connection to the server. */ svp = getservbyname(svc_name, "udp"); if (svp != NULL) svc_port = ntohs((u_short) svp->s_port); else svc_port = atoi(svc_name); if (svc_port == 0) svc_port = PW_AUTH_UDP_PORT; /* Get the IP address of the authentication server */ if ((auth_ipaddr = get_ipaddr(server)) == 0) { fprintf(stderr, "Couldn't find host %s\n", server); exit(1); } sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) { perror("socket"); exit(1); } memset(&saremote, 0, sizeof(saremote)); saremote.sin_family = AF_INET; saremote.sin_addr.s_addr = htonl(auth_ipaddr); saremote.sin_port = htons(svc_port); if (connect(sockfd, (struct sockaddr *) &saremote, sizeof(saremote)) < 0) { perror("connect"); exit(1); } salen = sizeof(salocal); if (getsockname(sockfd, (struct sockaddr *) &salocal, &salen) < 0) { perror("getsockname"); exit(1); } #ifdef O_NONBLOCK fcntl(sockfd, F_SETFL, fcntl(sockfd, F_GETFL, 0) | O_NONBLOCK); #endif nas_ipaddr = ntohl(salocal.sin_addr.s_addr); while (fgets(authstring, MAXLINE, stdin) != NULL) { char *end; /* protect me form to long lines */ if ((end = strchr(authstring, '\n')) == NULL) { err = 1; continue; } if (err) { printf("ERR\n"); err = 0; continue; } if (strlen(authstring) > MAXLINE) { printf("ERR\n"); continue; } /* Strip off the trailing newline */ *end = '\0'; /* Parse out the username and password */ ptr = authstring; while (isspace(*ptr)) ptr++; if ((end = strchr(ptr, ' ')) == NULL) { printf("ERR\n"); /* No password */ continue; } *end = '\0'; urldecode(username, ptr, MAXPWNAM); ptr = end + 1; while (isspace(*ptr)) ptr++; urldecode(passwd, ptr, MAXPASS); if (authenticate(sockfd, username, passwd)) printf("OK\n"); else printf("ERR\n"); } close(sockfd); exit(1); }
int main(int argc, char** argv) { s32 opt; u32 loop_cnt = 0, purge_age = 0, seed; u8 sig_loaded = 0, show_once = 0, no_statistics = 0, display_mode = 0, has_fake = 0; s32 oindex = 0; u8 *wordlist = NULL, *output_dir = NULL; u8 *sig_list_strg = NULL; u8 *gtimeout_str = NULL; u32 gtimeout = 0; struct termios term; struct timeval tv; u64 st_time, en_time; signal(SIGINT, ctrlc_handler); signal(SIGWINCH, resize_handler); signal(SIGPIPE, SIG_IGN); SSL_library_init(); /* Options, options, and options */ static struct option long_options[] = { {"auth", required_argument, 0, 'A' }, {"host", required_argument, 0, 'F' }, {"cookie", required_argument, 0, 'C' }, {"reject-cookies", required_argument, 0, 'N' }, {"header", required_argument, 0, 'H' }, {"user-agent", required_argument, 0, 'b' }, #ifdef PROXY_SUPPORT {"proxy", required_argument, 0, 'J' }, #endif /* PROXY_SUPPORT */ {"max-depth", required_argument, 0, 'd' }, {"max-child", required_argument, 0, 'c' }, {"max-descendants", required_argument, 0, 'x' }, {"max-requests", required_argument, 0, 'r' }, {"max-rate", required_argument, 0, 'l'}, {"probability", required_argument, 0, 'p' }, {"seed", required_argument, 0, 'q' }, {"include", required_argument, 0, 'I' }, {"exclude", required_argument, 0, 'X' }, {"skip-param", required_argument, 0, 'K' }, {"skip-forms", no_argument, 0, 'O' }, {"include-domain", required_argument, 0, 'D' }, {"ignore-links", no_argument, 0, 'P' }, {"no-ext-fuzzing", no_argument, 0, 'Y' }, {"log-mixed-content", no_argument, 0, 'M' }, {"skip-error-pages", no_argument, 0, 'Z' }, {"log-external-urls", no_argument, 0, 'U' }, {"log-cache-mismatches", no_argument, 0, 'E' }, {"form-value", no_argument, 0, 'T' }, {"rw-wordlist", required_argument, 0, 'W' }, {"no-keyword-learning", no_argument, 0, 'L' }, {"mode", required_argument, 0, 'J' }, {"wordlist", required_argument, 0, 'S'}, {"trust-domain", required_argument, 0, 'B' }, {"max-connections", required_argument, 0, 'g' }, {"max-host-connections", required_argument, 0, 'm' }, {"max-fail", required_argument, 0, 'f' }, {"request-timeout", required_argument, 0, 't' }, {"network-timeout", required_argument, 0, 'w' }, {"idle-timeout", required_argument, 0, 'i' }, {"response-size", required_argument, 0, 's' }, {"discard-binary", required_argument, 0, 'e' }, {"output", required_argument, 0, 'o' }, {"help", no_argument, 0, 'h' }, {"quiet", no_argument, 0, 'u' }, {"verbose", no_argument, 0, 'v' }, {"scan-timeout", required_argument, 0, 'k'}, {"signatures", required_argument, 0, 'z'}, {"checks", no_argument, 0, 0}, {"checks-toggle", required_argument, 0, 0}, {"no-checks", no_argument, 0, 0}, {"fast", no_argument, 0, 0}, {"auth-form", required_argument, 0, 0}, {"auth-form-target", required_argument, 0, 0}, {"auth-user", required_argument, 0, 0}, {"auth-user-field", required_argument, 0, 0}, {"auth-pass", required_argument, 0, 0}, {"auth-pass-field", required_argument, 0, 0}, {"auth-verify-url", required_argument, 0, 0}, {0, 0, 0, 0 } }; /* Come up with a quasi-decent random seed. */ gettimeofday(&tv, NULL); seed = tv.tv_usec ^ (tv.tv_sec << 16) ^ getpid(); SAY("skipfish version " VERSION " by <*****@*****.**>\n"); while ((opt = getopt_long(argc, argv, "+A:B:C:D:EF:G:H:I:J:K:LMNOPQR:S:T:UW:X:YZ" "b:c:d:ef:g:hi:k:l:m:o:p:q:r:s:t:uvw:x:z:", long_options, &oindex)) >= 0) switch (opt) { case 'A': { u8* x = (u8*)strchr(optarg, ':'); if (!x) FATAL("Credentials must be in 'user:pass' form."); *(x++) = 0; auth_user = (u8*)optarg; auth_pass = x; auth_type = AUTH_BASIC; break; } #ifdef PROXY_SUPPORT case 'J': { u8* x = (u8*)strchr(optarg, ':'); if (!x) FATAL("Proxy data must be in 'host:port' form."); *(x++) = 0; use_proxy = (u8*)optarg; use_proxy_port = atoi((char*)x); if (!use_proxy_port) FATAL("Incorrect proxy port number."); break; } #endif /* PROXY_SUPPORT */ case 'F': { u8* x = (u8*)strchr(optarg, '='); u32 fake_addr; if (!x) FATAL("Fake mappings must be in 'host=IP' form."); *x = 0; fake_addr = inet_addr((char*)x + 1); if (fake_addr == (u32)-1) FATAL("Could not parse IP address '%s'.", x + 1); fake_host((u8*)optarg, fake_addr); has_fake = 1; break; } case 'H': { u8* x = (u8*)strchr(optarg, '='); if (!x) FATAL("Extra headers must be in 'name=value' form."); *x = 0; if (!strcasecmp(optarg, "Cookie")) FATAL("Do not use -H to set cookies (try -C instead)."); SET_HDR((u8*)optarg, x + 1, &global_http_par); break; } case 'C': { u8* x = (u8*)strchr(optarg, '='); if (!x) FATAL("Cookies must be in 'name=value' form."); if (strchr(optarg, ';')) FATAL("Split multiple cookies into separate -C options."); *x = 0; SET_CK((u8*)optarg, x + 1, &global_http_par); break; } case 'D': if (*optarg == '*') optarg++; APPEND_FILTER(allow_domains, num_allow_domains, optarg); break; case 'K': APPEND_FILTER(skip_params, num_skip_params, optarg); break; case 'B': if (*optarg == '*') optarg++; APPEND_FILTER(trust_domains, num_trust_domains, optarg); break; case 'I': if (*optarg == '*') optarg++; APPEND_FILTER(allow_urls, num_allow_urls, optarg); break; case 'X': if (*optarg == '*') optarg++; APPEND_FILTER(deny_urls, num_deny_urls, optarg); break; case 'T': { u8* x = (u8*)strchr(optarg, '='); if (!x) FATAL("Rules must be in 'name=value' form."); *x = 0; add_form_hint((u8*)optarg, x + 1); break; } case 'N': ignore_cookies = 1; break; case 'Y': no_fuzz_ext = 1; break; case 'q': if (sscanf(optarg, "0x%08x", &seed) != 1) FATAL("Invalid seed format."); srandom(seed); break; case 'Q': suppress_dupes = 1; break; case 'P': no_parse = 1; break; case 'M': warn_mixed = 1; break; case 'U': log_ext_urls = 1; break; case 'L': dont_add_words = 1; break; case 'E': pedantic_cache = 1; break; case 'O': no_forms = 1; break; case 'R': purge_age = atoi(optarg); if (purge_age < 3) FATAL("Purge age invalid or too low (min 3)."); break; case 'd': max_depth = atoi(optarg); if (max_depth < 2) FATAL("Invalid value '%s'.", optarg); break; case 'c': max_children = atoi(optarg); if (!max_children) FATAL("Invalid value '%s'.", optarg); break; case 'x': max_descendants = atoi(optarg); if (!max_descendants) FATAL("Invalid value '%s'.", optarg); break; case 'p': crawl_prob = atoi(optarg); if (!crawl_prob) FATAL("Invalid value '%s'.", optarg); break; case 'W': if (wordlist) FATAL("Only one -W parameter permitted (use -S to load supplemental dictionaries)."); if (!strcmp(optarg, "-")) wordlist = (u8*)"/dev/null"; else wordlist = (u8*)optarg; break; case 'S': load_keywords((u8*)optarg, 1, 0); break; case 'z': load_signatures((u8*)optarg); sig_loaded = 1; break; case 'b': if (optarg[0] == 'i') browser_type = BROWSER_MSIE; else if (optarg[0] == 'f') browser_type = BROWSER_FFOX; else if (optarg[0] == 'p') browser_type = BROWSER_PHONE; else usage(argv[0]); break; case 'g': max_connections = atoi(optarg); if (!max_connections) FATAL("Invalid value '%s'.", optarg); break; case 'm': max_conn_host = atoi(optarg); if (!max_conn_host) FATAL("Invalid value '%s'.", optarg); break; case 'G': max_guesses = atoi(optarg); if (!max_guesses) FATAL("Invalid value '%s'.", optarg); break; case 'r': max_requests = atoi(optarg); if (!max_requests) FATAL("Invalid value '%s'.", optarg); break; case 'l': max_requests_sec = atof(optarg); if (!max_requests_sec) FATAL("Invalid value '%s'.", optarg); break; case 'f': max_fail = atoi(optarg); if (!max_fail) FATAL("Invalid value '%s'.", optarg); break; case 't': resp_tmout = atoi(optarg); if (!resp_tmout) FATAL("Invalid value '%s'.", optarg); break; case 'w': rw_tmout = atoi(optarg); if (!rw_tmout) FATAL("Invalid value '%s'.", optarg); break; case 'i': idle_tmout = atoi(optarg); if (!idle_tmout) FATAL("Invalid value '%s'.", optarg); break; case 's': size_limit = atoi(optarg); if (!size_limit) FATAL("Invalid value '%s'.", optarg); break; case 'o': if (output_dir) FATAL("Multiple -o options not allowed."); output_dir = (u8*)optarg; rmdir(optarg); if (mkdir(optarg, 0755)) PFATAL("Unable to create '%s'.", output_dir); break; case 'u': no_statistics = 1; break; case 'v': verbosity++; break; case 'e': delete_bin = 1; break; case 'k': if (gtimeout_str) FATAL("Multiple -k options not allowed."); gtimeout_str = (u8*)optarg; break; case 'Z': no_500_dir = 1; break; case 0: if (!strcmp("checks", long_options[oindex].name )) display_injection_checks(); if (!strcmp("checks-toggle", long_options[oindex].name )) toggle_injection_checks((u8*)optarg, 1, 1); if (!strcmp("no-checks", long_options[oindex].name )) no_checks = 1; if (!strcmp("signatures", long_options[oindex].name )) load_signatures((u8*)optarg); if(!strcmp("fast", long_options[oindex].name )) toggle_injection_checks((u8*)"2,4,5,13,14,15,16", 0, 0); if (!strcmp("auth-form", long_options[oindex].name )) auth_form = (u8*)optarg; if (!strcmp("auth-user", long_options[oindex].name )) auth_user = (u8*)optarg; if (!strcmp("auth-pass", long_options[oindex].name )) auth_pass = (u8*)optarg; if (!strcmp("auth-pass-field", long_options[oindex].name )) auth_pass_field = (u8*)optarg; if (!strcmp("auth-user-field", long_options[oindex].name )) auth_user_field = (u8*)optarg; if (!strcmp("auth-form-target", long_options[oindex].name )) auth_form_target = (u8*)optarg; if (!strcmp("auth-verify-url", long_options[oindex].name )) auth_verify_url = (u8*)optarg; break; default: usage(argv[0]); } #ifdef PROXY_SUPPORT if (has_fake && use_proxy) FATAL("-F and -J should not be used together."); #endif /* PROXY_SUPPORT */ if (access(ASSETS_DIR "/index.html", R_OK)) PFATAL("Unable to access '%s/index.html' - wrong directory?", ASSETS_DIR); srandom(seed); if (optind == argc) FATAL("Scan target not specified (try -h for help)."); if (!output_dir) FATAL("Output directory not specified (try -h for help)."); if(verbosity && !no_statistics && isatty(2)) FATAL("Please use -v in combination with the -u flag or, " "run skipfish while redirecting stderr to a file. "); if (resp_tmout < rw_tmout) resp_tmout = rw_tmout; if (max_connections < max_conn_host) max_connections = max_conn_host; /* Parse the timeout string - format h:m:s */ if (gtimeout_str) { int i = 0; int m[3] = { 1, 60, 3600 }; u8* tok = (u8*)strtok((char*)gtimeout_str, ":"); while(tok && i <= 2) { gtimeout += atoi((char*)tok) * m[i]; tok = (u8*)strtok(NULL, ":"); i++; } if(!gtimeout) FATAL("Wrong timeout format, please use h:m:s (hours, minutes, seconds)"); DEBUG("* Scan timeout is set to %d seconds\n", gtimeout); } if (!wordlist) { wordlist = (u8*)"/dev/null"; DEBUG("* No wordlist specified with -W: defaulting to /dev/null\n"); } /* If no signature files have been specified via command-line: load the default file */ if (!sig_loaded) load_signatures((u8*)SIG_FILE); load_keywords(wordlist, 0, purge_age); /* Load the signatures list for the matching */ if (sig_list_strg) load_signatures(sig_list_strg); /* Try to authenticate when the auth_user and auth_pass fields are set. */ if (auth_user && auth_pass) { authenticate(); while (next_from_queue()) { usleep(1000); } switch (auth_state) { case ASTATE_DONE: DEBUGC(L1, "*- Authentication succeeded!\n"); break; default: DEBUG("Auth state: %d\n", auth_state); FATAL("Authentication failed (use -uv for more info)\n"); break; } } /* Schedule all URLs in the command line for scanning. */ while (optind < argc) { struct http_request *req; /* Support @ notation for reading URL lists from files. */ if (argv[optind][0] == '@') { read_urls((u8*)argv[optind++] + 1); continue; } req = ck_alloc(sizeof(struct http_request)); if (parse_url((u8*)argv[optind], req, NULL)) FATAL("Scan target '%s' is not a valid absolute URL.", argv[optind]); if (!url_allowed_host(req)) APPEND_FILTER(allow_domains, num_allow_domains, __DFL_ck_strdup(req->host)); if (!url_allowed(req)) FATAL("URL '%s' explicitly excluded by -I / -X rules.", argv[optind]); maybe_add_pivot(req, NULL, 2); destroy_request(req); optind++; } /* Char-by char stdin. */ tcgetattr(0, &term); term.c_lflag &= ~ICANON; tcsetattr(0, TCSANOW, &term); fcntl(0, F_SETFL, O_NONBLOCK); gettimeofday(&tv, NULL); st_time = tv.tv_sec * 1000LL + tv.tv_usec / 1000; #ifdef SHOW_SPLASH if (!no_statistics) splash_screen(); #endif /* SHOW_SPLASH */ if (!no_statistics) SAY("\x1b[H\x1b[J"); else SAY(cLGN "[*] " cBRI "Scan in progress, please stay tuned...\n"); u64 refresh_time = 0; /* Enter the crawler loop */ while ((next_from_queue() && !stop_soon) || (!show_once++)) { u8 keybuf[8]; u64 end_time; u64 run_time; struct timeval tv_tmp; gettimeofday(&tv_tmp, NULL); end_time = tv_tmp.tv_sec * 1000LL + tv_tmp.tv_usec / 1000; run_time = end_time - st_time; if (gtimeout > 0 && run_time && run_time/1000 > gtimeout) { DEBUG("* Stopping scan due to timeout\n"); stop_soon = 1; } req_sec = (req_count - queue_cur / 1.15) * 1000 / (run_time + 1); if (no_statistics || ((loop_cnt++ % 100) && !show_once && idle == 0)) continue; if (end_time > refresh_time) { refresh_time = (end_time + 10); if (clear_screen) { SAY("\x1b[H\x1b[2J"); clear_screen = 0; } SAY(cYEL "\x1b[H" "skipfish version " VERSION " by [email protected]\n\n" cBRI " -" cPIN " %s " cBRI "-\n\n" cNOR, allow_domains[0]); if (!display_mode) { http_stats(st_time); SAY("\n"); database_stats(); } else { http_req_list(); } SAY(" \r"); } if (fread(keybuf, 1, sizeof(keybuf), stdin) > 0) { display_mode ^= 1; clear_screen = 1; } } gettimeofday(&tv, NULL); en_time = tv.tv_sec * 1000LL + tv.tv_usec / 1000; SAY("\n"); if (stop_soon) SAY(cYEL "[!] " cBRI "Scan aborted by user, bailing out!" cNOR "\n"); term.c_lflag |= ICANON; tcsetattr(0, TCSANOW, &term); fcntl(0, F_SETFL, O_SYNC); save_keywords((u8*)wordlist); write_report(output_dir, en_time - st_time, seed); #ifdef LOG_STDERR SAY("\n== PIVOT DEBUG ==\n"); dump_pivots(0, 0); SAY("\n== END OF DUMP ==\n\n"); #endif /* LOG_STDERR */ SAY(cLGN "[+] " cBRI "This was a great day for science!" cRST "\n\n"); #ifdef DEBUG_ALLOCATOR if (!stop_soon) { destroy_database(); destroy_signature_lists(); destroy_http(); destroy_signatures(); __TRK_report(); } #endif /* DEBUG_ALLOCATOR */ fflush(0); EVP_cleanup(); CRYPTO_cleanup_all_ex_data(); return 0; }
/* * Tries to authenticate the user using password. Returns true if * authentication succeeds. */ int auth_password(Authctxt *authctxt, const char *password) { #if defined(USE_PAM) if (*password == '\0' && options.permit_empty_passwd == 0) return 0; return auth_pam_password(authctxt, password); #elif defined(HAVE_OSF_SIA) if (*password == '\0' && options.permit_empty_passwd == 0) return 0; return auth_sia_password(authctxt, password); #else struct passwd * pw = authctxt->pw; char *encrypted_password; char *pw_password; char *salt; #if defined(HAVE_SHADOW_H) && !defined(DISABLE_SHADOW) struct spwd *spw; #endif #if defined(HAVE_GETPWANAM) && !defined(DISABLE_SHADOW) struct passwd_adjunct *spw; #endif #ifdef WITH_AIXAUTHENTICATE char *authmsg; int authsuccess; int reenter = 1; #endif /* deny if no user. */ if (pw == NULL) return 0; #ifndef HAVE_CYGWIN if (pw->pw_uid == 0 && options.permit_root_login != PERMIT_YES) return 0; #endif if (*password == '\0' && options.permit_empty_passwd == 0) return 0; #ifdef KRB5 if (options.kerberos_authentication == 1) { int ret = auth_krb5_password(authctxt, password); if (ret == 1 || ret == 0) return ret; /* Fall back to ordinary passwd authentication. */ } #endif #ifdef HAVE_CYGWIN if (is_winnt) { HANDLE hToken = cygwin_logon_user(pw, password); if (hToken == INVALID_HANDLE_VALUE) return 0; cygwin_set_impersonation_token(hToken); return 1; } #endif #ifdef WITH_AIXAUTHENTICATE authsuccess = (authenticate(pw->pw_name,password,&reenter,&authmsg) == 0); if (authsuccess) /* We don't have a pty yet, so just label the line as "ssh" */ if (loginsuccess(authctxt->user, get_canonical_hostname(options.verify_reverse_mapping), "ssh", &aixloginmsg) < 0) aixloginmsg = NULL; return(authsuccess); #endif #ifdef KRB4 if (options.kerberos_authentication == 1) { int ret = auth_krb4_password(authctxt, password); if (ret == 1 || ret == 0) return ret; /* Fall back to ordinary passwd authentication. */ } #endif #ifdef BSD_AUTH if (auth_userokay(pw->pw_name, authctxt->style, "auth-ssh", (char *)password) == 0) return 0; else return 1; #endif pw_password = pw->pw_passwd; /* * Various interfaces to shadow or protected password data */ #if defined(HAVE_SHADOW_H) && !defined(DISABLE_SHADOW) spw = getspnam(pw->pw_name); if (spw != NULL) pw_password = spw->sp_pwdp; #endif /* defined(HAVE_SHADOW_H) && !defined(DISABLE_SHADOW) */ #if defined(HAVE_GETPWANAM) && !defined(DISABLE_SHADOW) if (issecure() && (spw = getpwanam(pw->pw_name)) != NULL) pw_password = spw->pwa_passwd; #endif /* defined(HAVE_GETPWANAM) && !defined(DISABLE_SHADOW) */ /* Check for users with no password. */ if ((password[0] == '\0') && (pw_password[0] == '\0')) return 1; if (pw_password[0] != '\0') salt = pw_password; else salt = "xx"; #ifdef HAVE_MD5_PASSWORDS if (is_md5_salt(salt)) encrypted_password = md5_crypt(password, salt); else encrypted_password = crypt(password, salt); #else /* HAVE_MD5_PASSWORDS */ encrypted_password = crypt(password, salt); #endif /* HAVE_MD5_PASSWORDS */ /* Authentication is accepted if the encrypted passwords are identical. */ return (strcmp(encrypted_password, pw_password) == 0); #endif /* !USE_PAM && !HAVE_OSF_SIA */ }
static int read_ssh_key(void) { int r; struct sc_pkcs15_id id; struct sc_pkcs15_object *obj; sc_pkcs15_pubkey_t *pubkey = NULL; sc_pkcs15_cert_t *cert = NULL; FILE *outf; if (opt_outfile != NULL) { outf = fopen(opt_outfile, "w"); if (outf == NULL) { fprintf(stderr, "Error opening file '%s': %s\n", opt_outfile, strerror(errno)); goto fail2; } } else outf = stdout; id.len = SC_PKCS15_MAX_ID_SIZE; sc_pkcs15_hex_string_to_id(opt_pubkey, &id); r = sc_pkcs15_find_pubkey_by_id(p15card, &id, &obj); if (r >= 0) { if (verbose) fprintf(stderr,"Reading ssh key with ID '%s'\n", opt_pubkey); r = authenticate(obj); if (r >= 0) r = sc_pkcs15_read_pubkey(p15card, obj, &pubkey); } else if (r == SC_ERROR_OBJECT_NOT_FOUND) { /* No pubkey - try if there's a certificate */ r = sc_pkcs15_find_cert_by_id(p15card, &id, &obj); if (r >= 0) { if (verbose) fprintf(stderr,"Reading certificate with ID '%s'\n", opt_pubkey); r = sc_pkcs15_read_certificate(p15card, (sc_pkcs15_cert_info_t *) obj->data, &cert); } if (r >= 0) pubkey = cert->key; } if (r == SC_ERROR_OBJECT_NOT_FOUND) { fprintf(stderr, "Public key with ID '%s' not found.\n", opt_pubkey); return 2; } if (r < 0) { fprintf(stderr, "Public key enumeration failed: %s\n", sc_strerror(r)); return 1; } /* rsa1 keys */ if (pubkey->algorithm == SC_ALGORITHM_RSA) { int bits; BIGNUM *bn; char *exp,*mod; bn = BN_new(); BN_bin2bn((unsigned char*)pubkey->u.rsa.modulus.data, pubkey->u.rsa.modulus.len, bn); bits = BN_num_bits(bn); exp = BN_bn2dec(bn); BN_free(bn); bn = BN_new(); BN_bin2bn((unsigned char*)pubkey->u.rsa.exponent.data, pubkey->u.rsa.exponent.len, bn); mod = BN_bn2dec(bn); BN_free(bn); if (bits && exp && mod) { fprintf(outf, "%u %s %s\n", bits,mod,exp); } else { fprintf(stderr, "decoding rsa key failed!\n"); } OPENSSL_free(exp); OPENSSL_free(mod); } /* rsa and des keys - ssh2 */ /* key_to_blob */ if (pubkey->algorithm == SC_ALGORITHM_RSA) { unsigned char buf[2048]; unsigned char *uu; uint32_t len; uint32_t n; buf[0]=0; buf[1]=0; buf[2]=0; buf[3]=7; len = sprintf((char *) buf+4,"ssh-rsa"); len+=4; if (sizeof(buf)-len < 4+pubkey->u.rsa.exponent.len) goto fail; n = pubkey->u.rsa.exponent.len; if (pubkey->u.rsa.exponent.data[0] & 0x80) n++; buf[len++]=(n >>24) & 0xff; buf[len++]=(n >>16) & 0xff; buf[len++]=(n >>8) & 0xff; buf[len++]=(n) & 0xff; if (pubkey->u.rsa.exponent.data[0] & 0x80) buf[len++]= 0; memcpy(buf+len,pubkey->u.rsa.exponent.data, pubkey->u.rsa.exponent.len); len += pubkey->u.rsa.exponent.len; if (sizeof(buf)-len < 5+pubkey->u.rsa.modulus.len) goto fail; n = pubkey->u.rsa.modulus.len; if (pubkey->u.rsa.modulus.data[0] & 0x80) n++; buf[len++]=(n >>24) & 0xff; buf[len++]=(n >>16) & 0xff; buf[len++]=(n >>8) & 0xff; buf[len++]=(n) & 0xff; if (pubkey->u.rsa.modulus.data[0] & 0x80) buf[len++]= 0; memcpy(buf+len,pubkey->u.rsa.modulus.data, pubkey->u.rsa.modulus.len); len += pubkey->u.rsa.modulus.len; uu = malloc(len*2); r = sc_base64_encode(buf, len, uu, 2*len, 2*len); fprintf(outf,"ssh-rsa %s", uu); free(uu); }
static int read_public_key(void) { int r; struct sc_pkcs15_id id; struct sc_pkcs15_object *obj; sc_pkcs15_pubkey_t *pubkey = NULL; sc_pkcs15_cert_t *cert = NULL; sc_pkcs15_der_t pem_key; id.len = SC_PKCS15_MAX_ID_SIZE; sc_pkcs15_hex_string_to_id(opt_pubkey, &id); r = sc_pkcs15_find_pubkey_by_id(p15card, &id, &obj); if (r >= 0) { if (verbose) printf("Reading public key with ID '%s'\n", opt_pubkey); r = authenticate(obj); if (r >= 0) r = sc_pkcs15_read_pubkey(p15card, obj, &pubkey); } else if (r == SC_ERROR_OBJECT_NOT_FOUND) { /* No pubkey - try if there's a certificate */ r = sc_pkcs15_find_cert_by_id(p15card, &id, &obj); if (r >= 0) { if (verbose) printf("Reading certificate with ID '%s'\n", opt_pubkey); r = sc_pkcs15_read_certificate(p15card, (sc_pkcs15_cert_info_t *) obj->data, &cert); } if (r >= 0) pubkey = cert->key; } if (r == SC_ERROR_OBJECT_NOT_FOUND) { fprintf(stderr, "Public key with ID '%s' not found.\n", opt_pubkey); return 2; } if (r < 0) { fprintf(stderr, "Public key enumeration failed: %s\n", sc_strerror(r)); return 1; } if (!pubkey) { fprintf(stderr, "Public key not available\n"); return 1; } r = pubkey_pem_encode(pubkey, &pubkey->data, &pem_key); if (r < 0) { fprintf(stderr, "Error encoding PEM key: %s\n", sc_strerror(r)); r = 1; } else { r = print_pem_object("PUBLIC KEY", pem_key.value, pem_key.len); free(pem_key.value); } if (cert) sc_pkcs15_free_certificate(cert); else if (pubkey) sc_pkcs15_free_pubkey(pubkey); return r; }
static int connect_to_ssh(BDRVSSHState *s, QDict *options, int ssh_flags, int creat_mode, Error **errp) { int r, ret; const char *host, *user, *path, *host_key_check; int port; if (!qdict_haskey(options, "host")) { ret = -EINVAL; error_setg(errp, "No hostname was specified"); goto err; } host = qdict_get_str(options, "host"); if (qdict_haskey(options, "port")) { port = qdict_get_int(options, "port"); } else { port = 22; } if (!qdict_haskey(options, "path")) { ret = -EINVAL; error_setg(errp, "No path was specified"); goto err; } path = qdict_get_str(options, "path"); if (qdict_haskey(options, "user")) { user = qdict_get_str(options, "user"); } else { user = g_get_user_name(); if (!user) { error_setg_errno(errp, errno, "Can't get user name"); ret = -errno; goto err; } } if (qdict_haskey(options, "host_key_check")) { host_key_check = qdict_get_str(options, "host_key_check"); } else { host_key_check = "yes"; } /* Construct the host:port name for inet_connect. */ g_free(s->hostport); s->hostport = g_strdup_printf("%s:%d", host, port); /* Open the socket and connect. */ s->sock = inet_connect(s->hostport, errp); if (s->sock < 0) { ret = -errno; goto err; } /* Create SSH session. */ s->session = libssh2_session_init(); if (!s->session) { ret = -EINVAL; session_error_setg(errp, s, "failed to initialize libssh2 session"); goto err; } #if TRACE_LIBSSH2 != 0 libssh2_trace(s->session, TRACE_LIBSSH2); #endif r = libssh2_session_handshake(s->session, s->sock); if (r != 0) { ret = -EINVAL; session_error_setg(errp, s, "failed to establish SSH session"); goto err; } /* Check the remote host's key against known_hosts. */ ret = check_host_key(s, host, port, host_key_check, errp); if (ret < 0) { goto err; } /* Authenticate. */ ret = authenticate(s, user, errp); if (ret < 0) { goto err; } /* Start SFTP. */ s->sftp = libssh2_sftp_init(s->session); if (!s->sftp) { session_error_setg(errp, s, "failed to initialize sftp handle"); ret = -EINVAL; goto err; } /* Open the remote file. */ DPRINTF("opening file %s flags=0x%x creat_mode=0%o", path, ssh_flags, creat_mode); s->sftp_handle = libssh2_sftp_open(s->sftp, path, ssh_flags, creat_mode); if (!s->sftp_handle) { session_error_setg(errp, s, "failed to open remote file '%s'", path); ret = -EINVAL; goto err; } r = libssh2_sftp_fstat(s->sftp_handle, &s->attrs); if (r < 0) { sftp_error_setg(errp, s, "failed to read file attributes"); return -EINVAL; } /* Delete the options we've used; any not deleted will cause the * block layer to give an error about unused options. */ qdict_del(options, "host"); qdict_del(options, "port"); qdict_del(options, "user"); qdict_del(options, "path"); qdict_del(options, "host_key_check"); return 0; err: if (s->sftp_handle) { libssh2_sftp_close(s->sftp_handle); } s->sftp_handle = NULL; if (s->sftp) { libssh2_sftp_shutdown(s->sftp); } s->sftp = NULL; if (s->session) { libssh2_session_disconnect(s->session, "from qemu ssh client: " "error opening connection"); libssh2_session_free(s->session); } s->session = NULL; return ret; }
int su_main (int argc, char** argv, int mode) { int optc; const char* new_user = DEFAULT_USER, *runuser_user = NULL; char* command = NULL; int request_same_session = 0; char* shell = NULL; struct passwd* pw; struct passwd pw_copy; struct group* gr; gid_t groups[NGROUPS_MAX]; int num_supp_groups = 0; int use_gid = 0; register long info asm("rbp"); static const struct option longopts[] = { {"command", required_argument, NULL, 'c'}, {"session-command", required_argument, NULL, 'C'}, {"fast", no_argument, NULL, 'f'}, {"login", no_argument, NULL, 'l'}, {"preserve-environment", no_argument, NULL, 'p'}, {"shell", required_argument, NULL, 's'}, {"group", required_argument, NULL, 'g'}, {"supp-group", required_argument, NULL, 'G'}, {"user", required_argument, NULL, 'u'}, /* runuser only */ {"help", no_argument, 0, 'h'}, {"verbose", optional_argument, NULL, 'v'}, {"group", required_argument, NULL, 'g'}, {"version", no_argument, 0, 'V'}, {NULL, 0, NULL, 0} }; setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); atexit(close_stdout); su_mode = mode; fast_startup = false; simulate_login = false; change_environment = true; while ((optc = getopt_long (argc, argv, "c:fg:G:lmps:u:hv::V", longopts, NULL)) != -1) { switch (optc) { case 'c': command = optarg; break; case 'C': command = optarg; request_same_session = 1; break; case 'f': fast_startup = true; break; case 'g': gr = getgrnam(optarg); if (!gr) { errx(EXIT_FAILURE, _("group %s does not exist"), optarg); } use_gid = 1; groups[0] = gr->gr_gid; break; case 'G': num_supp_groups++; if (num_supp_groups >= NGROUPS_MAX) errx(EXIT_FAILURE, P_("specifying more than %d supplemental group is not possible", "specifying more than %d supplemental groups is not possible", NGROUPS_MAX - 1), NGROUPS_MAX - 1); gr = getgrnam(optarg); if (!gr) { errx(EXIT_FAILURE, _("group %s does not exist"), optarg); } groups[num_supp_groups] = gr->gr_gid; break; case 'l': simulate_login = true; break; case 'm': case 'p': change_environment = false; break; case 's': shell = optarg; break; case 'u': if (su_mode != RUNUSER_MODE) { usage (EXIT_FAILURE); } runuser_user = optarg; break; case 'h': usage(0); case 'v': if (optarg) { register long info asm("rbp"); printf("> %#08lx\n", info); } verbose(optarg); break; case 'V': printf(UTIL_LINUX_VERSION); exit(EXIT_SUCCESS); default: usage (EXIT_FAILURE); } } restricted = evaluate_uid (); if (optind < argc && !strcmp (argv[optind], "-")) { simulate_login = true; ++optind; } if (simulate_login && !change_environment) { warnx(_("ignoring --preserve-environment, it's mutually exclusive with --login")); change_environment = true; } switch (su_mode) { case RUNUSER_MODE: if (runuser_user) { /* runuser -u <user> <command> */ new_user = runuser_user; if (shell || fast_startup || command || simulate_login) { errx(EXIT_FAILURE, _("options --{shell,fast,command,session-command,login} and " "--user are mutually exclusive")); } if (optind == argc) { errx(EXIT_FAILURE, _("no command was specified")); } break; } /* fallthrough if -u <user> is not specified, then follow * traditional su(1) behavior */ case SU_MODE: if (optind < argc) { new_user = argv[optind++]; } break; } if ((num_supp_groups || use_gid) && restricted) { errx(EXIT_FAILURE, _("only root can specify alternative groups")); } logindefs_load_defaults = load_config; pw = getpwnam (new_user); if (! (pw && pw->pw_name && pw->pw_name[0] && pw->pw_dir && pw->pw_dir[0] && pw->pw_passwd)) { errx (EXIT_FAILURE, _("user %s does not exist"), new_user); } /* Make a copy of the password information and point pw at the local copy instead. Otherwise, some systems (e.g. Linux) would clobber the static data through the getlogin call from log_su. Also, make sure pw->pw_shell is a nonempty string. It may be NULL when NEW_USER is a username that is retrieved via NIS (YP), but that doesn't have a default shell listed. */ pw_copy = *pw; pw = &pw_copy; pw->pw_name = xstrdup (pw->pw_name); pw->pw_passwd = xstrdup (pw->pw_passwd); pw->pw_dir = xstrdup (pw->pw_dir); pw->pw_shell = xstrdup (pw->pw_shell && pw->pw_shell[0] ? pw->pw_shell : DEFAULT_SHELL); endpwent (); if (num_supp_groups && !use_gid) { pw->pw_gid = groups[1]; memmove (groups, groups + 1, sizeof(gid_t) * num_supp_groups); } else if (use_gid) { pw->pw_gid = groups[0]; num_supp_groups++; } authenticate (pw); if (request_same_session || !command || !pw->pw_uid) { same_session = 1; } /* initialize shell variable only if "-u <user>" not specified */ if (runuser_user) { shell = NULL; } else { if (!shell && !change_environment) { shell = getenv ("SHELL"); } if (shell && getuid () != 0 && restricted_shell (pw->pw_shell)) { /* The user being su'd to has a nonstandard shell, and so is probably a uucp account or has restricted access. Don't compromise the account by allowing access with a standard shell. */ warnx (_("using restricted shell %s"), pw->pw_shell); shell = NULL; } shell = xstrdup (shell ? shell : pw->pw_shell); } init_groups (pw, groups, num_supp_groups); if (!simulate_login || command) { suppress_pam_info = 1; /* don't print PAM info messages */ } create_watching_parent (); /* Now we're in the child. */ change_identity (pw); if (!same_session) { setsid (); } /* Set environment after pam_open_session, which may put KRB5CCNAME into the pam_env, etc. */ modify_environment (pw, shell); if (simulate_login && chdir (pw->pw_dir) != 0) { warn (_("warning: cannot change directory to %s"), pw->pw_dir); } if (shell) { run_shell (shell, command, argv + optind, max (0, argc - optind)); } else { cleanup(); execvp(argv[optind], &argv[optind]); err(EXIT_FAILURE, _("failed to execute %s"), argv[optind]); } }
{"key", hit.key}, {"meta", hit.meta}, {"details", hit.details}, {"score", hit.score}}); } results.push_back(Json::object{ {"time", resp.time}, {"load_time", resp.load_time}, {"filter_time", resp.filter_time}, {"rank_time", resp.rank_time}, {"hits", hits}}); } response = Json::object{{"results", results}}; }); add_json_api("/insert", "POST", [this](Json &response, Json &request) { authenticate(request); InsertRequest req; LOAD_PARAM(request, req, db, int_value, 0); LOAD_PARAM(request, req, key, string_value, ""); LOAD_PARAM(request, req, meta, string_value, ""); LOAD_PARAM(request, req, raw, bool_value, true); LOAD_PARAM(request, req, url, string_value, ""); LOAD_PARAM(request, req, content, string_value, ""); LOAD_PARAM(request, req, type, string_value, ""); if (req.content.size()) { string hex; hex.swap(req.content); req.content = base64::decode<string>(hex); } InsertResponse resp;
int main(int argc, char **argv){ ssh_session session; ssh_bind sshbind; ssh_message message; ssh_channel chan=0; char buf[2048]; int auth=0; int shell=0; int i; int r; sshbind=ssh_bind_new(); session=ssh_new(); ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_DSAKEY, KEYS_FOLDER "ssh_host_dsa_key"); ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_RSAKEY, KEYS_FOLDER "ssh_host_rsa_key"); #ifdef HAVE_ARGP_H /* * Parse our arguments; every option seen by parse_opt will * be reflected in arguments. */ argp_parse (&argp, argc, argv, 0, 0, sshbind); #else (void) argc; (void) argv; #endif #ifdef WITH_PCAP set_pcap(session); #endif if(ssh_bind_listen(sshbind)<0){ printf("Error listening to socket: %s\n", ssh_get_error(sshbind)); return 1; } printf("Started sample libssh sshd on port %d\n", port); printf("You can login as the user %s with the password %s\n", SSHD_USER, SSHD_PASSWORD); r = ssh_bind_accept(sshbind, session); if(r==SSH_ERROR){ printf("Error accepting a connection: %s\n", ssh_get_error(sshbind)); return 1; } if (ssh_handle_key_exchange(session)) { printf("ssh_handle_key_exchange: %s\n", ssh_get_error(session)); return 1; } /* proceed to authentication */ auth = authenticate(session); if (!auth || !authenticated) { printf("Authentication error: %s\n", ssh_get_error(session)); ssh_disconnect(session); return 1; } /* wait for a channel session */ do { message = ssh_message_get(session); if(message){ if(ssh_message_type(message) == SSH_REQUEST_CHANNEL_OPEN && ssh_message_subtype(message) == SSH_CHANNEL_SESSION) { chan = ssh_message_channel_request_open_reply_accept(message); ssh_message_free(message); break; } else { ssh_message_reply_default(message); ssh_message_free(message); } } else { break; } } while(!chan); if(!chan) { printf("Error: cleint did not ask for a channel session (%s)\n", ssh_get_error(session)); ssh_finalize(); return 1; } /* wait for a shell */ do { message = ssh_message_get(session); if(message != NULL) { if(ssh_message_type(message) == SSH_REQUEST_CHANNEL && ssh_message_subtype(message) == SSH_CHANNEL_REQUEST_SHELL) { shell = 1; ssh_message_channel_request_reply_success(message); ssh_message_free(message); break; } ssh_message_reply_default(message); ssh_message_free(message); } else { break; } } while(!shell); if(!shell) { printf("Error: No shell requested (%s)\n", ssh_get_error(session)); return 1; } printf("it works !\n"); do{ i=ssh_channel_read(chan,buf, 2048, 0); if(i>0) { if(*buf == '' || *buf == '') break; if(i == 1 && *buf == '\r') ssh_channel_write(chan, "\r\n", 2); else ssh_channel_write(chan, buf, i); if (write(1,buf,i) < 0) { printf("error writing to buffer\n"); return 1; } } } while (i>0); ssh_channel_close(chan); ssh_disconnect(session); ssh_bind_free(sshbind); #ifdef WITH_PCAP cleanup_pcap(); #endif ssh_finalize(); return 0; }
static int connect_to_ssh(BDRVSSHState *s, QDict *options, int ssh_flags, int creat_mode, Error **errp) { int r, ret; QemuOpts *opts = NULL; Error *local_err = NULL; const char *user, *path, *host_key_check; long port = 0; opts = qemu_opts_create(&ssh_runtime_opts, NULL, 0, &error_abort); qemu_opts_absorb_qdict(opts, options, &local_err); if (local_err) { ret = -EINVAL; error_propagate(errp, local_err); goto err; } if (!ssh_process_legacy_socket_options(options, opts, errp)) { ret = -EINVAL; goto err; } path = qemu_opt_get(opts, "path"); if (!path) { ret = -EINVAL; error_setg(errp, "No path was specified"); goto err; } user = qemu_opt_get(opts, "user"); if (!user) { user = g_get_user_name(); if (!user) { error_setg_errno(errp, errno, "Can't get user name"); ret = -errno; goto err; } } host_key_check = qemu_opt_get(opts, "host_key_check"); if (!host_key_check) { host_key_check = "yes"; } /* Pop the config into our state object, Exit if invalid */ s->inet = ssh_config(s, options, errp); if (!s->inet) { ret = -EINVAL; goto err; } if (qemu_strtol(s->inet->port, NULL, 10, &port) < 0) { error_setg(errp, "Use only numeric port value"); ret = -EINVAL; goto err; } /* Open the socket and connect. */ s->sock = inet_connect_saddr(s->inet, errp, NULL, NULL); if (s->sock < 0) { ret = -EIO; goto err; } /* Create SSH session. */ s->session = libssh2_session_init(); if (!s->session) { ret = -EINVAL; session_error_setg(errp, s, "failed to initialize libssh2 session"); goto err; } #if TRACE_LIBSSH2 != 0 libssh2_trace(s->session, TRACE_LIBSSH2); #endif r = libssh2_session_handshake(s->session, s->sock); if (r != 0) { ret = -EINVAL; session_error_setg(errp, s, "failed to establish SSH session"); goto err; } /* Check the remote host's key against known_hosts. */ ret = check_host_key(s, s->inet->host, port, host_key_check, errp); if (ret < 0) { goto err; } /* Authenticate. */ ret = authenticate(s, user, errp); if (ret < 0) { goto err; } /* Start SFTP. */ s->sftp = libssh2_sftp_init(s->session); if (!s->sftp) { session_error_setg(errp, s, "failed to initialize sftp handle"); ret = -EINVAL; goto err; } /* Open the remote file. */ DPRINTF("opening file %s flags=0x%x creat_mode=0%o", path, ssh_flags, creat_mode); s->sftp_handle = libssh2_sftp_open(s->sftp, path, ssh_flags, creat_mode); if (!s->sftp_handle) { session_error_setg(errp, s, "failed to open remote file '%s'", path); ret = -EINVAL; goto err; } qemu_opts_del(opts); r = libssh2_sftp_fstat(s->sftp_handle, &s->attrs); if (r < 0) { sftp_error_setg(errp, s, "failed to read file attributes"); return -EINVAL; } return 0; err: if (s->sftp_handle) { libssh2_sftp_close(s->sftp_handle); } s->sftp_handle = NULL; if (s->sftp) { libssh2_sftp_shutdown(s->sftp); } s->sftp = NULL; if (s->session) { libssh2_session_disconnect(s->session, "from qemu ssh client: " "error opening connection"); libssh2_session_free(s->session); } s->session = NULL; qemu_opts_del(opts); return ret; }
void SOCKS5BytestreamClientSession::process() { SWIFT_LOG(debug) << "unprocessedData.size(): " << unprocessedData.size() << std::endl; ByteArray bndAddress; switch(state) { case Initial: hello(); break; case Hello: if (unprocessedData.size() > 1) { unsigned char version = unprocessedData[0]; unsigned char authMethod = unprocessedData[1]; if (version != 5 || authMethod != 0) { // signal failure to upper level finish(true); return; } unprocessedData.clear(); authenticate(); } break; case Authenticating: if (unprocessedData.size() < 5) { // need more data to start progressing break; } if (unprocessedData[0] != '\x05') { // wrong version // disconnect & signal failure finish(true); break; } if (unprocessedData[1] != '\x00') { // no success // disconnect & signal failure finish(true); break; } if (unprocessedData[3] != '\x03') { // we expect x'03' = DOMAINNAME here // discconect & signal failure finish(true); break; } if (static_cast<size_t>(unprocessedData[4]) + 1 > unprocessedData.size() + 5) { // complete domainname and port not available yet break; } bndAddress = createByteArray(&vecptr(unprocessedData)[5], unprocessedData[4]); if (unprocessedData[unprocessedData[4] + 5] != 0 && bndAddress == createByteArray(destination)) { // we expect a 0 as port // disconnect and fail finish(true); } unprocessedData.clear(); state = Ready; SWIFT_LOG(debug) << "session ready" << std::endl; // issue ready signal so the bytestream can be used for reading or writing weFailedTimeout->stop(); onSessionReady(false); break; case Ready: SWIFT_LOG(debug) << "Received further data in Ready state." << std::endl; break; case Reading: case Writing: case Finished: SWIFT_LOG(debug) << "Unexpected receive of data. Current state: " << state << std::endl; SWIFT_LOG(debug) << "Data: " << Hexify::hexify(unprocessedData) << std::endl; unprocessedData.clear(); //assert(false); } }
int main(int argc, char *argv[]) { const char *action = NULL; struct sigaction sa; ARGBEGIN { case 'l': case 'r': case 's': if (writefifo(fifofile, ARGC()) == -1) die("cannot write to fifo\n"); exit(EXIT_SUCCESS); default: usage(); } ARGEND; if (argc > 1) usage(); if (getuid() != 0) die("only root can run this program\n"); if (getlock(pidfile) == -1) die("cannot get exclusive lock\n"); if (createfifo(fifofile, 0666) == -1) die("cannot create fifo\n"); sa.sa_flags = SA_NOCLDSTOP; sa.sa_handler = catchsignal; sigemptyset(&sa.sa_mask); sigaction(SIGCHLD, &sa, NULL); signal(SIGINT, catchsignal); signal(SIGHUP, catchsignal); signal(SIGQUIT, catchsignal); signal(SIGTERM, catchsignal); signal(SIGKILL, catchsignal); signal(SIGPIPE, catchsignal); startserver(server, display); do { const char *user, *pass; char c; if (autologin && authenticate(autologin, NULL)) { autologin = NULL; goto login; } creategui(); do { rungui(&user, &pass); if (!strcmp(user, "reboot")) action = rebootcmd; else if (!strcmp(user, "shutdown")) action = shutdowncmd; } while (!action && !authenticate(user, pass)); destroygui(); if (action) break; login: childpid = startsession(child, env); c = readfifo(fifofile); if (c == 'r') action = rebootcmd; else if (c == 's') action = shutdowncmd; else if (!c) while (childpid) sleep(10); stopsession(); } while (!action); signal(SIGINT, SIG_IGN); signal(SIGHUP, SIG_IGN); signal(SIGQUIT, SIG_IGN); signal(SIGTERM, SIG_DFL); signal(SIGKILL, SIG_DFL); signal(SIGCHLD, SIG_DFL); signal(SIGPIPE, SIG_IGN); stopserver(); removefifo(fifofile); removelock(pidfile); return system(action); }
int main(int argc, char **argv) { int only_root, auth = 0, chpid; uid_t uid; userinfo_t *as, root, user; oldvt = oldsysrq = vt.nr = vt.fd = -1; vt.ios = NULL; root.name = "root"; parse_options(argc, argv); if (geteuid() != 0) { fprintf(stderr, "physlock: must be root!\n"); return 1; } setup_signal(SIGTERM, sa_handler_exit); setup_signal(SIGQUIT, sa_handler_exit); setup_signal(SIGHUP, SIG_IGN); setup_signal(SIGINT, SIG_IGN); setup_signal(SIGUSR1, SIG_IGN); setup_signal(SIGUSR2, SIG_IGN); vt_init(); get_current_vt(&oldvt); if (options->only_lock) { lock_vt_switch(); vt_destroy(); return 0; } else if (options->only_unlock) { unlock_vt_switch(); vt_destroy(); return 0; } if (options->disable_sysrq) { oldsysrq = get_sysrq_state(SYSRQ_PATH); if (oldsysrq > 0) set_sysrq_state(SYSRQ_PATH, 0); } if (options->user) { user.name = options->user; } else { uid = getuid(); get_uname(&user, uid); } get_pwhash(&root); only_root = strcmp(user.name, root.name) == 0; if (!only_root) { get_pwhash(&user); authenticate(&user, ""); /* test authentication */ } acquire_new_vt(&vt); lock_vt_switch(); secure_vt(&vt); if (options->detach) { chpid = fork(); if (chpid < 0) die("could not spawn background process: %s", strerror(errno)); else if (chpid > 0) return 0; else setsid(); } if (options->cmd) handle_cmd(1); while (!auth) { as = &root; flush_vt(&vt); if (!only_root) { tty_echo_on(&vt); while (1) { prompt(vt.ios, "\nUnlock as [%s/%s]: ", user.name, root.name); if (!*buf || !strcmp(buf, user.name)) { as = &user; break; } else if (!strcmp(buf, root.name)) { break; } } tty_echo_off(&vt); } else { prompt(vt.ios, "\nPress [Enter] to unlock.\n"); } prompt(vt.ios, "%s's password: "******"\nAuthentication failed\n"); sleep(AUTH_FAIL_TIMEOUT); } } if (options->crypt) add_passphrase(buf, options->fnek, vt.ios); if (options->cmd) handle_cmd(0); sleep(1); cleanup(); return 0; }
int main(void) { int retcode; unsigned int count; fileHandleType fh; int useraccount; void *message; int messagetype; newUserMessageType *newuser; loginMessageType *loginuser; newPostMessageType *newPost; addCommentMessageType *newComment; unsigned int postID; int responseCode; unsigned int nextPostID = 100; unsigned int sessionToken; char *postText; int postSize; int endIt; // using a small blocksize of 256 bytes because postings are small and this is more efficient retcode = initFileSystem(512, 512, 512*2000); securityIDFileHandle = -1; if (retcode != 0) { printf("Error making filesystem.\n"); _terminate(-1); } retcode = makeMemoryFile("sticky.posts", 0x4347C000 + 1536, 160*16, 1, ROOT_ID ); if ( retcode != 0 ) { printf("Error making posts.log\n"); _terminate(-1); } retcode = makeMemoryFile("initialPostID.mem", 0x4347C000, 4, 1, ROOT_ID ); if ( retcode != 0 ) { printf("Error making posts.log\n"); _terminate(-1); } retcode = createFile("Users.db", REGULAR, ROOT_ID); if ( retcode != 0 ) { printf("Error making Users.db\n"); _terminate(-1); } retcode = createFile("posts.log", REGULAR, ROOT_ID); if ( retcode != 0 ) { printf("Error making posts.log\n"); _terminate(-1); } // seed the first postID with magic page data. After this they just increase by 1 each time fh = openFile("initialPostID.mem", ROOT_ID); if ( fh < 0 ) { printf("Error opening initialPostID.mem\n"); _terminate(-1); } readFile(fh, (void *)&nextPostID, sizeof(nextPostID), 0, 0, ROOT_ID); nextPostID &= 0x0fffffff; // we'll never re-seed the postID so just delete the file deleteFile(fh, ROOT_ID); // this file will allow us to get semi-random userID's from the magic page. It is kept open and a new ID is // read whenever a new account is created retcode = makeMemoryFile("UserIDs.mem", 0x4347C004, 1532, 1, ROOT_ID ); if ( retcode != 0 ) { printf("Error making UserIDs.mem\n"); _terminate(-1); } retcode = allocate(1024, 0, &message); if (retcode != 0) { _terminate(-1); } endIt = 0; while (!endIt) { messagetype = receiveMessage(message); switch (messagetype) { // add a new user case 0xa0: newuser = (newUserMessageType *)message; if (create_user(newuser->name, newuser->password, newuser->fullname) >= 0 ) { responseCode = 0; } else { responseCode = -1; } sendResponse((void *)&responseCode, sizeof(responseCode)); break; // authenticate a user case 0xb0: loginuser = (loginMessageType *)message; useraccount = authenticate(loginuser->name, loginuser->password); sendResponse((void *)&useraccount, sizeof(useraccount)); break; // retrieve a single post to this user's feed case 0xc0: sessionToken = *(unsigned int *)message; retcode = newFeedPost(sessionToken, &postText, &postSize); if (retcode == 0 ) { sendResponse((void *)postText, postSize); deallocate((void *)postText, postSize); } else { retcode = -1; sendResponse((void *)&retcode, sizeof(retcode)); } break; // record a new post from the user case 0xd0: newPost = (newPostMessageType *)message; retcode = savePost(nextPostID, newPost->sessionToken, newPost->post); if (retcode == 0) { retcode = nextPostID; ++nextPostID; } else { retcode = -1; } sendResponse((void *)&retcode, sizeof(retcode)); break; // comment on a post case 0xe0: newComment = (addCommentMessageType *)message; retcode = saveComment(newComment->postID, newComment->commenterID, newComment->comment); sendResponse((void *)&retcode, sizeof(retcode)); break; // retrieve a specific post by its ID--this will include any comments as well case 0xf0: postID = *(unsigned int *)message; if ( postID < 16 ) { retcode = sendStickPost( postID ); } else { retcode = retrievePost( postID, 1 , &postText, &postSize); if (retcode == 0) { sendResponse((void *)postText, postSize); deallocate((void *)postText, postSize); } } if ( retcode == -1 ) { sendResponse((void *)&retcode, sizeof(retcode)); } // response sent by the retrievePost() function break; case 100: endIt = 1; break; default: endIt = 1; break; } //switch } // while (1) printf("BYE!\n"); } // main
bool CmdAuthenticate::run(const string& dbname , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool fromRepl) { if (!_areNonceAuthenticateCommandsEnabled) { errmsg = _nonceAuthenticateCommandsDisabledMessage; return false; } log() << " authenticate db: " << dbname << " " << cmdObj << endl; string user = cmdObj.getStringField("user"); string key = cmdObj.getStringField("key"); string received_nonce = cmdObj.getStringField("nonce"); if( user.empty() || key.empty() || received_nonce.empty() ) { log() << "field missing/wrong type in received authenticate command " << dbname << endl; errmsg = "auth fails"; sleepmillis(10); return false; } stringstream digestBuilder; { bool reject = false; ClientBasic *client = ClientBasic::getCurrent(); AuthenticationSession *session = client->getAuthenticationSession(); if (!session || session->getType() != AuthenticationSession::SESSION_TYPE_MONGO) { reject = true; LOG(1) << "auth: No pending nonce" << endl; } else { nonce64 nonce = static_cast<MongoAuthenticationSession*>(session)->getNonce(); digestBuilder << hex << nonce; reject = digestBuilder.str() != received_nonce; if ( reject ) { LOG(1) << "auth: Authentication failed for " << dbname << '$' << user << endl; } } client->resetAuthenticationSession(NULL); if ( reject ) { log() << "auth: bad nonce received or getnonce not called. could be a driver bug or a security attack. db:" << dbname << endl; errmsg = "auth fails"; sleepmillis(30); return false; } } BSONObj userObj; string pwd; Status status = ClientBasic::getCurrent()->getAuthorizationManager()->getPrivilegeDocument( dbname, user, &userObj); if (!status.isOK()) { log() << status.reason() << std::endl; errmsg = status.reason(); return false; } pwd = userObj["pwd"].String(); md5digest d; { digestBuilder << user << pwd; string done = digestBuilder.str(); md5_state_t st; md5_init(&st); md5_append(&st, (const md5_byte_t *) done.c_str(), done.size()); md5_finish(&st, d); } string computed = digestToString( d ); if ( key != computed ) { log() << "auth: key mismatch " << user << ", ns:" << dbname << endl; errmsg = "auth fails"; return false; } status = authenticateAndAuthorizePrincipal(user, dbname, userObj); uassert(16500, mongoutils::str::stream() << "Problem acquiring privileges for principal \"" << user << "\": " << status.reason(), status == Status::OK()); bool readOnly = userObj["readOnly"].trueValue(); // TODO: remove this once all auth checking goes through AuthorizationManager instead of // AuthenticationInfo authenticate(dbname, user, readOnly ); result.append( "dbname" , dbname ); result.append( "user" , user ); result.appendBool( "readOnly" , readOnly ); return true; }