23
The Dark Side of Winsock - Lectu re Notes (C) 2005 Jonathan Levin, All Rights Reserved 1 The Dark Side of Winsock By Jonathan Levin DefCon XIII, Las Vegas Http://www.securicy.net/Talks/dc-spi.pdf

The Dark Side of Winsock- Lecture Notes

Embed Size (px)

Citation preview

Page 1: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 1/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved1

The Dark Side of Winsock

By Jonathan Levin

DefCon XIII, Las Vegas

Http://www.securicy.net/Talks/dc-spi.pdf

Page 2: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 2/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved2

Introduction & Nomenclature

You probably already know this but…

IP communications are implemented using the socket API.

A socket is a transport endpoint, used to send/receive data.

The application reads from/writes to the socket, much as itwould to any other file descriptor

The OS transparently fragments/encapsulates the data.

This talk assumes you’ve seen sockets in action before. Be it in Stevens’legendary tomes (TCP/IP Illustrated, UNIX Network Programming..) orelsewhere.

Page 3: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 3/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved3

Introduction & Nomenclature

You probably already know this too, but…

In UNIX, sockets follow the Berkeley (BSD) model closely

Windows adapted the BSD socket API into WinSock:

Winsock 1.x was a close adaptation of the BSD API

Winsock 2.x added new features

- Asynchronous calls & callbacks- Overlapped I/O

- The layered service provider (LSP) architecture

(more)

Page 4: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 4/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved4

Introduction & Nomenclature

However, not too many people know that…

Winsock’s Layered Service Provider architecture providespowerful hooking functionality enabling interception,eavesdropping or rerouting of almost all IP based trafficin windows platforms.

(more)

This talk will focus on the LSP, presenting it’s useful

(legitimate) applications, and even more useful (but lesslegitimate) ones.

Page 5: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 5/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved5

Winsock 2 Architecture

Windows is designed in a scalable, multi-layered

architecture:

The Winsock 2 API provides the mainThe Winsock 2 API provides the main

entry point for applications. Theentry point for applications. The ““bodybody””

is responsible for multiplexing sockets.is responsible for multiplexing sockets.

The Transport Driver Interface (TDI) bridgesThe Transport Driver Interface (TDI) bridgescalls to the levels belowcalls to the levels below

The Network Driver Interface SpecificationThe Network Driver Interface Specification

(NDIS) serves to abstract the hardware, so(NDIS) serves to abstract the hardware, so

Multiple or different interfaces may be usedMultiple or different interfaces may be used

simultaneously.simultaneously.

NetBT

TDI

NDIS

Hardware

WKS

SRV

Winsock 2

API

NetBT (The NetBIOS over TCP/IP interface) is “reserved”, and is used bywindows’ Workstation and Server services (file and print sharing) to bypass

“traditional” winsock calls (and is out of our scope anyway).

All other (user mode) applications use winsock to communicate over the network.

Page 6: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 6/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved6

NetBT

TDI

NDIS

Hardware

WKS

SRV

Winsock 2

API

Winsock 2 Architecture

Transport SPI NameSpace SPI

WSock2_32.DLL

Winsock 2 API

Winsock 2 SPI

BaseProv n

BaseProv 1

Prov nProv……

While exporting the API, Winsock itself is a client of the SPI ,or service provider interface, exported to it by themiscellaneous service providers installed below it.

Providers may beProviders may be

classified as either:classified as either:

--TRANSPORTTRANSPORT

-- NAMESPACENAMESPACE

The Winsock DLL itself serves as a multiplexer for two types of providers:

- Transport Providers: Protocol stacks, that setup connections, and transferdata on the network, possibly supplying features such as QoS, error handling,etc.

Windows 2000 ships with two transports:

rsvpsp.dll – implementing RSVP QoS

mswsock.dll – implementing the Winsock core.

The provider is chosen upon socket creation, by the parameters to the Socket()

(or WSASocket()) call.

- NameSpace Providers: Naming services – suppliers of name resolutionmechanisms (e.g. implementations of getXXXbyYYY functions).

Winsock 2000 supports the TCP/IP, NT DS and NLA namespaces.

There can be more than one provider of any type. Winsock accesses theproviders by their interface, which is the Service Provider Interface, or SPI.

Page 7: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 7/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved7

Winsock 2 ArchitectureExport Goods (ws2_32.dll)

Winsock provides a potent API for installing custom providers, both namespace andtransport. In ws2spi.h:

int WSPAPI WSCInstallProvider(

IN LPGUID lpProviderId,

IN const WCHAR FAR * lpszProviderDllPath,

IN const LPWSAPROTOCOL_INFOW lpProtocolInfoList,

IN DWORD dwNumberOfEntries,

OUT LPINT lpErrno

);

int WSPAPI WSCDeinstallProvider(

IN LPGUID lpProviderId,

OUT LPINT lpErrno

);

Page 8: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 8/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved8

And the namespace ones:

INT WSPAPI WSCInstallNameSpace (

IN LPWSTR lpszIdentifier,

IN LPWSTR lpszPathName,

IN DWORD dwNameSpace,

IN DWORD dwVersion,

IN LPGUID lpProviderId

);

INT WSPAPI WSCUnInstallNameSpace (

IN LPGUID lpProviderId

);

The different header definitions (int vs. INT, and “Deinstall” vs. “Uninstall”) arelike that in the original ws2spi.h.

Page 9: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 9/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved9

Winsock 2 Providerssporder.exe

The sporder DLL and EXE,

from the platform SDK,enable enumeration of thevarious providers.

The above is a screen shot of the “SPOrder.EXE”, provided as part of theplatform SDK. This small utility displays the service providers registered under

winsock. Note both classes – “Service Providers” (i.e. Transport ServiceProviders) and “Name Resolution” (Namespace Service Providers).

Note each provider structure is quite detailed. The one shown here is for theAF_INET (0x02) address family protocol # 0x06 – better known as TCP.

Page 10: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 10/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved10

Sporder.dll

SPOrder.dll is a small DLL with insidious capabilities – it allows the reordering of serviceproviders, by exporting two functions: WSCWriteNameSpaceOrder , andWSCWriteProviderOrder . And, as one can deduce by the names – these rewrite the order of the

layered service providers – namespace and transport, respectively. A further look at the importtable sheds some light as to how that’s done – using the familiar ADVAPI32.DLL registryfunctions.

One needn’t look hard to understand how to use these functions - These functions are part of thePlatform SDK, and are defined in sporder.h:

int

WSPAPI

WSCWriteProviderOrder (

IN LPDWORD lpwdCatalogEntryId,

IN DWORD dwNumberOfEntries

);

int

WSPAPI

WSCWriteNameSpaceOrder (

IN LPGUID lpProviderId,

IN DWORD dwNumberOfEntries

);

Page 11: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 11/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved11

Winsock 2 ProvidersTransport providers may be enhanced by LAYERING

additional providers, and chaining them.

The base service providerstill handles the actualimplementation (i.e. sendingdata, etc.) but layered SPsmay be used for QoS,encryption, security, etc.

So long as all providers ina chain support SPI , anynumber of providersmay be chained.

Transport SPI NameSpace SPI

WSock2_32.DLL

Winsock 2 API

Winsock 2 SPI

LSPBaseProv 1

Prov nProv……

BaseProv 1

SPI

Page 12: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 12/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved12

Winsock 2 ProvidersEnumerating providers

int WSPAPI WSCEnumProtocols (IN LPINT lpiProtocols ,OUT LPWSAPROTOCOL_INFOW lpProtocolBuffer,IN OUT LPDWORD lpdwBufferLength,OUT LPINT lpErrno 

);

Usage: Retrieve information about available transport protocols.

Parameters:

lpiProtocols – NULL term. Array of iProtocols to enum, or NULL.lpProtocolBuffer – buffer of WSAPROTOCOL_INFOW structs

lpdwBufferLength – in/out parameter specifying sizeof..lpErrNo – Out parameter, holding error code, if any.

Returns: Number of enumerated protocols.

ws2spi.h

The following example demonstrates enumeration of the layered serviceproviders, and the WSAPROTOCOL_INFOW structs. Essentially, this is a CLIversion of sporder.exe from the platform SDK.

Note: it gets the job done. It’s not an example of pretty or “right” coding.

/**

* Winsock 2 API Protocol Enumerator - By [email protected]

* (Standards disclaimers apply)

*/

#ifndef WIN32_LEAN_AND_MEAN

#define WIN32_LEAN_AND_MEAN

#endif

#define WINSOCK_API_LINKAGE

#include <winsock2.h>

#include <ws2spi.h>

#include <wtypes.h>

#include <assert.h>

#include <winnt.h>

#include <stdlib.h>

#include <stdio.h>

Page 13: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 13/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved13

char *ExpandServiceFlags(DWORD serviceFlags)

{

/* A little utility function to make sense of all those bit flags *//* The following code leaks. Yeah, I know.. Go find Buffer 0v3rfl0w$ :-) */

char *serviceFlagsText = (char *) malloc (2048);

memset (serviceFlagsText, '\0', 2048);

char *strip_comma;

/* Hey - it's only for printing and demo purposes.. */if (serviceFlags & XP1_CONNECTIONLESS)

{

strcat (serviceFlagsText, "Connectionless, ");

}

if (serviceFlags & XP1_GUARANTEED_ORDER)

{

strcat (serviceFlagsText, "Guaranteed Order, ");

}

if (serviceFlags & XP1_GUARANTEED_DELIVERY)

{

strcat (serviceFlagsText, "Message Oriented, ");

}

if (serviceFlags & XP1_MESSAGE_ORIENTED)

{

strcat (serviceFlagsText, "Message Oriented, ");

}

if (serviceFlags & XP1_CONNECT_DATA )

{

strcat (serviceFlagsText, "Connect Data, ");

}

if (serviceFlags & XP1_DISCONNECT_DATA )

{

strcat (serviceFlagsText, "Disconnect Data, ");

}

if (serviceFlags & XP1_SUPPORT_BROADCAST )

{

strcat (serviceFlagsText, "Broadcast Supported, ");

}

if (serviceFlags & XP1_EXPEDITED_DATA )

{

strcat (serviceFlagsText, "Urgent Data, ");

}

if (serviceFlags & XP1_QOS_SUPPORTED )

{

strcat (serviceFlagsText, "QoS supported, ");

}

/** While we're quick and dirty, let's get as dirty as possible..*/strip_comma = strrchr(serviceFlagsText,',');

if (strip_comma)

*strip_comma = '\0';

return (serviceFlagsText);

}

Page 14: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 14/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved14

void PrintProtocolInfo (LPWSAPROTOCOL_INFOW prot)

{

wprintf (L"Protocol Name: %s\n",prot->szProtocol); /* #%^@$! UNICODE...*/

printf ("\tServiceFlags1: %d (%s)\n",

prot->dwServiceFlags1,

ExpandServiceFlags(prot->dwServiceFlags1));

printf ("\tProvider Flags: %d\n",prot->dwProviderFlags);

printf ("\tNetwork Byte Order: %s\n",

(prot->iNetworkByteOrder == BIGENDIAN) ? "Big Endian" : "Little Endian");

printf ("\tVersion: %d\n", prot->iVersion);

printf ("\tAddress Family: %d\n", prot->iAddressFamily);

printf ("\tSocket Type: ");

switch (prot->iSocketType)

{

case SOCK_STREAM:

printf ("STREAM\n");

break;

case SOCK_DGRAM:

printf ("DGRAM\n");

break;

case SOCK_RAW:

printf ("RAW\n");

break;

default:

printf (" Some other type\n");

}

printf ("\tProtocol: ");

switch (prot->iProtocol)

{

case IPPROTO_TCP:

printf ("TCP/IP\n");

break;

case IPPROTO_UDP:

printf ("UDP/IP\n");

break;

default:

printf ("some other protocol\n");

}

}

Page 15: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 15/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved15

And finally, the main:

int _cdecl main( int argc, char** argv)

{

LPWSAPROTOCOL_INFOW bufProtocolInfo = NULL;

DWORD dwSize = 0;

INT dwError;INT iNumProt;

/*

* Enum Protocols - First, obtain size required

*/

printf("Sample program to enumerate Protocols\n");

WSCEnumProtocols(NULL, // lpiProtocols

bufProtocolInfo, // lpProtocolBuffer

& dwSize, // lpdwBufferLength

& dwError); // lpErrno

bufProtocolInfo = (LPWSAPROTOCOL_INFOW) malloc(dwSize);

if (!bufProtocolInfo){

fprintf (stderr,"SHOOT! Can't MALLOC!!\n");

exit(1);

}

/* Now, Enum */

iNumProt = WSCEnumProtocols(

NULL, // lpiProtocols

bufProtocolInfo, // lpProtocolBuffer

&dwSize, // lpdwBufferLength&dwError);

if (SOCKET_ERROR == iNumProt)

{

fprintf(stderr,"Darn! Can't Enum!!\n");

exit(1);

}

printf("%d Protocols detected:\n", iNumProt);

for (int i=0;

i < iNumProt;

i++){

PrintProtocolInfo(&bufProtocolInfo[i]);

printf ("-------\n");

}

printf("Done");

return(0);

}

Page 16: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 16/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved16

Winsock 2 ProvidersSo you want to build your own LSP?

int WSPStartup (IN WORD wVersionRequested,OUT LPWSPDATAW lpWSPData,IN LPWSAPROTOCOL_INFOW lpProtocolInfo,IN WSPUPCALLTABLE UpcallTable,OUT LPWSPPROC_TABLE lpProcTable );

Initialize layered service providerUsage:

Parameters:wVersionRequested – q.v. WSAStartup.

lpWSPData – layered service provider data, you should populatelpProtocolInfo – protocol details. Useful if hooking multiple protocolsUpcallTable – dispatch table for winsock callslpProcTable - our implemented calls.

Returns: No error, hopefully..

Start by implementing WSPStartup()

Implementing a Layered Service Provider isn’t as hard as it might seem. Basically, all it takes is toadhere to a set API, and manipulate some function pointers. Winsock Layered service providersare implemented as standard DLLs, exporting the WSPStartup() function:

The WSPStartup() is expected to:

- Set the Version info:

(i.e. lpWSPData->wVersion = MAKEWORD(2,2);

lpWSPData->wHighVersion = MAKEWORD(2,2);

wcscpy(lpWSPData->szProtocol, L”My Name”); )

- Save the UpCallTable: for future use

- Populate the lpProcTable to the addresses of the local WSP functions

(e.g. - lpProcTable->lpWSPAccept = WSPAccept; 

lpProcTable->lpWSPConnect = WSPConnect; 

lpProcTable->lpWSPSend = WSPSend; …)

- Return NO_ERROR

Page 17: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 17/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved17

Winsock 2 ProvidersAPI->SPI Mapping

Most Winsock2 API functions are mapped to correspondingSPI functions, with the simple rule of WSA*WSP*.

Once a WSA* function is called, Winsock 2 will call thecorresponding WSP function, from the provider chain, inorder.

ALL functionality can be hijacked – getpeerbyname,setsockopt.. AddresstoString, etc.

Call Upcall table function to enable passthrough.

Functions NOT implemented in the SPI:

Event Handling Functions:

WSACreateEvent,

WSACloseEvent,

WSASetEvent,

WSAResetEvent

WSAWaitForMultipleEvents

Naming Services functions:GetXXXByYYY and their WSAAsync counterparts.

ntohs, ntohl, htonl, htons

inet_XtoY, inet_addr, ...

As well as:

WSAEnumProtocols – Enumerating service providers

WSAIsBlocking,

WSASetBlockingHook,

WSAUnhookBlockingHook

Page 18: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 18/23

Page 19: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 19/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved19

Winsock 2 SPIDemo

The demo shown is a nearly unmodified version of theINTC/MSFT source code provided in the platform SDK.

Page 20: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 20/23

Page 21: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 21/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved21

Winsock 2 SPIGood Vs. Bad

Possible (lawful goody-goody) uses include:

- Implement a user-mode application layer firewall(rather than work at TDI/NDIS, be socket-aware)

- transparently add encryption to applications(but then, there’s IPSec)

- Support new protocols(IPv9, anyone? (RFC1606) (for future use: RFC 1149?))

- Enforce QoS(s/Q/D)

- Patch content on the fly (q.v. Google Desktop)(A double edged sword)

Page 22: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 22/23

The Dark Side of Winsock- Lecture Notes

(C) 2005 Jonathan Levin, All Rights Reserved22

Winsock 2 SPILet’s just stick with the BAD

But the MUCH better (chaotic evil) uses include:

- Obtain connection statistics, URLs, etc.

(for spyware, statistical purposes, or whatever)

- Eavesdropping (non SSL) connections

(all socket based communication (inc. raw))

- Rerouting connections (i.e. socket hijacking)

The Dark Side has never been so tempting before..

- Patch content on the fly (q.v. Google Desktop)

(for obvious uses)

Page 23: The Dark Side of Winsock- Lecture Notes

8/14/2019 The Dark Side of Winsock- Lecture Notes

http://slidepdf.com/reader/full/the-dark-side-of-winsock-lecture-notes 23/23

The Dark Side of Winsock- Lecture Notes

The End…

(or perhaps, the beginning?)

Questions/Comments Welcome:

[email protected]