Код исходника для фаервола на С++

  • Автор темы Sorrowing
  • Дата начала
Статус
Закрыто для дальнейших ответов.
S

Sorrowing

#1
Помогите, пожалуйста, разобраться с кодом, обьясните ( в идеале-построчно). Очень нужно. Поскольку сроки сдачи диплома поджимают, а сам написать простенький фаервол за 2 недели я не в состоянии. Буду очень благодарен. Код на С++.
[codebox]#include <string.h>
#include <stdio.h>
#include <ntddk.h>
#include <ntddndis.h>
#include <pfhook.h>
#include "DrvFltIp.h"

#if DBG
#define dprintf DbgPrint
#else
#define dprintf(x)
#endif

NTSTATUS DrvDispatch(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp);
VOID DrvUnload(IN PDRIVER_OBJECT DriverObject);

NTSTATUS SetFilterFunction(PacketFilterExtensionPtr filterFunction);

NTSTATUS AddFilterToList(IPFilter *pf);
void ClearFilterList(void);
PF_FORWARD_ACTION cbFilterFunction(IN unsigned char *PacketHeader,IN unsigned char *Packet, IN unsigned int PacketLength, IN unsigned int RecvInterfaceIndex, IN unsigned int SendInterfaceIndex, IN unsigned long RecvLinkNextHop, IN unsigned long SendLinkNextHop);

#define NT_DEVICE_NAME L"\\Device\\DrvFltIp"
#define DOS_DEVICE_NAME L"\\DosDevices\\DrvFltIp"


struct filterList *first = NULL;
struct filterList *last = NULL;

/*++

Routine Description:

Installable driver initialization entry point.
This entry point is called directly by the I/O system.

Arguments:

DriverObject - pointer to the driver object

RegistryPath - pointer to a unicode string representing the path
to driver-specific key in the registry

Return Value:

STATUS_SUCCESS if successful,
STATUS_UNSUCCESSFUL otherwise

--*/
NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath)
{

PDEVICE_OBJECT deviceObject = NULL;
NTSTATUS ntStatus;
UNICODE_STRING deviceNameUnicodeString;
UNICODE_STRING deviceLinkUnicodeString;

dprintf("DrvFltIp.SYS: entering DriverEntry\n");


//we have to create the device
RtlInitUnicodeString(&deviceNameUnicodeString, NT_DEVICE_NAME);

ntStatus = IoCreateDevice(DriverObject,
0,
&deviceNameUnicodeString,
FILE_DEVICE_DRVFLTIP,
0,
FALSE,
&deviceObject);


if ( NT_SUCCESS(ntStatus) )
{

// Create a symbolic link that Win32 apps can specify to gain access
// to this driver/device
RtlInitUnicodeString(&deviceLinkUnicodeString, DOS_DEVICE_NAME);

ntStatus = IoCreateSymbolicLink(&deviceLinkUnicodeString, &deviceNameUnicodeString);

if ( !NT_SUCCESS(ntStatus) )
{
dprintf("DrvFltIp.SYS: IoCreateSymbolicLink failed\n");
}

//
// Create dispatch points for device control, create, close.
//

DriverObject->MajorFunction[IRP_MJ_CREATE] =
DriverObject->MajorFunction[IRP_MJ_CLOSE] =
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DrvDispatch;
DriverObject->DriverUnload = DrvUnload;
}

if ( !NT_SUCCESS(ntStatus) )
{
dprintf("Error in initialization. Unloading...");

DrvUnload(DriverObject);
}

return ntStatus;
}


/*++

Routine Description:

Process the IRPs sent to this device.

Arguments:

DeviceObject - pointer to a device object

Irp - pointer to an I/O Request Packet

Return Value:

--*/
NTSTATUS DrvDispatch(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
{

PIO_STACK_LOCATION irpStack;
PVOID ioBuffer;
ULONG inputBufferLength;
ULONG outputBufferLength;
ULONG ioControlCode;
NTSTATUS ntStatus;

Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;



// Get a pointer to the current location in the Irp. This is where
// the function codes and parameters are located.
irpStack = IoGetCurrentIrpStackLocation(Irp);


// Get the pointer to the input/output buffer and it's length
ioBuffer = Irp->AssociatedIrp.SystemBuffer;
inputBufferLength = irpStack->Parameters.DeviceIoControl.InputBufferLength;
outputBufferLength = irpStack->Parameters.DeviceIoControl.OutputBufferLength;

switch (irpStack->MajorFunction)
{
case IRP_MJ_CREATE:

dprintf("DrvFltIp.SYS: IRP_MJ_CREATE\n");

break;

case IRP_MJ_CLOSE:

dprintf("DrvFltIp.SYS: IRP_MJ_CLOSE\n");

break;

case IRP_MJ_DEVICE_CONTROL:

dprintf("DrvFltIp.SYS: IRP_MJ_DEVICE_CONTROL\n");

ioControlCode = irpStack->Parameters.DeviceIoControl.IoControlCode;

switch (ioControlCode)
{
// ioctl code to start filtering
case START_IP_HOOK:
{
SetFilterFunction(cbFilterFunction);

break;
}

// ioctl to stop filtering
case STOP_IP_HOOK:
{
SetFilterFunction(NULL);

break;
}

// ioctl to add a filter rule
case ADD_FILTER:
{
if(inputBufferLength == sizeof(IPFilter))
{
IPFilter *nf;

nf = (IPFilter *)ioBuffer;

AddFilterToList(nf);
}

break;
}

// ioctl to free filter rule list
case CLEAR_FILTER:
{
ClearFilterList();

break;
}

default:
Irp->IoStatus.Status = STATUS_INVALID_PARAMETER;

dprintf("DrvFltIp.SYS: unknown IRP_MJ_DEVICE_CONTROL\n");

break;
}

break;
}


//
// DON'T get cute and try to use the status field of
// the irp in the return status. That IRP IS GONE as
// soon as you call IoCompleteRequest.
//

ntStatus = Irp->IoStatus.Status;

IoCompleteRequest(Irp, IO_NO_INCREMENT);


//
// We never have pending operation so always return the status code.
//

return ntStatus;
}

/*++

Routine Description:

Free all the allocated resources, etc.

Arguments:

DriverObject - pointer to a driver object

Return Value:


--*/
VOID DrvUnload(IN PDRIVER_OBJECT DriverObject)
{
UNICODE_STRING deviceLinkUnicodeString;

dprintf("DrvFltIp.SYS: Unloading\n");

SetFilterFunction(NULL);

// Free any resources
ClearFilterList();

// Delete the symbolic link
RtlInitUnicodeString(&deviceLinkUnicodeString, DOS_DEVICE_NAME);
IoDeleteSymbolicLink(&deviceLinkUnicodeString);


// Delete the device object
IoDeleteDevice(DriverObject->DeviceObject);
}



/*++

Routine Description:

Get a reference to IpFilterDriver so we will be able to install the filter

Arguments:

pDeviceObject - pointer to a pointer of device object

pFileObject - pointer to a pointer of file object

Return Value:

STATUS_SUCCESS if successful,
STATUS_UNSUCCESSFUL otherwise

--*/
NTSTATUS SetFilterFunction(PacketFilterExtensionPtr filterFunction)
{
NTSTATUS status = STATUS_SUCCESS, waitStatus=STATUS_SUCCESS;
UNICODE_STRING filterName;
PDEVICE_OBJECT ipDeviceObject=NULL;
PFILE_OBJECT ipFileObject=NULL;

PF_SET_EXTENSION_HOOK_INFO filterData;

KEVENT event;
IO_STATUS_BLOCK ioStatus;
PIRP irp;

dprintf("Getting pointer to IpFilterDriver\n");

//first of all, we have to get a pointer to IpFilterDriver Device
RtlInitUnicodeString(&filterName, DD_IPFLTRDRVR_DEVICE_NAME);
status = IoGetDeviceObjectPointer(&filterName,STANDARD_RIGHTS_ALL, &ipFileObject, &ipDeviceObject);

if(NT_SUCCESS(status))
{
//initialize the struct with functions parameters
filterData.ExtensionPointer = filterFunction;

//we need initialize the event used later by the IpFilterDriver to signal us
//when it finished its work
KeInitializeEvent(&event, NotificationEvent, FALSE);

//we build the irp needed to establish fitler function
irp = IoBuildDeviceIoControlRequest(IOCTL_PF_SET_EXTENSION_POINTER,
ipDeviceObject,
(PVOID) &filterData,
sizeof(PF_SET_EXTENSION_HOOK_INFO),
NULL,
0,
FALSE,
&event,
&ioStatus);


if(irp != NULL)
{
// we send the IRP
status = IoCallDriver(ipDeviceObject, irp);

//and finally, we wait for "acknowledge" of IpDriverFilter
if (status == STATUS_PENDING)
{
waitStatus = KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);

if (waitStatus != STATUS_SUCCESS )
dprintf("Error waiting for IpFilterDriver response.");
}

status = ioStatus.Status;

if(!NT_SUCCESS(status))
dprintf("Error, IO error with ipFilterDriver\n");
}

else
{
//if we cant allocate the space, we return the corresponding code error
status = STATUS_INSUFFICIENT_RESOURCES;

dprintf("Error building IpFilterDriver IRP\n");
}

if(ipFileObject != NULL)
ObDereferenceObject(ipFileObject);

ipFileObject = NULL;
ipDeviceObject = NULL;
}

else
dprintf("Error while getting the pointer\n");

return status;
}




/*++

Routine Description:

Add a rule to the filter list

Arguments:

pf - pointer to filter rule


Return Value:

STATUS_SUCCESS if successful,
STATUS_INSUFFICIENT_RESOURCES otherwise

--*/
NTSTATUS AddFilterToList(IPFilter *pf)
{
struct filterList *aux=NULL;

// first, we reserve memory (non paged) to the new filter
aux=(struct filterList *) ExAllocatePool(NonPagedPool, sizeof(struct filterList));

if(aux == NULL)
{
dprintf("Problem reserving memory\n");

return STATUS_INSUFFICIENT_RESOURCES;
}

//fill the new structure
aux->ipf.destinationIp = pf->destinationIp;
aux->ipf.sourceIp = pf->sourceIp;

aux->ipf.destinationMask = pf->destinationMask;
aux->ipf.sourceMask = pf->sourceMask;

aux->ipf.destinationPort = pf->destinationPort;
aux->ipf.sourcePort = pf->sourcePort;

aux->ipf.protocol = pf->protocol;

aux->ipf.drop=pf->drop;

//Add the new filter to the filter list
if(first == NULL)
{
first = last = aux;

first->next = NULL;
}

else
{
last->next = aux;
last = aux;
last->next = NULL;
}

dprintf("Rule Added\n\t%x %x\n\t%x %x\n\t%x\n\t%x", aux->ipf.sourceIp
, aux->ipf.sourceMask
, aux->ipf.destinationIp
, aux->ipf.destinationMask
, aux->ipf.sourcePort
, aux->ipf.destinationPort);

return STATUS_SUCCESS;
}




/*++

Routine Description:

Remove the linked list where the rules were saved.

Arguments:


Return Value:


--*/
void ClearFilterList(void)
{
struct filterList *aux = NULL;

//free the linked list
dprintf("Removing the filter List...");

while(first != NULL)
{
aux = first;
first = first->next;
ExFreePool(aux);

dprintf("One Rule removed");
}

first = last = NULL;

dprintf("Removed is complete.");
}


/*++

Routine Description:

Filter each packet is received or sended

To see parameters and return you can read it in MSDN
--*/

PF_FORWARD_ACTION cbFilterFunction(IN unsigned char *PacketHeader,IN unsigned char *Packet, IN unsigned int PacketLength, IN unsigned int RecvInterfaceIndex, IN unsigned int SendInterfaceIndex, IN unsigned long RecvLinkNextHop, IN unsigned long SendLinkNextHop)
{
IPPacket *ipp;
TCPHeader *tcph;
UDPHeader *udph;

int countRule=0;

struct filterList *aux = first;

//we "extract" the ip Header
ipp=(IPPacket *)PacketHeader;

dprintf("Tamaño: %x, %d", PacketLength, RecvInterfaceIndex);
dprintf("Source: %x\nDestination: %x\nProtocol: %d", ipp->ipSource, ipp->ipDestination, ipp->ipProtocol);

//TCP -> protocol = 6
//we accept all packets of established connections
if(ipp->ipProtocol == 6)
{
tcph=(TCPHeader *)Packet;

dprintf("FLAGS: %x\n", tcph->flags);

//if we havent the bit SYN activate, we pass the packets
if(!(tcph->flags & 0x02))
return PF_FORWARD;
}

//otherwise, we compare the packet with our rules
while(aux != NULL)
{
dprintf("Comparing with Rule %d", countRule);

//if protocol is the same....
if(aux->ipf.protocol == 0 || ipp->ipProtocol == aux->ipf.protocol)
{
//we look in source Address
if(aux->ipf.sourceIp != 0 && (ipp->ipSource & aux->ipf.sourceMask) != aux->ipf.sourceIp)
{
aux=aux->next;

countRule++;
continue;
}

// we look in destination address
if(aux->ipf.destinationIp != 0 && (ipp->ipDestination & aux->ipf.destinationMask) != aux->ipf.destinationIp)
{
aux=aux->next;

countRule++;
continue;
}

//if we have a tcp packet, we look in ports
//tcp, protocol = 6
if(ipp->ipProtocol == 6)
{
if(aux->ipf.sourcePort == 0 || tcph->sourcePort == aux->ipf.sourcePort)
{
if(aux->ipf.destinationPort == 0 || tcph->destinationPort == aux->ipf.destinationPort) //puerto tcp destino
{
//now we decided what to do with the packet
if(aux->ipf.drop)
return PF_DROP;
else
return PF_FORWARD;
}
}
}

//udp, protocol = 17
else if(ipp->ipProtocol == 17)
{
udph=(UDPHeader *)Packet;

if(aux->ipf.sourcePort == 0 || udph->sourcePort == aux->ipf.sourcePort)
{
if(aux->ipf.destinationPort == 0 || udph->destinationPort == aux->ipf.destinationPort)
{
//now we decided what to do with the packet
if(aux->ipf.drop)
return PF_DROP;

else
return PF_FORWARD;
}
}
}

else
{
//for other packet we dont look more and ....
//now we decided what to do with the packet
if(aux->ipf.drop)
return PF_DROP;
else
return PF_FORWARD;
}
}

//compare with the next rule
countRule++;
aux=aux->next;
}

//we accept all not registered
return PF_FORWARD;
}[/codebox]
Коментарии перевел, да только все равно ничего не понятно... :) Если поможет - кидаю весь исходник Посмотреть вложение DrvFltIp_source.zip (остальное, кстатее, тоже не очень ясно((( Мое мыло xenon101@inbox.ru Заранее СПАСИБО.
 

Вложения

A

alexsid

#2
типичный код драйвера
Эта функция - аналог WinMain для оконного приложения
Код:
NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath)
в ней происходит создание и инициализация дескриптора драйвера.

В процессе работы драйвера вызываются разные функции-обработчики.
Тут инициализация этих обработчиков:
Код:
DriverObject->MajorFunction[IRP_MJ_CREATE] =
DriverObject->MajorFunction[IRP_MJ_CLOSE] =
DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DrvDispatch;
DriverObject->DriverUnload = DrvUnload;
Драйвер заточен на работу через ioctl механизм (функция DeviceIoControl описание здесь).
Обработчик запросов - функция DrvDispatch.

Обрабатываются START_IP_HOOK, STOP_IP_HOOK, ADD_FILTER, CLEAR_FILTER.
Соответственно:
- начинает фильтрацию
- останавливает фильтрацию
- добавляет фильтр
- удаляет фильтр

Это вкратце
 
S

Sorrowing

#3
Спасибо тебе большое!!! Я - то думал что фаервол, а оказалось драйвер((( Я понимаю, что наглею малость, но не подсобиш ли еще раз?
[codebox]#include "stdafx.h"
#include "FirewallApp.h"

#include "MainFrm.h"
#include "FirewallAppDoc.h"
#include "FirewallAppView.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CFirewallAppApp

BEGIN_MESSAGE_MAP(CFirewallAppApp, CWinApp)
//{{AFX_MSG_MAP(CFirewallAppApp)
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG_MAP
// Standard file based document commands
ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
// Standard print setup command
ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CFirewallAppApp construction

CFirewallAppApp::CFirewallAppApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CFirewallAppApp object

CFirewallAppApp theApp;

/////////////////////////////////////////////////////////////////////////////
// CFirewallAppApp initialization

BOOL CFirewallAppApp::InitInstance()
{
AfxEnableControlContainer();

// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.

#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif

// Change the registry key under which our settings are stored.
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization.
SetRegistryKey(_T("FirewallApp"));

LoadStdProfileSettings(); // Load standard INI file options (including MRU)

// Register the application's document templates. Document templates
// serve as the connection between documents, frame windows and views.

CSingleDocTemplate* pDocTemplate;
pDocTemplate = new CSingleDocTemplate(
IDR_MAINFRAME,
RUNTIME_CLASS(CFirewallAppDoc),
RUNTIME_CLASS(CMainFrame), // main SDI frame window
RUNTIME_CLASS(CFirewallAppView));
AddDocTemplate(pDocTemplate);

// Parse command line for standard shell commands, DDE, file open
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);

// Dispatch commands specified on the command line
if (!ProcessShellCommand(cmdInfo))
return FALSE;

// The one and only window has been initialized, so show and update it.
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();

return TRUE;
}


/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
CAboutDlg();

// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA

// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL

// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
// No message handlers
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

// App command to run the dialog
void CFirewallAppApp::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}[/codebox]

Это точно фаер)) расширение .срр
И вот это...
[codebox]#include "stdafx.h"
#include "FirewallApp.h"
#include "RuleDlg.h"

#include "sockUtil.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CRuleDlg dialog


CRuleDlg::CRuleDlg(CWnd* pParent /*=NULL*/)
: CDialog(CRuleDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CRuleDlg)
m_ipsource = _T("0.0.0.0");
m_portsource = 0;
m_ipdestination = _T("0.0.0.0");
m_portDestination = 0;
m_action = _T("Tirar");
m_protocol = _T("TCP");
m_srcMask = _T("255.255.255.255");
m_dstMask = _T("255.255.255.255");
//}}AFX_DATA_INIT
}


void CRuleDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CRuleDlg)
DDX_Text(pDX, IDC_EDIT1, m_ipsource);
DDV_MaxChars(pDX, m_ipsource, 15);
DDX_Text(pDX, IDC_EDIT2, m_portsource);
DDX_Text(pDX, IDC_EDIT3, m_ipdestination);
DDV_MaxChars(pDX, m_ipdestination, 15);
DDX_Text(pDX, IDC_EDIT4, m_portDestination);
DDX_CBString(pDX, IDC_COMBO3, m_action);
DDX_CBString(pDX, IDC_COMBO4, m_protocol);
DDX_Text(pDX, IDC_EDIT6, m_srcMask);
DDV_MaxChars(pDX, m_srcMask, 15);
DDX_Text(pDX, IDC_EDIT5, m_dstMask);
DDV_MaxChars(pDX, m_dstMask, 15);
//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CRuleDlg, CDialog)
//{{AFX_MSG_MAP(CRuleDlg)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CRuleDlg message handlers

void CRuleDlg::OnOK()
{
int result;

UpdateData(TRUE);

result = inet_addr(m_ipsource, &srcIp);

if(result == -1)
{
AfxMessageBox("Source Ip isn't valid.");

return;
}

result = inet_addr(m_srcMask, &srcMask);

if(result == -1)
{
AfxMessageBox("Source Mask isn't valid.");

return;
}


result = inet_addr(m_ipdestination, &dstIp);

if(result == -1)
{
AfxMessageBox("Destination Ip isn't valid.");

return;
}

result = inet_addr(m_dstMask, &dstMask);

if(result == -1)
{
AfxMessageBox("Destination Mask isn't valid.");

return;
}


if(m_protocol == "TCP")
protocol = 6;

else if(m_protocol == "UDP")
protocol = 17;

else if(m_protocol == "ICMP")
protocol = 1;

else
protocol = 0;


if(m_action == "")
{
AfxMessageBox("Select an Action, please");

return;
}

else
{
if(m_action == "Forward")
cAction = 0;

else
cAction = 1;

}

srcPort = m_portsource;
dstPort = m_portDestination;

CDialog::OnOK();
}[/codebox]
Насколько я понять смог, создание правил...

P. S.
Напиши заодно как репутацию тебе поднять...)))
 
A

alexsid

#4
фаервол скорее всего прога которая состоит из:
- драйвера - юзается для блокировки потоков данных через порт
- графического интерфейса пользователя - для установки правил блокирования просмотра и прочей мути.

у тя код 1 - общий для приложения и 2 - диалог для получения данных о правиле блокирования (адрес, порт и т.п.)
Короче его очень немного и на прогу не наскребешь :)

ПС: рейтинг гдето в посте можно подымать
точно не знаю
 
S

Sorrowing

#5
Спасибо за ответ. У меня готовый фаер лежит.. Просто в нем надо разобратся чтоб описать... Эти коды-части...
 
S

Sorrowing

#6
И все-таки я в упор понять не могу... Что за устройство выбирается под номером 0x00654322 ???.
Вот, смотри. В коде описывается намера каких-то устройств, определяется для них IOCTL (Тоже не совсем ясно... О каком устройстве может идти речь, если это чисто программный персональный файервол) Посмотри код, пожалуйста.
Код:
//
// Define the various device type values. Note that values used by Microsoft
// Corporation are in the range 0-32767, and 32768-65535 are reserved for use
// by customers.
//
// Type of the device. Of 0-32767 reserved by Microsoft.
#define FILE_DEVICE_DRVFLTIP 0x00654322


// Macro to define IOCTL
#define DRVFLTIP_IOCTL_INDEX 0x830


// I define the IOCTLs
#define START_IP_HOOK CTL_CODE(FILE_DEVICE_DRVFLTIP, DRVFLTIP_IOCTL_INDEX,METHOD_BUFFERED, FILE_ANY_ACCESS)

#define STOP_IP_HOOK CTL_CODE(FILE_DEVICE_DRVFLTIP, DRVFLTIP_IOCTL_INDEX+1, METHOD_BUFFERED, FILE_ANY_ACCESS)

#define ADD_FILTER CTL_CODE(FILE_DEVICE_DRVFLTIP, DRVFLTIP_IOCTL_INDEX+2, METHOD_BUFFERED, FILE_WRITE_ACCESS)

#define CLEAR_FILTER CTL_CODE(FILE_DEVICE_DRVFLTIP, DRVFLTIP_IOCTL_INDEX+3, METHOD_BUFFERED, FILE_ANY_ACCESS)



// He structures to define a rule of leaked
typedef struct filter
{
USHORT protocol;		// Protocol

ULONG sourceIp;			// Direction IP source
ULONG destinationIp;	// Direction IP destined

ULONG sourceMask;		// Mask of direction IP source
ULONG destinationMask;	// Mask of direction IP destined

USHORT sourcePort;		// Port source
USHORT destinationPort; // Port destined

BOOLEAN drop;			// If TRUE, the bundle will be thrown in case of coincidence
}IPFilter, *PIPFilter;



// He structures to define the connected list of rules.
struct filterList
{
IPFilter ipf;

struct filterList *next;
};


// Head IP
typedef struct IPHeader 
{
UCHAR	 iphVerLen;	 // Version and length head
UCHAR	 ipTOS;		 // Type of service
USHORT	ipLength;	  // Entire length of the datagrama
USHORT	ipID;			 // Identification 
USHORT	ipFlags;		 // Flags
UCHAR	 ipTTL;		 // TTL
UCHAR	 ipProtocol;	 // Protocol of top level
USHORT	ipChecksum;	 // Checksum of the head
ULONG	 ipSource;	  // Direction source
ULONG	 ipDestination; // Direction destined
} IPPacket, *PIPPacket; 


// Head TCP
typedef struct _TCPHeader
{
USHORT			sourcePort;			// Port source
USHORT			destinationPort;	// Port destined
ULONG			sequenceNumber;		// Number of sequence
ULONG			acknowledgeNumber;	// Number of recognition
UCHAR			dataoffset;			// Leader to the information
UCHAR			flags;				// Flags
USHORT			windows;			// Size of the window TCP
USHORT			checksum;			// Checksum of the bundle
USHORT			urgentPointer;		// Puntero a los datos "urgentes"
} TCPHeader, *PTCPHeader;


// Cabecera UDP
typedef struct _UDPHeader
{
USHORT			sourcePort;			// Port source
USHORT			destinationPort;	// Port destined
USHORT			len;				// Length of the datagrama
USHORT			checksum;			// Checksum of the datagrama
} UDPHeader, *PUDPHeader;
Как-то оно тут все происходит... Не могу я толком разобратся(((

P.S
Не нашел я где репутацию поднимать, может не могу вовсе...

И снова-же...
Код:
#define DRVFLTIP_IOCTL_INDEX 0x830
Макрос какой-то или что? И к чему снова этот номер...
 
A

alexsid

#7
Код:
FILE_DEVICE_DRVFLTIP
Этож тип твоего драйвера - произвольно выбран
Код:
#define DRVFLTIP_IOCTL_INDEX 0x830
Это базовый номер для кодов ctl (которыми ты вызов функции запрашиваешь)
CTL_CODE--просто число (и составляется из чисел), которое кладется в определенное место irp-пакета. и используется для идентификации различных IRP пакетов

Код:
// I define the IOCTLs
#define START_IP_HOOK CTL_CODE(FILE_DEVICE_DRVFLTIP, DRVFLTIP_IOCTL_INDEX,METHOD_BUFFERED, FILE_ANY_ACCESS)

#define STOP_IP_HOOK CTL_CODE(FILE_DEVICE_DRVFLTIP, DRVFLTIP_IOCTL_INDEX+1, METHOD_BUFFERED, FILE_ANY_ACCESS)

#define ADD_FILTER CTL_CODE(FILE_DEVICE_DRVFLTIP, DRVFLTIP_IOCTL_INDEX+2, METHOD_BUFFERED, FILE_WRITE_ACCESS)

#define CLEAR_FILTER CTL_CODE(FILE_DEVICE_DRVFLTIP, DRVFLTIP_IOCTL_INDEX+3, METHOD_BUFFERED, FILE_ANY_ACCESS)
А тут они и определены

ващи инфы в нете навалом...
 
S

Sorrowing

#8
)) Это наверное последний фрагмент будет... Ато я уж и надоесть успел походу))))
Смотри.. Прога занимается преобразованием IP в правильную форму (это как я думаю). А как она это делает, особенно вот вторая часть... Глянь пожалуйста...
Код:
#include "stdafx.h"
#include "sockutil.h"
#include <stdlib.h>
#include <string.h>

/*++

Description:

It converts a chain Ip to network format

Arguments:

ip - chain that contains the direction ipstring that represent to ip address

If the chain does not have the correct format (x.x.x.x) he returns-1. If the octets
are minors of 0 or major than 255 0.0.0.0 returns direction.

Returned values:

ip in network format

--*/
int inet_addr(const char *sIp, unsigned long *lIp)
{
int octets[4];
int i;
const char * auxCad = sIp;
*lIp = 0;

// I extract each of the octets. Atoi extracts characters up to finding
// not numerical character, in ours '.'
for(i = 0; i < 4; i++)
{
octets[i] = atoi(auxCad);

if(octets[i] < 0 || octets[i] > 255)
return -1;

*lIp |= (octets[i] << (i*8));

// Update auxCad so that it points at the following octet
auxCad = strchr(auxCad, '.');

if(auxCad == NULL && i!=3)
return -1;

auxCad++;
}


return 0;
}



/*++

Description:

It changes the order of the octets. Major order to minor order and vice versa.

Arguments:

port - Number to turn


Returned values:

turned port

--*/
unsigned short htons(unsigned short port)
{
unsigned short portRet;

portRet = ((port << 8) | (port >> 8));

return portRet;
}

char *IpToString(char *ip, unsigned long lIp)
{
char octeto[4];

ip[0] = 0;

itoa(lIp & 0xff, octeto, 10);

strcat(ip, octeto);
strcat(ip, ".");


itoa((lIp >> 8) & 0xff, octeto, 10);

strcat(ip, octeto);
strcat(ip, ".");


itoa((lIp >> 16) & 0xff, octeto, 10);

strcat(ip, octeto);
strcat(ip, ".");

itoa((lIp >> 24) & 0xff, octeto, 10);

strcat(ip, octeto);


return ip;
}
 
Статус
Закрыто для дальнейших ответов.