static ssize_t bpp_read(struct file *f, char *c, size_t cnt, loff_t * ppos) { long rc; const unsigned minor = MINOR(f->f_dentry->d_inode->i_rdev); if (minor >= BPP_NO) return -ENODEV; if (!instances[minor].present) return -ENODEV; switch (instances[minor].mode) { default: if (instances[minor].mode != COMPATIBILITY) terminate(minor); if (instances[minor].enhanced) { /* For now, do all reads with ECP-RLE mode */ unsigned short pins; rc = negotiate(DEFAULT_ECP, minor); if (rc < 0) break; instances[minor].mode = ECP_RLE; /* Event 30: set nAutoFd low to setup for ECP mode */ pins = get_pins(minor); pins &= ~BPP_PP_nAutoFd; set_pins(pins, minor); /* Wait for Event 31: peripheral ready */ rc = wait_for(BPP_GP_PError, 0, TIME_PResponse, minor); if (rc == -1) return -ETIMEDOUT; rc = read_ecp(minor, c, cnt); } else { rc = negotiate(DEFAULT_NIBBLE, minor); if (rc < 0) break; instances[minor].mode = NIBBLE; rc = read_nibble(minor, c, cnt); } break; case NIBBLE: rc = read_nibble(minor, c, cnt); break; case ECP: case ECP_RLE: rc = read_ecp(minor, c, cnt); break; } return rc; }
static int do_client(CLI *c) { int result; if(init_local(c)) return -1; if(!options.option.client && !c->opt->protocol) { /* Server mode and no protocol negotiation needed */ if(init_ssl(c)) return -1; if(init_remote(c)) return -1; } else { if(init_remote(c)) return -1; if(negotiate(c)<0) { s_log(LOG_ERR, "Protocol negotiations failed"); return -1; } if(init_ssl(c)) return -1; } result=transfer(c); s_log(LOG_NOTICE, "Connection %s: %d bytes sent to SSL, %d bytes sent to socket", result ? "reset" : "closed", c->ssl_bytes, c->sock_bytes); return result; }
int smb_session_login_spnego(smb_session *s, const char *domain, const char *user, const char *password) { int res; assert(s != NULL && domain != NULL && user != NULL && password != NULL); // Clear User ID that might exists from previous authentication attempt s->srv.uid = 0; if (init_asn1(s) != DSM_SUCCESS) return DSM_ERROR_GENERIC; if ((res = negotiate(s, domain)) != DSM_SUCCESS) goto error; if ((res = challenge(s)) != DSM_SUCCESS) goto error; res = auth(s, domain, user, password); clean_asn1(s); return res; error: BDSM_dbg("login_spnego Interrupted\n"); clean_asn1(s); return res; }
void checkNegotiation( const char *host1, const char *arb1, int state1, int newState1, const char *host2, const char *arb2, int state2, int newState2 ) { ReplPair one( host1, arb1 ); one.state = state1; ReplPair two( host2, arb2 ); two.state = state2; negotiate( one, two ); ASSERT( one.state == newState1 ); ASSERT( two.state == newState2 ); }
static void do_client(CLI *c) { init_local(c); if(!c->opt->option.client && !c->opt->protocol) { /* server mode and no protocol negotiation needed */ init_ssl(c); init_remote(c); } else { init_remote(c); negotiate(c); init_ssl(c); } transfer(c); }
int AmSession::acceptAudio(const string& body, const string& hdrs, string* sdp_reply) { try { try { // handle codec and send reply string str_msg_flags = getHeader(hdrs,"P-MsgFlags"); unsigned int msg_flags = 0; if(reverse_hex2int(str_msg_flags,msg_flags)){ ERROR("while parsing 'P-MsgFlags' header\n"); msg_flags = 0; } negotiate( body, msg_flags & FL_FORCE_ACTIVE, sdp_reply); // enable RTP stream lockAudio(); rtp_str.init(&payload); unlockAudio(); DBG("Sending Rtp data to %s/%i\n", rtp_str.getRHost().c_str(),rtp_str.getRPort()); return 0; } catch(const AmSession::Exception& e){ throw e; } catch(const string& str){ ERROR("%s\n",str.c_str()); throw AmSession::Exception(500,str); } catch(...){ throw AmSession::Exception(500,"unexpected exception."); } } catch(const AmSession::Exception& e){ ERROR("%i %s\n",e.code,e.reason.c_str()); throw; // if(dlg.reply(req,e.code,e.reason, "")){ // dlg.bye(); // } // setStopped(); } return -1; }
bool SSLConnection::doOpen() { if (!did_init) return false; ctx = SSL_CTX_new (SSLv23_client_method ()); /* disable SSL protocols as needed */ if (!UseTLS1) { SSL_CTX_set_options (ctx, SSL_OP_NO_TLSv1); } if (!UseSSL3) { SSL_CTX_set_options (ctx, SSL_OP_NO_SSLv3); } if (!UseTLS1 && !UseSSL3) return false; getClientCert (); ssl = SSL_new (ctx); SSL_set_fd (ssl,fd); if (!negotiate ()) return false; int maxbits; ssf = SSL_CIPHER_get_bits (SSL_get_current_cipher (ssl),&maxbits); buffer_t msg; buffer_init(&msg); buffer_add_str(&msg,_("SSL/TLS connection using "),-1); buffer_add_str(&msg,SSL_get_cipher_version(ssl),-1); buffer_add_str(&msg," (",2); buffer_add_str(&msg,SSL_get_cipher_name(ssl),-1); buffer_add_ch(&msg,')'); displayProgress.emit(&msg); buffer_free(&msg); return true; }
void respond(int sd,char *expstr) { char buf[1024]; int x; fd_set rset; printf("[*] negotiating\n"); negotiate(sd); printf("[*] sending exploit string\n"); write(sd,expstr,strlen(expstr)); printf("[*] did it work? now press enter\n"); fflush(stdout); FD_ZERO(&rset); while (1) { FD_SET(sd,&rset); FD_SET(0,&rset); select(sd+1,&rset,0,0,0); if (FD_ISSET(sd,&rset)) { memset(buf,'\0',sizeof(buf)); if ((x = read(sd,buf,sizeof(buf)-1)) == 0) { printf("Connection closed by foreign host.\n"); exit(-1); } fprintf(stderr,"%s",buf); } if (FD_ISSET(0,&rset)) { memset(buf,'\0',sizeof(buf)); if ((x = read(0,buf,sizeof(buf)-1)) > 0) { write(sd,buf,x); } } } }
static CURLcode telnet_do(struct connectdata *conn, bool *done) { CURLcode result; struct SessionHandle *data = conn->data; curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; #ifdef USE_WINSOCK HMODULE wsock2; WSOCK2_FUNC close_event_func; WSOCK2_FUNC create_event_func; WSOCK2_FUNC event_select_func; WSOCK2_FUNC enum_netevents_func; WSAEVENT event_handle; WSANETWORKEVENTS events; HANDLE stdin_handle; HANDLE objs[2]; DWORD obj_count; DWORD wait_timeout; DWORD waitret; DWORD readfile_read; int err; #else int interval_ms; struct pollfd pfd[2]; int poll_cnt; curl_off_t total_dl = 0; curl_off_t total_ul = 0; #endif ssize_t nread; struct timeval now; bool keepon = TRUE; char *buf = data->state.buffer; struct TELNET *tn; *done = TRUE; /* unconditionally */ result = init_telnet(conn); if(result) return result; tn = (struct TELNET *)data->req.protop; result = check_telnet_options(conn); if(result) return result; #ifdef USE_WINSOCK /* ** This functionality only works with WinSock >= 2.0. So, ** make sure have it. */ result = check_wsock2(data); if(result) return result; /* OK, so we have WinSock 2.0. We need to dynamically */ /* load ws2_32.dll and get the function pointers we need. */ wsock2 = LoadLibrary(TEXT("WS2_32.DLL")); if(wsock2 == NULL) { failf(data, "failed to load WS2_32.DLL (%d)", ERRNO); return CURLE_FAILED_INIT; } /* Grab a pointer to WSACreateEvent */ create_event_func = GetProcAddress(wsock2, "WSACreateEvent"); if(create_event_func == NULL) { failf(data, "failed to find WSACreateEvent function (%d)", ERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSACloseEvent */ close_event_func = GetProcAddress(wsock2, "WSACloseEvent"); if(close_event_func == NULL) { failf(data, "failed to find WSACloseEvent function (%d)", ERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSAEventSelect */ event_select_func = GetProcAddress(wsock2, "WSAEventSelect"); if(event_select_func == NULL) { failf(data, "failed to find WSAEventSelect function (%d)", ERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSAEnumNetworkEvents */ enum_netevents_func = GetProcAddress(wsock2, "WSAEnumNetworkEvents"); if(enum_netevents_func == NULL) { failf(data, "failed to find WSAEnumNetworkEvents function (%d)", ERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* We want to wait for both stdin and the socket. Since ** the select() function in winsock only works on sockets ** we have to use the WaitForMultipleObjects() call. */ /* First, create a sockets event object */ event_handle = (WSAEVENT)create_event_func(); if(event_handle == WSA_INVALID_EVENT) { failf(data, "WSACreateEvent failed (%d)", SOCKERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* Tell winsock what events we want to listen to */ if(event_select_func(sockfd, event_handle, FD_READ|FD_CLOSE) == SOCKET_ERROR) { close_event_func(event_handle); FreeLibrary(wsock2); return CURLE_OK; } /* The get the Windows file handle for stdin */ stdin_handle = GetStdHandle(STD_INPUT_HANDLE); /* Create the list of objects to wait for */ objs[0] = event_handle; objs[1] = stdin_handle; /* If stdin_handle is a pipe, use PeekNamedPipe() method to check it, else use the old WaitForMultipleObjects() way */ if(GetFileType(stdin_handle) == FILE_TYPE_PIPE || data->set.is_fread_set) { /* Don't wait for stdin_handle, just wait for event_handle */ obj_count = 1; /* Check stdin_handle per 100 milliseconds */ wait_timeout = 100; } else { obj_count = 2; wait_timeout = 1000; } /* Keep on listening and act on events */ while(keepon) { waitret = WaitForMultipleObjects(obj_count, objs, FALSE, wait_timeout); switch(waitret) { case WAIT_TIMEOUT: { for(;;) { if(data->set.is_fread_set) { /* read from user-supplied method */ result = (int)data->state.fread_func(buf, 1, BUFSIZE - 1, data->state.in); if(result == CURL_READFUNC_ABORT) { keepon = FALSE; result = CURLE_READ_ERROR; break; } if(result == CURL_READFUNC_PAUSE) break; if(result == 0) /* no bytes */ break; readfile_read = result; /* fall thru with number of bytes read */ } else { /* read from stdin */ if(!PeekNamedPipe(stdin_handle, NULL, 0, NULL, &readfile_read, NULL)) { keepon = FALSE; result = CURLE_READ_ERROR; break; } if(!readfile_read) break; if(!ReadFile(stdin_handle, buf, sizeof(data->state.buffer), &readfile_read, NULL)) { keepon = FALSE; result = CURLE_READ_ERROR; break; } } result = send_telnet_data(conn, buf, readfile_read); if(result) { keepon = FALSE; break; } } } break; case WAIT_OBJECT_0 + 1: { if(!ReadFile(stdin_handle, buf, sizeof(data->state.buffer), &readfile_read, NULL)) { keepon = FALSE; result = CURLE_READ_ERROR; break; } result = send_telnet_data(conn, buf, readfile_read); if(result) { keepon = FALSE; break; } } break; case WAIT_OBJECT_0: events.lNetworkEvents = 0; if(SOCKET_ERROR == enum_netevents_func(sockfd, event_handle, &events)) { if((err = SOCKERRNO) != EINPROGRESS) { infof(data, "WSAEnumNetworkEvents failed (%d)", err); keepon = FALSE; result = CURLE_READ_ERROR; } break; } if(events.lNetworkEvents & FD_READ) { /* read data from network */ result = Curl_read(conn, sockfd, buf, BUFSIZE - 1, &nread); /* read would've blocked. Loop again */ if(result == CURLE_AGAIN) break; /* returned not-zero, this an error */ else if(result) { keepon = FALSE; break; } /* returned zero but actually received 0 or less here, the server closed the connection and we bail out */ else if(nread <= 0) { keepon = FALSE; break; } result = telrcv(conn, (unsigned char *) buf, nread); if(result) { keepon = FALSE; break; } /* Negotiate if the peer has started negotiating, otherwise don't. We don't want to speak telnet with non-telnet servers, like POP or SMTP. */ if(tn->please_negotiate && !tn->already_negotiated) { negotiate(conn); tn->already_negotiated = 1; } } if(events.lNetworkEvents & FD_CLOSE) { keepon = FALSE; } break; } if(data->set.timeout) { now = Curl_tvnow(); if(Curl_tvdiff(now, conn->created) >= data->set.timeout) { failf(data, "Time-out"); result = CURLE_OPERATION_TIMEDOUT; keepon = FALSE; } } } /* We called WSACreateEvent, so call WSACloseEvent */ if(!close_event_func(event_handle)) { infof(data, "WSACloseEvent failed (%d)", SOCKERRNO); } /* "Forget" pointers into the library we're about to free */ create_event_func = NULL; close_event_func = NULL; event_select_func = NULL; enum_netevents_func = NULL; /* We called LoadLibrary, so call FreeLibrary */ if(!FreeLibrary(wsock2)) infof(data, "FreeLibrary(wsock2) failed (%d)", ERRNO); #else pfd[0].fd = sockfd; pfd[0].events = POLLIN; if(data->set.is_fread_set) { poll_cnt = 1; interval_ms = 100; /* poll user-supplied read function */ } else { /* really using fread, so infile is a FILE* */ pfd[1].fd = fileno((FILE *)data->state.in); pfd[1].events = POLLIN; poll_cnt = 2; interval_ms = 1 * 1000; } while(keepon) { switch (Curl_poll(pfd, poll_cnt, interval_ms)) { case -1: /* error, stop reading */ keepon = FALSE; continue; case 0: /* timeout */ pfd[0].revents = 0; pfd[1].revents = 0; /* fall through */ default: /* read! */ if(pfd[0].revents & POLLIN) { /* read data from network */ result = Curl_read(conn, sockfd, buf, BUFSIZE - 1, &nread); /* read would've blocked. Loop again */ if(result == CURLE_AGAIN) break; /* returned not-zero, this an error */ else if(result) { keepon = FALSE; break; } /* returned zero but actually received 0 or less here, the server closed the connection and we bail out */ else if(nread <= 0) { keepon = FALSE; break; } total_dl += nread; Curl_pgrsSetDownloadCounter(data, total_dl); result = telrcv(conn, (unsigned char *)buf, nread); if(result) { keepon = FALSE; break; } /* Negotiate if the peer has started negotiating, otherwise don't. We don't want to speak telnet with non-telnet servers, like POP or SMTP. */ if(tn->please_negotiate && !tn->already_negotiated) { negotiate(conn); tn->already_negotiated = 1; } } nread = 0; if(poll_cnt == 2) { if(pfd[1].revents & POLLIN) { /* read from in file */ nread = read(pfd[1].fd, buf, BUFSIZE - 1); } } else { /* read from user-supplied method */ nread = (int)data->state.fread_func(buf, 1, BUFSIZE - 1, data->state.in); if(nread == CURL_READFUNC_ABORT) { keepon = FALSE; break; } if(nread == CURL_READFUNC_PAUSE) break; } if(nread > 0) { result = send_telnet_data(conn, buf, nread); if(result) { keepon = FALSE; break; } total_ul += nread; Curl_pgrsSetUploadCounter(data, total_ul); } else if(nread < 0) keepon = FALSE; break; } /* poll switch statement */ if(data->set.timeout) { now = Curl_tvnow(); if(Curl_tvdiff(now, conn->created) >= data->set.timeout) { failf(data, "Time-out"); result = CURLE_OPERATION_TIMEDOUT; keepon = FALSE; } } if(Curl_pgrsUpdate(conn)) { result = CURLE_ABORTED_BY_CALLBACK; break; } } #endif /* mark this as "no further transfer wanted" */ Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL); return result; }
CURLcode Curl_telnet(struct connectdata *conn) { CURLcode code; struct SessionHandle *data = conn->data; curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; #if defined(WIN32) || defined(WIN64) HMODULE wsock2; WSOCK2_FUNC close_event_func; WSOCK2_FUNC create_event_func; WSOCK2_FUNC event_select_func; WSOCK2_FUNC enum_netevents_func; WSAEVENT event_handle; WSANETWORKEVENTS events; HANDLE stdin_handle; HANDLE objs[2]; DWORD waitret; DWORD readfile_read; #else fd_set readfd; fd_set keepfd; #endif ssize_t nread; bool keepon = TRUE; char *buf = data->state.buffer; struct TELNET *tn; code = init_telnet(conn); if(code) return code; tn = (struct TELNET *)conn->proto.telnet; code = check_telnet_options(conn); if(code) return code; #if defined(WIN32) || defined(WIN64) /* ** This functionality only works with WinSock >= 2.0. So, ** make sure have it. */ code = check_wsock2(data); if (code) return code; /* OK, so we have WinSock 2.0. We need to dynamically */ /* load ws2_32.dll and get the function pointers we need. */ wsock2 = LoadLibrary("WS2_32.DLL"); if (wsock2 == NULL) { failf(data,"failed to load WS2_32.DLL (%d)",GetLastError()); return CURLE_FAILED_INIT; } /* Grab a pointer to WSACreateEvent */ create_event_func = GetProcAddress(wsock2,"WSACreateEvent"); if (create_event_func == NULL) { failf(data,"failed to find WSACreateEvent function (%d)", GetLastError()); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSACloseEvent */ close_event_func = GetProcAddress(wsock2,"WSACloseEvent"); if (create_event_func == NULL) { failf(data,"failed to find WSACloseEvent function (%d)", GetLastError()); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSAEventSelect */ event_select_func = GetProcAddress(wsock2,"WSAEventSelect"); if (event_select_func == NULL) { failf(data,"failed to find WSAEventSelect function (%d)", GetLastError()); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSAEnumNetworkEvents */ enum_netevents_func = GetProcAddress(wsock2,"WSAEnumNetworkEvents"); if (enum_netevents_func == NULL) { failf(data,"failed to find WSAEnumNetworkEvents function (%d)", GetLastError()); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* We want to wait for both stdin and the socket. Since ** the select() function in winsock only works on sockets ** we have to use the WaitForMultipleObjects() call. */ /* First, create a sockets event object */ event_handle = (WSAEVENT)create_event_func(); if (event_handle == WSA_INVALID_EVENT) { failf(data,"WSACreateEvent failed (%d)",WSAGetLastError()); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* The get the Windows file handle for stdin */ stdin_handle = GetStdHandle(STD_INPUT_HANDLE); /* Create the list of objects to wait for */ objs[0] = stdin_handle; objs[1] = event_handle; /* Tell winsock what events we want to listen to */ if(event_select_func(sockfd, event_handle, FD_READ|FD_CLOSE) == SOCKET_ERROR) { close_event_func(event_handle); FreeLibrary(wsock2); return 0; } /* Keep on listening and act on events */ while(keepon) { waitret = WaitForMultipleObjects(2, objs, FALSE, INFINITE); switch(waitret - WAIT_OBJECT_0) { case 0: { unsigned char outbuf[2]; int out_count = 0; ssize_t bytes_written; char *buffer = buf; if(!ReadFile(stdin_handle, buf, sizeof(data->state.buffer), &readfile_read, NULL)) { keepon = FALSE; break; } nread = readfile_read; while(nread--) { outbuf[0] = *buffer++; out_count = 1; if(outbuf[0] == CURL_IAC) outbuf[out_count++] = CURL_IAC; Curl_write(conn, conn->sock[FIRSTSOCKET], outbuf, out_count, &bytes_written); } } break; case 1: if(enum_netevents_func(sockfd, event_handle, &events) != SOCKET_ERROR) { if(events.lNetworkEvents & FD_READ) { /* This reallu OUGHT to check its return code. */ (void)Curl_read(conn, sockfd, buf, BUFSIZE - 1, &nread); telrcv(conn, (unsigned char *)buf, nread); fflush(stdout); /* Negotiate if the peer has started negotiating, otherwise don't. We don't want to speak telnet with non-telnet servers, like POP or SMTP. */ if(tn->please_negotiate && !tn->already_negotiated) { negotiate(conn); tn->already_negotiated = 1; } } if(events.lNetworkEvents & FD_CLOSE) { keepon = FALSE; } } break; } } /* We called WSACreateEvent, so call WSACloseEvent */ if (close_event_func(event_handle) == FALSE) { infof(data,"WSACloseEvent failed (%d)",WSAGetLastError()); } /* "Forget" pointers into the library we're about to free */ create_event_func = NULL; close_event_func = NULL; event_select_func = NULL; enum_netevents_func = NULL; /* We called LoadLibrary, so call FreeLibrary */ if (!FreeLibrary(wsock2)) infof(data,"FreeLibrary(wsock2) failed (%d)",GetLastError()); #else FD_ZERO (&readfd); /* clear it */ FD_SET (sockfd, &readfd); FD_SET (0, &readfd); keepfd = readfd; while (keepon) { struct timeval interval; readfd = keepfd; /* set this every lap in the loop */ interval.tv_sec = 1; interval.tv_usec = 0; switch (select (sockfd + 1, &readfd, NULL, NULL, &interval)) { case -1: /* error, stop reading */ keepon = FALSE; continue; case 0: /* timeout */ break; default: /* read! */ if(FD_ISSET(0, &readfd)) { /* read from stdin */ unsigned char outbuf[2]; int out_count = 0; ssize_t bytes_written; char *buffer = buf; nread = read(0, buf, 255); while(nread--) { outbuf[0] = *buffer++; out_count = 1; if(outbuf[0] == CURL_IAC) outbuf[out_count++] = CURL_IAC; Curl_write(conn, conn->sock[FIRSTSOCKET], outbuf, out_count, &bytes_written); } } if(FD_ISSET(sockfd, &readfd)) { /* This OUGHT to check the return code... */ (void)Curl_read(conn, sockfd, buf, BUFSIZE - 1, &nread); /* if we receive 0 or less here, the server closed the connection and we bail out from this! */ if (nread <= 0) { keepon = FALSE; break; } telrcv(conn, (unsigned char *)buf, nread); /* Negotiate if the peer has started negotiating, otherwise don't. We don't want to speak telnet with non-telnet servers, like POP or SMTP. */ if(tn->please_negotiate && !tn->already_negotiated) { negotiate(conn); tn->already_negotiated = 1; } } } if(data->set.timeout) { struct timeval now; /* current time */ now = Curl_tvnow(); if(Curl_tvdiff(now, conn->created)/1000 >= data->set.timeout) { failf(data, "Time-out"); code = CURLE_OPERATION_TIMEOUTED; keepon = FALSE; } } } #endif /* mark this as "no further transfer wanted" */ Curl_Transfer(conn, -1, -1, FALSE, NULL, -1, NULL); return code; }
void mapd_client_recv(const struct icmp6_hdr *ih, ssize_t len, const struct in6_addr *saddr, const struct in6_addr *daddr, int iif, int hoplimit, int sock_fd) { // struct md_inet6_iface *iface; if(ih->icmp6_type == ND_ROUTER_ADVERT) { struct nd_router_advert *ra = (struct nd_router_advert *)ih; int optlen = len - sizeof(struct nd_router_advert); uint8_t *opt = (uint8_t *)(ra + 1); // printf("Message Is A RA\n"); while (optlen > 1) { int olen = opt[1] << 3; if (olen > optlen || olen == 0) return; switch (opt[0]) { case 62: { // uint8_t type = opt[0]; // uint8_t len = opt[1]; uint8_t no_maps = opt[2]; int i = 0; struct np_map *npm = malloc(no_maps * sizeof(struct np_map)); printf("RA Received With %d Mappings\n", no_maps); int off = 3; opt += off; for(i = 0; i < no_maps; i++) { memcpy(&npm[i], opt, sizeof(struct np_map)); // printf("Mapping = %d\nprio = %d\n", npm[i].mapping, npm[i].prio); off+=sizeof(struct np_map); opt+=sizeof(struct np_map); } negotiate(npm, no_maps, saddr, daddr, iif, sock_fd); free(npm); break; } } optlen -= olen; opt += olen; } return; } else if(ih->icmp6_type == ND_NEIGHBOR_SOLICIT) { struct nd_neighbor_solicit *ns = (struct nd_neighbor_solicit *)ih; int optlen = len - sizeof(struct nd_neighbor_solicit); uint8_t *opt = (uint8_t *)(ns + 1); // printf("Message Is A NS\n"); while (optlen > 1) { int olen = opt[1] << 3; if (olen > optlen || olen == 0) return; switch (opt[0]) { case 62: { // uint8_t type = opt[0]; // uint8_t len = opt[1]; uint8_t no_maps = opt[2]; int i = 0; struct np_map *npm = malloc(no_maps * sizeof(struct np_map)); printf("NS Received With %d Mappings\n", no_maps); int off = 3; opt += off; for(i = 0; i < no_maps; i++) { memcpy(&npm[i], opt, sizeof(struct np_map)); // printf("Mapping = %d\nprio = %d\n", npm[i].mapping, npm[i].prio); off+=sizeof(struct np_map); opt+=sizeof(struct np_map); } negotiate(npm, no_maps, saddr, daddr, iif, sock_fd); free(npm); break; } } optlen -= olen; opt += olen; } } }
void ConnectionSOCKS5Proxy::handleReceivedData( const ConnectionBase* /*connection*/, const std::string& data ) { // if( m_s5state != S5StateConnected ) // { // printf( "data recv: " ); // const char* x = data.c_str(); // for( unsigned int i = 0; i < data.length(); ++i ) // printf( "%02X ", (const char)x[i] ); // printf( "\n" ); // } if( !m_connection || !m_handler ) return; switch( m_s5state ) { case S5StateConnecting: if( data.length() != 2 || data[0] != 0x05 ) { m_connection->disconnect(); m_handler->handleDisconnect( this, ConnIoError ); } if( data[1] == 0x00 ) // no auth { negotiate(); } else if( data[1] == 0x02 && !m_proxyUser.empty() && !m_proxyPassword.empty() ) // user/password auth { m_logInstance.log( LogLevelDebug, LogAreaClassConnectionSOCKS5Proxy, "authenticating to socks5 proxy as user " + m_proxyUser ); m_s5state = S5StateAuthenticating; char* d = new char[3 + m_proxyUser.length() + m_proxyPassword.length()]; int pos = 0; d[pos++] = 0x01; d[pos++] = m_proxyUser.length(); strncpy( d + pos, m_proxyUser.c_str(), m_proxyUser.length() ); pos += m_proxyUser.length(); d[pos++] = m_proxyPassword.length(); strncpy( d + pos, m_proxyPassword.c_str(), m_proxyPassword.length() ); pos += m_proxyPassword.length(); if( !send( std::string( d, pos ) ) ) { cleanup(); m_handler->handleDisconnect( this, ConnIoError ); } delete[] d; } else if( data[1] == (char)0xFF && !m_proxyUser.empty() && !m_proxyPassword.empty() ) { m_connection->disconnect(); m_handler->handleDisconnect( this, ConnProxyNoSupportedAuth ); } else if( data[1] == (char)0xFF && ( m_proxyUser.empty() || m_proxyPassword.empty() ) ) { m_connection->disconnect(); m_handler->handleDisconnect( this, ConnProxyAuthRequired ); } else { m_connection->disconnect(); m_handler->handleDisconnect( this, ConnProxyAuthRequired ); } break; case S5StateNegotiating: if( data.length() >= 6 && data[0] == 0x05 ) { if( data[1] == 0x00 ) { m_state = StateConnected; m_s5state = S5StateConnected; m_handler->handleConnect( this ); } else // connection refused { m_connection->disconnect(); m_handler->handleDisconnect( this, ConnConnectionRefused ); } } else { m_connection->disconnect(); m_handler->handleDisconnect( this, ConnIoError ); } break; case S5StateAuthenticating: if( data.length() == 2 && data[0] == 0x01 && data[1] == 0x00 ) { negotiate(); } else { m_connection->disconnect(); m_handler->handleDisconnect( this, ConnProxyAuthFailed ); } break; case S5StateConnected: m_handler->handleReceivedData( this, data ); break; default: break; } }
/* -------------------------------------------------------------------- */ void doLogin(char moreYet) { int foundIt; char InitPw[NAMESIZE+NAMESIZE+2]; char password[NAMESIZE+NAMESIZE+2]; char initials[NAMESIZE+NAMESIZE+2]; char *semicolon; Mflush(); if (!CARRIER) return; if (login_user || login_pw) /* handle command line log-ins */ { if (!modStat) if (cfg.offhook) offhook(); /* login using initials and pw */ if (login_pw) { normalizepw(cmd_login, initials, password); login_pw = FALSE; } else if (login_user) { normalizeString(cmd_login); if (findPerson(cmd_login, &logBuf) != ERROR) { strcpy(initials, logBuf.lbin); strcpy(password, logBuf.lbpw); } login_user = FALSE; } } else /* ask user for initials and password */ { if (moreYet == 2) moreYet = FALSE; else { /* dont print Login when hitting 'L' from console mode */ if (!(!moreYet && !loggedIn && !modStat)) { mPrintf("Login "); } } if (loggedIn) { mPrintf("\n Already logged in!\n "); return; } if (!modStat) if (cfg.offhook) offhook(); getNormStr((moreYet) ? "" : "your initials", InitPw, NAMESIZE+NAMESIZE+1, NO_ECHO); if (!CARRIER) return; dospCR(); semicolon = strchr(InitPw, ';'); if (!semicolon) { strcpy(initials, InitPw); getNormStr( "password", password, NAMESIZE, NO_ECHO); dospCR(); } else { normalizepw(InitPw, initials, password); } /* dont allow anything over 19 characters */ initials[NAMESIZE] = '\0'; } /* reset transmitted & received */ transmitted = 0l; received = 0l; /* reset read & entered */ mread = 0; entered = 0; foundIt = ((pwslot(initials, password)) != ERROR); if (foundIt && *password) { loggedIn = TRUE; update25(); /* trap it */ if (!logBuf.lbflags.NODE) { sprintf( msgBuf->mbtext, "Login %s", logBuf.lbname); if (onConsole) strcat(msgBuf->mbtext, " (Console)"); trap(msgBuf->mbtext, T_LOGIN); } else { sprintf( msgBuf->mbtext, "NetLogin %s", logBuf.lbname); trap(msgBuf->mbtext, T_NETWORK); } } else { loginNew(initials, password); } if (!loggedIn) return; heldMessage = FALSE; setsysconfig(); setgroupgen(); setroomgen(); setlbvisit(); slideLTab(thisSlot); /* cant log in now. */ if (cfg.accounting && !logBuf.lbflags.NOACCOUNT) { negotiate(); logincrement(); if (!logincheck()) { Hangup(); return; } } /* can't log in now. */ if (logBuf.VERIFIED && !onConsole) { tutorial("verified.blb"); Hangup(); return; } if (logBuf.lbflags.NODE) { #ifdef TRASH if (debug) { readnode(); cPrintf("Node: \"%s\" \"%s\"", node.ndname, node.ndregion); doccr(); cPrintf("Phone: \"%s\" %d", node.ndphone, node.nddialto); doccr(); cPrintf("Login: \"%s\" %d", node.ndlogin, node.ndwaitto); doccr(); cPrintf("Baud: %d Protocol: \"%s\"\n ", node.ndbaud, node.ndprotocol); cPrintf("Expire:%d Waitout: %d", node.ndexpire, node.ndwaitto); doccr(); cPrintf("Network: %d ZIP: %s UNZIP: %s", node.network, node.zip, node.unzip); doccr(); } #endif time(&logtimestamp); return; } if (logBuf.PSYCHO) { backout = TRUE; } /* reverse engineering Minibin?!?! */ if (logBuf.MINIBIN) { minibin(); } changedir(cfg.helppath); if ( filexists("bulletin.blb") ) { tutorial("bulletin.blb"); } gotodefaulthall(); roomtalley(); mf.mfLim = 0; /* just to make sure. */ mf.mfMai = 0; mf.mfPub = 0; mf.mfUser[0]=0; nochat(TRUE); /* reset chats */ /* verbose = FALSE; */ verbose = logBuf.VERBOSE; /* hmmm... where to put this */ if (roomBuf.rbflags.APLIC && roomBuf.rbflags.AUTOAPP ) ExeAplic(); showMessages(NEWoNLY, FALSE); verbose = FALSE; if (expert) listRooms(NEWRMS, FALSE); else listRooms(OLDNEW, FALSE); outFlag = OUTOK; setio(whichIO, echo, outFlag); /* record login time, date */ time(&logtimestamp); cfg.callno++; storeLog(); }
std::unique_ptr<RequestBuilderInterface> makeRequestBuilder(ProtocolSet clientProtos, ProtocolSet serverProtos) { return makeRequestBuilder(uassertStatusOK(negotiate(clientProtos, serverProtos))); }
void test_negotiate() { negotiate(); }
static void tests() { CFErrorRef testError = NULL; SecOTRFullIdentityRef aliceID = SecOTRFullIdentityCreate(kCFAllocatorDefault, &testError); SecMPLogError(testError); CFReleaseNull(testError); testError = NULL; SecOTRFullIdentityRef bobID = SecOTRFullIdentityCreate(kCFAllocatorDefault, &testError); SecMPLogError(testError); CFReleaseNull(testError); testError = NULL; ok(aliceID, "create alice ID"); ok(bobID, "create bob ID"); SecOTRPublicIdentityRef alicePublicID = SecOTRPublicIdentityCopyFromPrivate(kCFAllocatorDefault, aliceID, &testError); SecMPLogError(testError); CFReleaseNull(testError); SecOTRPublicIdentityRef bobPublicID = SecOTRPublicIdentityCopyFromPrivate(kCFAllocatorDefault, bobID, &testError); SecMPLogError(testError); CFReleaseNull(testError); ok(alicePublicID, "extract alice public"); ok(bobPublicID, "extract bob public"); SecOTRSessionRef aliceSession = SecOTRSessionCreateFromIDAndFlags(kCFAllocatorDefault, aliceID, bobPublicID, kSecOTRSendTextMessages); SecOTRSessionRef bobSession = SecOTRSessionCreateFromIDAndFlags(kCFAllocatorDefault, bobID, alicePublicID, kSecOTRSendTextMessages); ok(aliceSession, "create alice session"); ok(bobSession, "create bob session"); SecOTRSessionRef aliceCompactSession = SecOTRSessionCreateFromIDAndFlags(kCFAllocatorDefault, aliceID, bobPublicID, kSecOTRUseAppleCustomMessageFormat); SecOTRSessionRef bobCompactSession = SecOTRSessionCreateFromIDAndFlags(kCFAllocatorDefault, bobID, alicePublicID, kSecOTRUseAppleCustomMessageFormat); ok(aliceCompactSession, "create alice compact session"); ok(bobCompactSession, "create bob compact session"); SecOTRSessionRef aliceCompactHashesSession = SecOTRSessionCreateFromIDAndFlags(kCFAllocatorDefault, aliceID, bobPublicID, kSecOTRUseAppleCustomMessageFormat|kSecOTRIncludeHashesInMessages); SecOTRSessionRef bobCompactHashesSession = SecOTRSessionCreateFromIDAndFlags(kCFAllocatorDefault, bobID, alicePublicID, kSecOTRUseAppleCustomMessageFormat|kSecOTRIncludeHashesInMessages); ok(aliceCompactHashesSession, "create alice compact session with hashes"); ok(bobCompactHashesSession, "create bob compact session with hashes"); // Release the IDs, sessions shouldn't need us to retain them for them. CFReleaseNull(aliceID); CFReleaseNull(bobID); CFReleaseNull(alicePublicID); CFReleaseNull(bobPublicID); negotiate(&aliceSession, &bobSession, true, true, true, false); negotiate(&aliceSession, &bobSession, true, false, true, false); negotiate(&aliceCompactSession, &bobCompactSession, true, true, false, true); negotiate(&aliceCompactSession, &bobCompactSession, true, false, false, true); negotiate(&aliceCompactHashesSession, &bobCompactHashesSession, true, true, false, true); negotiate(&aliceCompactHashesSession, &bobCompactHashesSession, true, false, false, true); /* cleanup keychain */ ok(SecOTRFIPurgeAllFromKeychain(&testError),"cleanup keychain"); SecMPLogError(testError); CFReleaseNull(testError); CFReleaseNull(aliceSession); CFReleaseNull(bobSession); CFReleaseNull(aliceCompactSession); CFReleaseNull(bobCompactSession); CFReleaseNull(aliceCompactHashesSession); CFReleaseNull(bobCompactHashesSession); }
int main(int argc, char *const *argv) { struct addrinfo hints, *ai_list, *ai; int r, sockfd = 0; ssize_t session_state_length = 0; uint8_t *session_state = NULL; /* Optional args */ const char *alpn_protocols = NULL; const char *server_name = NULL; const char *ca_file = NULL; const char *ca_dir = NULL; uint16_t mfl_value = 0; uint8_t insecure = 0; int reconnect = 0; uint8_t session_ticket = 1; s2n_status_request_type type = S2N_STATUS_REQUEST_NONE; uint32_t dyn_rec_threshold = 0; uint8_t dyn_rec_timeout = 0; /* required args */ const char *cipher_prefs = "default"; const char *host = NULL; struct verify_data unsafe_verify_data; const char *port = "443"; int echo_input = 0; int use_corked_io = 0; static struct option long_options[] = { {"alpn", required_argument, 0, 'a'}, {"ciphers", required_argument, 0, 'c'}, {"echo", required_argument, 0, 'e'}, {"help", no_argument, 0, 'h'}, {"name", required_argument, 0, 'n'}, {"status", no_argument, 0, 's'}, {"mfl", required_argument, 0, 'm'}, {"ca-file", required_argument, 0, 'f'}, {"ca-dir", required_argument, 0, 'd'}, {"insecure", no_argument, 0, 'i'}, {"reconnect", no_argument, 0, 'r'}, {"no-session-ticket", no_argument, 0, 'T'}, {"dynamic", required_argument, 0, 'D'}, {"timeout", required_argument, 0, 't'}, {"corked-io", no_argument, 0, 'C'}, }; while (1) { int option_index = 0; int c = getopt_long(argc, argv, "a:c:ehn:sf:d:D:t:irTC", long_options, &option_index); if (c == -1) { break; } switch (c) { case 'a': alpn_protocols = optarg; break; case 'C': use_corked_io = 1; break; case 'c': cipher_prefs = optarg; break; case 'e': echo_input = 1; break; case 'h': usage(); break; case 'n': server_name = optarg; break; case 's': type = S2N_STATUS_REQUEST_OCSP; break; case 'm': mfl_value = (uint16_t) atoi(optarg); break; case 'f': ca_file = optarg; break; case 'd': ca_dir = optarg; break; case 'i': insecure = 1; break; case 'r': reconnect = 5; break; case 'T': session_ticket = 0; break; case 't': dyn_rec_timeout = (uint8_t) MIN(255, atoi(optarg)); break; case 'D': dyn_rec_threshold = strtoul(optarg, 0, 10); if (errno == ERANGE) { dyn_rec_threshold = 0; } break; case '?': default: usage(); break; } } if (optind < argc) { host = argv[optind++]; } if (optind < argc) { port = argv[optind++]; } if (!host) { usage(); } if (!server_name) { server_name = host; } memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { fprintf(stderr, "Error disabling SIGPIPE\n"); exit(1); } GUARD_EXIT(s2n_init(), "Error running s2n_init()"); if ((r = getaddrinfo(host, port, &hints, &ai_list)) != 0) { fprintf(stderr, "error: %s\n", gai_strerror(r)); exit(1); } do { int connected = 0; for (ai = ai_list; ai != NULL; ai = ai->ai_next) { if ((sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) { continue; } if (connect(sockfd, ai->ai_addr, ai->ai_addrlen) == -1) { close(sockfd); continue; } connected = 1; /* connect() succeeded */ break; } if (connected == 0) { fprintf(stderr, "Failed to connect to %s:%s\n", host, port); exit(1); } struct s2n_config *config = s2n_config_new(); setup_s2n_config(config, cipher_prefs, type, &unsafe_verify_data, host, alpn_protocols, mfl_value); if (ca_file || ca_dir) { if (s2n_config_set_verification_ca_location(config, ca_file, ca_dir) < 0) { print_s2n_error("Error setting CA file for trust store."); } } else if (insecure) { GUARD_EXIT(s2n_config_disable_x509_verification(config), "Error disabling X.509 validation"); } if (session_ticket) { GUARD_EXIT(s2n_config_set_session_tickets_onoff(config, 1), "Error enabling session tickets"); } struct s2n_connection *conn = s2n_connection_new(S2N_CLIENT); if (conn == NULL) { print_s2n_error("Error getting new connection"); exit(1); } GUARD_EXIT(s2n_connection_set_config(conn, config), "Error setting configuration"); GUARD_EXIT(s2n_set_server_name(conn, server_name), "Error setting server name"); GUARD_EXIT(s2n_connection_set_fd(conn, sockfd) , "Error setting file descriptor"); if (use_corked_io) { GUARD_EXIT(s2n_connection_use_corked_io(conn), "Error setting corked io"); } /* Update session state in connection if exists */ if (session_state_length > 0) { GUARD_EXIT(s2n_connection_set_session(conn, session_state, session_state_length), "Error setting session state in connection"); } /* See echo.c */ int ret = negotiate(conn); if (ret != 0) { /* Error is printed in negotiate */ return -1; } printf("Connected to %s:%s\n", host, port); /* Save session state from connection if reconnect is enabled */ if (reconnect > 0) { if (!session_ticket && s2n_connection_get_session_id_length(conn) <= 0) { printf("Endpoint sent empty session id so cannot resume session\n"); exit(1); } free(session_state); session_state_length = s2n_connection_get_session_length(conn); session_state = calloc(session_state_length, sizeof(uint8_t)); if (s2n_connection_get_session(conn, session_state, session_state_length) != session_state_length) { print_s2n_error("Error getting serialized session state"); exit(1); } } if (dyn_rec_threshold > 0 && dyn_rec_timeout > 0) { s2n_connection_set_dynamic_record_threshold(conn, dyn_rec_threshold, dyn_rec_timeout); } if (echo_input == 1) { echo(conn, sockfd); } s2n_blocked_status blocked; s2n_shutdown(conn, &blocked); GUARD_EXIT(s2n_connection_free(conn), "Error freeing connection"); GUARD_EXIT(s2n_config_free(config), "Error freeing configuration"); close(sockfd); reconnect--; } while (reconnect >= 0); GUARD_EXIT(s2n_cleanup(), "Error running s2n_cleanup()"); free(session_state); freeaddrinfo(ai_list); return 0; }
int main(int argc, char * const *argv) { struct addrinfo hints, *ai_list, *ai; int r, sockfd = 0; /* Optional args */ const char *alpn_protocols = NULL; const char *server_name = NULL; s2n_status_request_type type = S2N_STATUS_REQUEST_NONE; /* required args */ const char *host = NULL; const char *port = "443"; static struct option long_options[] = { { "alpn", required_argument, 0, 'a' }, { "help", no_argument, 0, 'h' }, { "name", required_argument, 0, 'n' }, { "status", no_argument, 0, 's' }, }; while (1) { int option_index = 0; int c = getopt_long (argc, argv, "a:hn:s", long_options, &option_index); if (c == -1) { break; } switch (c) { case 'a': alpn_protocols = optarg; break; case 'h': usage(); break; case 'n': server_name = optarg; break; case 's': type = S2N_STATUS_REQUEST_OCSP; break; case '?': default: usage(); break; } } if (optind < argc) { host = argv[optind++]; } if (optind < argc) { port = argv[optind++]; } if (!host) { usage(); } if (!server_name) { server_name = host; } memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { fprintf(stderr, "Error disabling SIGPIPE\n"); exit(1); } if ((r = getaddrinfo(host, port, &hints, &ai_list)) != 0) { fprintf(stderr, "error: %s\n", gai_strerror(r)); exit(1); } int connected = 0; for (ai = ai_list; ai != NULL; ai = ai->ai_next) { if ((sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) { continue; } if (connect(sockfd, ai->ai_addr, ai->ai_addrlen) == -1) { close(sockfd); continue; } connected = 1; /* connect() succeeded */ break; } freeaddrinfo(ai_list); if (connected == 0) { fprintf(stderr, "Failed to connect to %s:%s\n", argv[1], port); close(sockfd); exit(1); } if (s2n_init() < 0) { fprintf(stderr, "Error running s2n_init(): '%s'\n", s2n_strerror(s2n_errno, "EN")); } struct s2n_config *config = s2n_config_new(); if (config == NULL) { fprintf(stderr, "Error getting new config: '%s'\n", s2n_strerror(s2n_errno, "EN")); exit(1); } if (s2n_config_set_status_request_type(config, type) < 0) { fprintf(stderr, "Error setting status request type: '%s'\n", s2n_strerror(s2n_errno, "EN")); exit(1); } if (alpn_protocols) { /* Count the number of commas, this tells us how many protocols there are in the list */ const char *ptr = alpn_protocols; int protocol_count = 1; while (*ptr) { if (*ptr == ',') { protocol_count++; } ptr++; } char **protocols = malloc(sizeof(char *) * protocol_count); if (!protocols) { fprintf(stderr, "Error allocating memory\n"); exit(1); } const char *next = alpn_protocols; int index = 0; int length = 0; ptr = alpn_protocols; while (*ptr) { if (*ptr == ',') { protocols[index] = malloc(length + 1); if (!protocols[index]) { fprintf(stderr, "Error allocating memory\n"); exit(1); } memcpy(protocols[index], next, length); protocols[index][length] = '\0'; length = 0; index++; ptr++; next = ptr; } else { length++; ptr++; } } if (ptr != next) { protocols[index] = malloc(length + 1); if (!protocols[index]) { fprintf(stderr, "Error allocating memory\n"); exit(1); } memcpy(protocols[index], next, length); protocols[index][length] = '\0'; } if (s2n_config_set_protocol_preferences(config, (const char * const *)protocols, protocol_count) < 0) { fprintf(stderr, "Failed to set protocol preferences: '%s'\n", s2n_strerror(s2n_errno, "EN")); exit(1); } while(protocol_count) { protocol_count--; free(protocols[protocol_count]); } free(protocols); } struct s2n_connection *conn = s2n_connection_new(S2N_CLIENT); if (conn == NULL) { fprintf(stderr, "Error getting new connection: '%s'\n", s2n_strerror(s2n_errno, "EN")); exit(1); } printf("Connected to %s:%s\n", host, port); if (s2n_connection_set_config(conn, config) < 0) { fprintf(stderr, "Error setting configuration: '%s'\n", s2n_strerror(s2n_errno, "EN")); exit(1); } if (s2n_set_server_name(conn, server_name) < 0) { fprintf(stderr, "Error setting server name: '%s'\n", s2n_strerror(s2n_errno, "EN")); exit(1); } if (s2n_connection_set_fd(conn, sockfd) < 0) { fprintf(stderr, "Error setting file descriptor: '%s'\n", s2n_strerror(s2n_errno, "EN")); exit(1); } /* See echo.c */ negotiate(conn); echo(conn, sockfd); s2n_blocked_status blocked; if (s2n_shutdown(conn, &blocked) < 0) { fprintf(stderr, "Error calling s2n_shutdown: '%s'\n", s2n_strerror(s2n_errno, "EN")); exit(1); } if (s2n_connection_free(conn) < 0) { fprintf(stderr, "Error freeing connection: '%s'\n", s2n_strerror(s2n_errno, "EN")); exit(1); } if (s2n_config_free(config) < 0) { fprintf(stderr, "Error freeing configuration: '%s'\n", s2n_strerror(s2n_errno, "EN")); exit(1); } if (s2n_cleanup() < 0) { fprintf(stderr, "Error running s2n_cleanup(): '%s'\n", s2n_strerror(s2n_errno, "EN")); } return 0; }
CURLcode Curl_telnet(struct connectdata *conn, bool *done) { CURLcode code; struct SessionHandle *data = conn->data; curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; #ifdef USE_WINSOCK HMODULE wsock2; WSOCK2_FUNC close_event_func; WSOCK2_FUNC create_event_func; WSOCK2_FUNC event_select_func; WSOCK2_FUNC enum_netevents_func; WSAEVENT event_handle; WSANETWORKEVENTS events; HANDLE stdin_handle; HANDLE objs[2]; DWORD obj_count; DWORD wait_timeout; DWORD waitret; DWORD readfile_read; #else int interval_ms; struct pollfd pfd[2]; #endif ssize_t nread; bool keepon = TRUE; char *buf = data->state.buffer; struct TELNET *tn; *done = TRUE; /* uncontionally */ code = init_telnet(conn); if(code) return code; tn = (struct TELNET *)data->reqdata.proto.telnet; code = check_telnet_options(conn); if(code) return code; #ifdef USE_WINSOCK /* ** This functionality only works with WinSock >= 2.0. So, ** make sure have it. */ code = check_wsock2(data); if (code) return code; /* OK, so we have WinSock 2.0. We need to dynamically */ /* load ws2_32.dll and get the function pointers we need. */ wsock2 = LoadLibrary("WS2_32.DLL"); if (wsock2 == NULL) { failf(data,"failed to load WS2_32.DLL (%d)", ERRNO); return CURLE_FAILED_INIT; } /* Grab a pointer to WSACreateEvent */ create_event_func = GetProcAddress(wsock2,"WSACreateEvent"); if (create_event_func == NULL) { failf(data,"failed to find WSACreateEvent function (%d)", ERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSACloseEvent */ close_event_func = GetProcAddress(wsock2,"WSACloseEvent"); if (close_event_func == NULL) { failf(data,"failed to find WSACloseEvent function (%d)", ERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSAEventSelect */ event_select_func = GetProcAddress(wsock2,"WSAEventSelect"); if (event_select_func == NULL) { failf(data,"failed to find WSAEventSelect function (%d)", ERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSAEnumNetworkEvents */ enum_netevents_func = GetProcAddress(wsock2,"WSAEnumNetworkEvents"); if (enum_netevents_func == NULL) { failf(data,"failed to find WSAEnumNetworkEvents function (%d)", ERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* We want to wait for both stdin and the socket. Since ** the select() function in winsock only works on sockets ** we have to use the WaitForMultipleObjects() call. */ /* First, create a sockets event object */ event_handle = (WSAEVENT)create_event_func(); if (event_handle == WSA_INVALID_EVENT) { failf(data,"WSACreateEvent failed (%d)", SOCKERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* The get the Windows file handle for stdin */ stdin_handle = GetStdHandle(STD_INPUT_HANDLE); /* Create the list of objects to wait for */ objs[0] = event_handle; objs[1] = stdin_handle; /* Tell winsock what events we want to listen to */ if(event_select_func(sockfd, event_handle, FD_READ|FD_CLOSE) == SOCKET_ERROR) { close_event_func(event_handle); FreeLibrary(wsock2); return 0; } /* If stdin_handle is a pipe, use PeekNamedPipe() method to check it, else use the old WaitForMultipleObjects() way */ if(GetFileType(stdin_handle) == FILE_TYPE_PIPE) { /* Don't wait for stdin_handle, just wait for event_handle */ obj_count = 1; /* Check stdin_handle per 100 milliseconds */ wait_timeout = 100; } else { obj_count = 2; wait_timeout = INFINITE; } /* Keep on listening and act on events */ while(keepon) { waitret = WaitForMultipleObjects(obj_count, objs, FALSE, wait_timeout); switch(waitret) { case WAIT_TIMEOUT: { unsigned char outbuf[2]; int out_count = 0; ssize_t bytes_written; char *buffer = buf; while(1) { if(!PeekNamedPipe(stdin_handle, NULL, 0, NULL, &readfile_read, NULL)) { keepon = FALSE; break; } nread = readfile_read; if(!nread) break; if(!ReadFile(stdin_handle, buf, sizeof(data->state.buffer), &readfile_read, NULL)) { keepon = FALSE; break; } nread = readfile_read; while(nread--) { outbuf[0] = *buffer++; out_count = 1; if(outbuf[0] == CURL_IAC) outbuf[out_count++] = CURL_IAC; Curl_write(conn, conn->sock[FIRSTSOCKET], outbuf, out_count, &bytes_written); } } } break; case WAIT_OBJECT_0 + 1: { unsigned char outbuf[2]; int out_count = 0; ssize_t bytes_written; char *buffer = buf; if(!ReadFile(stdin_handle, buf, sizeof(data->state.buffer), &readfile_read, NULL)) { keepon = FALSE; break; } nread = readfile_read; while(nread--) { outbuf[0] = *buffer++; out_count = 1; if(outbuf[0] == CURL_IAC) outbuf[out_count++] = CURL_IAC; Curl_write(conn, conn->sock[FIRSTSOCKET], outbuf, out_count, &bytes_written); } } break; case WAIT_OBJECT_0: if(enum_netevents_func(sockfd, event_handle, &events) != SOCKET_ERROR) { if(events.lNetworkEvents & FD_READ) { /* This reallu OUGHT to check its return code. */ (void)Curl_read(conn, sockfd, buf, BUFSIZE - 1, &nread); telrcv(conn, (unsigned char *)buf, nread); fflush(stdout); /* Negotiate if the peer has started negotiating, otherwise don't. We don't want to speak telnet with non-telnet servers, like POP or SMTP. */ if(tn->please_negotiate && !tn->already_negotiated) { negotiate(conn); tn->already_negotiated = 1; } } if(events.lNetworkEvents & FD_CLOSE) { keepon = FALSE; } } break; } } /* We called WSACreateEvent, so call WSACloseEvent */ if (close_event_func(event_handle) == FALSE) { infof(data,"WSACloseEvent failed (%d)", SOCKERRNO); } /* "Forget" pointers into the library we're about to free */ create_event_func = NULL; close_event_func = NULL; event_select_func = NULL; enum_netevents_func = NULL; /* We called LoadLibrary, so call FreeLibrary */ if (!FreeLibrary(wsock2)) infof(data,"FreeLibrary(wsock2) failed (%d)", ERRNO); #else pfd[0].fd = sockfd; pfd[0].events = POLLIN; pfd[1].fd = 0; pfd[1].events = POLLIN; interval_ms = 1 * 1000; while (keepon) { switch (Curl_poll(pfd, 2, interval_ms)) { case -1: /* error, stop reading */ keepon = FALSE; continue; case 0: /* timeout */ break; default: /* read! */ if(pfd[1].revents & POLLIN) { /* read from stdin */ unsigned char outbuf[2]; int out_count = 0; ssize_t bytes_written; char *buffer = buf; nread = read(0, buf, 255); while(nread--) { outbuf[0] = *buffer++; out_count = 1; if(outbuf[0] == CURL_IAC) outbuf[out_count++] = CURL_IAC; Curl_write(conn, conn->sock[FIRSTSOCKET], outbuf, out_count, &bytes_written); } } if(pfd[0].revents & POLLIN) { /* This OUGHT to check the return code... */ (void)Curl_read(conn, sockfd, buf, BUFSIZE - 1, &nread); /* if we receive 0 or less here, the server closed the connection and we bail out from this! */ if (nread <= 0) { keepon = FALSE; break; } telrcv(conn, (unsigned char *)buf, nread); /* Negotiate if the peer has started negotiating, otherwise don't. We don't want to speak telnet with non-telnet servers, like POP or SMTP. */ if(tn->please_negotiate && !tn->already_negotiated) { negotiate(conn); tn->already_negotiated = 1; } } } if(data->set.timeout) { struct timeval now; /* current time */ now = Curl_tvnow(); if(Curl_tvdiff(now, conn->created) >= data->set.timeout) { failf(data, "Time-out"); code = CURLE_OPERATION_TIMEDOUT; keepon = FALSE; } } } #endif /* mark this as "no further transfer wanted" */ Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL); return code; }
int main(int argc,char **argv) { struct sockaddr_in sock; struct hostent *pHe; int sd; short port = -1; int x; char *host = NULL; char *user = NULL; char exp[1024]; int a; char *default_port = "23"; printf("linux_pam_smb\n"); printf("Linux lib_pam_smb < 1.1.6 /bin/login remote exploit\n"); printf("[vertex//lids/org]\n\n"); if (argc < 2) { printf("%s -h <victim> [-p port] \n",argv[0]); return 0; } while ((a = getopt(argc,argv,"h:p:u:")) != -1) { switch (a) { case 'h': host = optarg; break; case 'p': port = atoi(optarg); break; default: printf("[-] invalid option.\n"); break; } } if (host == NULL) { printf("[-] must specify a host to attack\n"); return 0; } if (port < 0) port = atoi(default_port); if ((pHe = gethostbyname(host)) == NULL) { printf("Host lookup error.\n"); return 0; } printf("[*] attacking %s:%d\n",host,port); printf("[*] opening socket\n"); if ((sd = socket(AF_INET,SOCK_STREAM,0)) == -1) { printf("[-] could not create socket"); return 0; } sock.sin_family = AF_INET; sock.sin_port = htons(port); memcpy(&sock.sin_addr.s_addr,pHe->h_addr,pHe->h_length); if ((connect(sd,(struct sockaddr *)&sock,sizeof(sock))) == -1) { printf("[-] failed to connect to %s\n",host); return 0; } printf("[*] connected!\n"); printf("[*] Begin negotiate... \n"); negotiate(sd); printf("[*] Login... \n"); login(sd); return 0; }
/// =-=-=-=-=-=-=- /// @brief function which manages the TLS and Auth negotiations with the client error client_server_negotiation_for_client( irods::network_object_ptr _ptr, std::string& _result ) { // =-=-=-=-=-=-=- // we requested a negotiation, wait for the response from CS_NEG_SVR_1_MSG boost::shared_ptr< cs_neg_t > cs_neg; error err = read_client_server_negotiation_message( _ptr, cs_neg ); if ( !err.ok() ) { return PASS( err ); } // =-=-=-=-=-=-=- // get the server requested policy std::string svr_policy( cs_neg->result_ ); if ( svr_policy.empty() || cs_neg->status_ != CS_NEG_STATUS_SUCCESS ) { std::stringstream msg; msg << "invalid result [" << cs_neg->result_ << "] or status: " << cs_neg->status_; return ERROR( -1, msg.str() ); } // =-=-=-=-=-=-=- // get the irods environment so we can compare the // policy in the .irodsEnv file rodsEnv rods_env; int status = getRodsEnv( &rods_env ); if ( status < 0 ) { return ERROR( status, "failed in getRodsEnv" ); } // =-=-=-=-=-=-=- // if the policy is empty, then default to DONT_CARE std::string cli_policy( rods_env.rodsClientServerPolicy ); if ( cli_policy.empty() ) { cli_policy = CS_NEG_DONT_CARE; } // =-=-=-=-=-=-=- // perform the negotiation client_server_negotiations_context negotiate; std::string result; error neg_err = negotiate( cli_policy, svr_policy, result ); // =-=-=-=-=-=-=- // aggregate the error stack if necessary error ret = SUCCESS(); if ( !neg_err.ok() ) { ret = PASSMSG( "failed in negotiation context", neg_err ); } // =-=-=-=-=-=-=- // handle failure - send a failure msg back to client if ( !err.ok() || CS_NEG_FAILURE == result ) { // =-=-=-=-=-=-=- // send CS_NEG_CLI_1_MSG, failure message to the server cs_neg_t send_cs_neg; send_cs_neg.status_ = CS_NEG_STATUS_FAILURE; strncpy( send_cs_neg.result_, CS_NEG_FAILURE.c_str(), MAX_NAME_LEN ); error send_err = send_client_server_negotiation_message( _ptr, send_cs_neg ); if ( !send_err.ok() ) { ret = PASSMSG( "failed to send CS_NEG_CLI1_MSG Failure Messsage", send_err ); } std::stringstream msg; msg << "client-server negoations failed for server request ["; msg << svr_policy << "] and client request [" << cli_policy << "]"; ret = PASSMSG( msg.str(), ret ); return ret; } // =-=-=-=-=-=-=- // send CS_NEG_CLI_1_MSG, success message to the server with our choice cs_neg_t send_cs_neg; send_cs_neg.status_ = CS_NEG_STATUS_SUCCESS; strncpy( send_cs_neg.result_, result.c_str(), MAX_NAME_LEN ); err = send_client_server_negotiation_message( _ptr, send_cs_neg ); if ( !err.ok() ) { return PASSMSG( "failed to send CS_NEG_CLI_1_MSG Success Message", err ); } // =-=-=-=-=-=-=- // set the out variable and return _result = result; return SUCCESS(); } // client_server_negotiation_for_client
void HttpBasedTransport::retryNegotiation() { disconnect(&_retryTimerTimeout, SIGNAL(timeout()), this, SLOT(retryNegotiation())); _retryTimerTimeout.stop(); negotiate(); }