Forum Replies Created
-
AuthorPosts
-
Я уже спрашивал, так правильно будет перехватывать?
Да
Ну и соответственно и контекст еще так же присвоить…
Да
А еще, подскажете пожалуйста как в драйвере хранить список
Можешь свой список сделать. Можешь использовать встроенные односвязные или двухсвязные. Смотри функции:
InitializeListHead, ExInterlockedInsertHeadList, ExInterlockedInsertTailList, ExInterlockedRemoveHeadList, ExInterlockedPopEntryList, ExInterlockedPushEntryList, InsertHeadList, InsertTailList, IsListEmpty, KeInitializeSpinLock, PopEntryList, PushEntryList, RemoveEntryList, RemoveHeadList, RemoveTailListЧто-то я не пойму.. а как тогда хранить для каждого address object свой оригинал callback функции? и потом еще в самой callback функции определять какой оригинал вызывать..
Честно говоря, если после моего предыдущего пояснения остались вопросы, то может тогда не стоит и браться за подобный проект? Лучше возьмите за основу что-нибудь готовое, иначе на написание первого стабильного драйвера потратите уйму времени Да и TDI в Vista уже depreciated, так что стоит ли напрягаться…
🙄Распишу что я имел ввиду. Для каждого address object аллокируем некую структуру, которую храним у себя например в списке. В этой структур помимо прочих полей, которые могут понадобится, мы сохраняем оригинальный адрес ClientEventReceive и оригинальный контекст, который должен быть в нее передан. В обработчике TDI_SET_EVENT_HANDLER с TDI_EVENT_RECEIVE подменяем оригинальную ClientEventReceive и контекст заменяем на адрес той структуры, которая у нас оборачивает address object. Соответсвенно, в новом обработчике ClientEventReceive имеем указатель на структуру с оригинальным обработчиком и контекстом. Теперь понятно? 8)
IrpSp->FileObject
Pointer to an open file object representing a local-node address. The transport uses the FsContext and, possibly, FsContext2 fields to access the state it maintains about this address.
Depending on the type of ClientEventXxx handler to be registered, this address might be or become associated with an established endpoint-to-endpoint connection made by this client.Хендлеры ставятся в контексте address object, то есть сохранять подменять нужно не для разных потоков, а для разных address object.
IrpSp->Parameters
Pointer to a TDI_REQUEST_KERNEL_SET_EVENT structure, defined as follows:
struct _TDI_REQUEST_KERNEL_SET_EVENT {
LONG EventType;
PVOID EventHandler;
PVOID EventContext;
} TDI_REQUEST_KERNEL_SET_EVENT, *PTDI_REQUEST_KERNEL_SET_EVENT;
The transport uses the members of this structure as follows:EventType
Specifies the type of ClientEventXxx handler to be registered (see Comments).
EventHandler
Specifies the entry point of the ClientEventXxx routine to be called when this type of event occurs. This member can be NULL if the client is deregistering a previously registered event handler.
EventContext
Specifies a pointer to be passed, uninterpreted by the transport, to the given ClientEventXxx routine whenever it is called. This member is NULL if EventHandler is NULL.Можно подменить EventContext на некую собственную структуру оборачивающую address object и содержащую указатель на оригинальный ClientEventReceive.
P.S. А вообще вместо изобретения велосипеда стоило заглянуть в Resources и сходить по ссылке http://sourceforge.net/projects/tdifw
Во-первых, до того как будет вызван оригинальный обработчик никаких данных в IRP TDI_RECEIVE нет и быть не может, так как IRP перехвачен на пути от приложения к сети, а не наоборот. Так можно только TDI_SEND поймать.
Ну а во вторых, большинство TDI клиентов используют не IRPs с TDI_RECEIVE, а устанавливают callbacks на события с использованием TDI_SET_EVENT_HANDLER (в случае с receive это ClientEventReceive). В DDK все написано.
Ну так а что сделано чтобы получать входящий траффик? Обычно входящие данные идут через callbacks, соответственно нужно перехватывать их установку.
ЗЫ К суппорту тема не имеет отношения, для подобных вопросов есть отдельная борда Windows Internals
ЗЗЫ Тему отредактировал, следите за кодировкой…
Еще небольшой вопросик, в поставке за 3500 $ входят исходники NDIS IM драйвера?
Да, конечно.
Собственно говоря, драйвера разделяют значительный обьем кода между собой. При разработске kernel mode решения это удобно, так как можно расширять этот общий код и при условии использования некотрых ограничений писать кроссплатформенный код.
Ну данная метода мне известна, просто подразумевается что софт будет работать и на 2К.
В принципе в Windows 2000 есть возможность получить такую же табличку как и в Windows XP+ с использованием некоторого количества недокументированных структур. Детали правда я уже не помню, но можно поискать/восстановить.
В догонку тогда еще вопрос. Как с помощью вашего драйвера отбросить ИСХОДЯЩЕЕ соединение например на какойто порт?
Пропарсить заголовки исходящего пакета и если окажется что это TCP SYN пакет на тот порт, что иы хотим заблокировать, то просто не возврашать пакет стеку.
TDI filter илм LSP, но вообще говоря таблицу активных соединений с PID можно получить у стека и без дополнительных усилий начиная с Windows XP.
ЗЫ Название темы подправип, беда с этими кодировками…
But on 2000 I have only SectionHandle and that handle is valid in the HANDLE_TABLE of corresponding process not in process in the context of which my driver is getting called.
KeAttachProcess/KeDetachProcess should help 8)
You could use LSP for this. Probably this is the most suitable solution in this case.
Can you direct me to any websites that document the shifting of the SEQ and ACK fields. Also is shifting a set incremental value or is it based on the content of the packet?
I don’t think you will be able to find this sort of information anywhere. The only thing I can suggest is reading some good description of TCP protocol (by R. Stevens http://www.kohala.com/start/ an example).
Yes there is last field EPROCESS block which points to a UNICODE_STRING which gives me the FullPathName , but still I am not able to get the Drive Letters form there.
You have not explained in what form you get full path name here and I supposed you have got volume device name instead drive letter. Seems I got wrong 😳
Anyways, why won’t you use the approach I posted above in this thread:
1. Obtain EPROCESS pointer through IoGetCurrentProcess().
2. For NT 4.0 and 5.0 take section handle from EPROCESS(SectionHandle) and using ObReferenceObjectByHandle() we obtain SectionObject; for NT 5.1 we can take SectionObject from EPROCESS directly.
3. From SectionObject we obtain SegmentObject.
4. From SegmentObject we obtain ControlArea.
5. From ControlArea we obtain FilePointer (this is FileObject pointer).
6. Using ObQueryNameString() we obtain full process name
All operations should be performed on PASSIVE_LEVEL and in the context of the process we obtain full path for.This one is proved to work.
Yes there is last field EPROCESS block which points to a UNICODE_STRING which gives me the FullPathName , but still I am not able to get the Drive Letters form there.
Drive letter is a symbolic link to disk object, so you can enumerate symbolic links to get the exact mappings.
I had one more query ,what does DEVICEMAP field in EPROCESS strucure signify…?
Devicemap is used when object manager sees a name beginning from ?? for getting the object directory to use for the particular process.
Using my intercepting application, can I send a tcp request to one of the two applications by filling the Request.EthPacket.Buffer with a new packet that I create and then send it using SendPacketToMstcp or SendPacketToAdapter?
Yes, you can. However, please note that injecting data into the TCP stream is not as easy as it may seem at the first look, because you should properly shift SEQ and ACK fields in your newly inserted packet and all sequent packets.
Would either application be able to tell that the packet didn’t originate from the application it is connected to?
If packet is injected properly then it won’t.
'Dump packet size
sOut = sOut & vbTab & "Packet size = " & PacketBuffer.m_Length & vbCrLf
CopyMemory EthHeader, PacketBuffer.m_IBuffer(0), Len(EthHeader)
The code above is taken from VB passthru sample. Here PacketBuffer.m_IBuffer array contains the entire packet, you can dump it if necessary.
-
AuthorPosts