安全測試學習筆記_第1頁
安全測試學習筆記_第2頁
安全測試學習筆記_第3頁
安全測試學習筆記_第4頁
安全測試學習筆記_第5頁
已閱讀5頁,還剩209頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領

文檔簡介

安全領域Microsoft.Press《Hunting.Security.Bugs》DEMO網(wǎng)站-AltoroJ.war初學者模擬黑客闖關網(wǎng)站http://www.try2hack.nl/第一關:http://www.try2hack.nl/level1.html查看源文件,有下面的內(nèi)容:<SCRIPTLANGUAGE="JavaScript">functionTry(passwd){if(passwd=="hackerzzz"){alert("Alright!Ontolevel2...");location.href="levvel2.html";第二關:http://www.try2hack.nl/levvel2.html查看源文件,注意這句:<EMBEDsrc="FlashLevel2.swf"quality=highbgc,所以到http://www.try2hack.nl/FlashLevel2.swf試下,然后用netant或flashget把文件到本地,用ultraedit打開,可以看到有下面的字符串:Try2Hack,NokiaIsGood等,試user=Try2Hack,pawd=NokiaIsGood,passed.也可以用FlashDeCompiler之類的Flash反編譯工具來查看FlashDeCompiler可從FLASH文件swf中提取所有資源的工具軟件。包括:聲音、圖像、視頻、圖形、幀畫面、文本、字體、按鍵、圖標及動作腳本。irtehh4x0r!第三關:http://www.try2hack.nl/LLeVeLL3.html一開始就跳出密碼框,查不到源文件,但cancel,然后stop,可以查到以下:<SCRIPTlanguage="JavaScript">pwd=prompt("Pleaseenterthepasswordforlevel3:","");if(pwd==PASSWORD){alert("Alright!\nEnteringLevel4...");location.href=CORRECTSITE;}else{alert("WRONG!\nBacktodisneyland!!!");location.href=WRONGSITE;}PASSWORD="AbCdE";CORRECTSITE="level4.html";WRONGSITE="";里面沒有所要的密碼.嗯,到本機的TemporaryInternetFiles目錄下查下最新的文件,有一JavaScript的文件,正好是這網(wǎng)站的,把它copy出來,打開,看到PASSWORD="TheCorrectAnswer";CORRECTSITE="thelevel4.html";WRONGSITE="";成功了!查看源文件:<scripttype="text/javascript"src="JavaScript"></script>訪問http://www.try2hack.nl/levels/JavaScript得到密碼:try2hackrawks第四關:http://www.try2hack.nl/thelevel4.html很明顯,是Javaapplet程序,把他下載下來:http://www.try2hack.nl/PasswdLevel4.class,用java反編譯軟件,我用jad.exe來反編譯.jad-fPasswdLevel4.class,得到PasswdLevel4.jad文件,用Notepad打開,這句查對passwd和user的:if(txtlogin.getText().trim().toUpperCase().intern()==inuser[2*(i-1)+2].trim().toUpperCase().intern()&&txtpass.getText().trim().toUpperCase().intern()==inuser[2*(i-1)+3].trim().toUpperCase().intern()),而inuser是從下面這段程序讀進來的:countConn=inURL.openStream();countData=newjava.io.BufferedReader(newjava.io.InputStreamReader(countConn));java.lang.Strings;while((s=countData.readLine())!=null)if(totno<21){totno=totno+1;inuser[totno]=s;s="";}else{lblstatus.setText("CannotExceed10users,Appletfailstart!");destroy();}inuser又從inURL來,infile=newjava.lang.String("level4");try{inURL=new.URL(getCodeBase(),infile);}所以密碼文件為http://www.try2hack.nl/level4,用flashget下載,有5_level_5.htmlTry2HackAppletsAreEasyhttp://www.try2hack.nl/levels/level4level5-fdvbdf.xhtmlappletkingpieceofcake第五關:http://www.try2hack.nl/5_level_5.html下載,解壓,看到有VBRun300.dll就知道應該是VB3的文件,用VB反編譯工具,可得到level5.bas,查看有以下查對passwd的語句:IftxtUsername<>Mid(mc001A,56,1)&Mid(mc001A,28,1)&Mid(mc001A,35,1)&Mid(mc001A,3,1)&Mid(mc001A,44,1)&Mid(mc001A,11,1)&Mid(mc001A,13,1)&Mid(mc001A,21,1)ThenMsgBox"Usernamenotaccepted."ExitSubEndIfIftxtPassword<>Mid(mc001A,51,1)&Mid(mc001A,31,1)&Mid(mc001A,30,1)&Mid(mc001A,51,1)&Mid(mc001A,16,1)&Mid(mc001A,45,1)&Mid(mc001A,24,1)&Mid(mc001A,29,1)&Mid(mc001A,26,1)&Mid(mc001A,19,1)&Mid(mc001A,28,1)&Mid(mc001A,11,1)&Mid(mc001A,30,1)&Mid(mc001A,19,1)&Mid(mc001A,25,1)&Mid(mc001A,24,1)Then而Constmc001A="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,:;-*+=~|&!_$#@()[]{}<\/>"可知是從該字串相應位置的字符組成passwd和user,如Mid(mc001A,56,1)="T",可得user:Try2Hackpwd:OutOfInspiration又過了!參考:/html/200310/20031007QBI141805.htmlVB3runtime:/kb/196285下載VB反編譯工具VBDeCompiler(vb23decomp.zip),支持VB3.0'LEVEL5.FRMOptionExplicitSubcmdLogin_Click()IfedtUsername=Mid(gc0006,56,1)&Mid(gc0006,28,1)&Mid(gc0006,35,1)&Mid(gc0006,3,1)&Mid(gc0006,44,1)&Mid(gc0006,11,1)&Mid(gc0006,13,1)&Mid(gc0006,21,1)ThenIfedtPassword=Mid(gc0006,45,1)&Mid(gc0006,48,1)&Mid(gc0006,25,1)&Mid(gc0006,32,1)&Mid(gc0006,15,1)&Mid(gc0006,40,1)&Mid(gc0006,25,1)&Mid(gc0006,14,1)&Mid(gc0006,19,1)ThenMsgBox"Level6canbefoundat:"&Left$(gc000A,37)&Mid(gc0006,21,1)&Mid(gc0006,14,1)&Mid(gc0006,29,1)&Mid(gc0006,32,1)&Mid(gc0006,12,1)&Mid(gc0006,14,1)&Mid(gc000A,44,6),0,"Horray!"EndEndIfEndIfMsgBox"Invalidusernameand/orpassword!",0,"ERROR!"EndSubSubForm_Load()Me.Move(Screen.Width-Me.Width)/2,(Screen.Height-Me.Height)/2EndSub寫個VBS文件自動顯示出來:gc0006="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,:;-*+=~|&!_$#@()[]{}<\/>"gc000A="http://www.try2hack.nl/levels/level6-ksghvb.xhtml"edtUsername=Mid(gc0006,56,1)&Mid(gc0006,28,1)&Mid(gc0006,35,1)&Mid(gc0006,3,1)&Mid(gc0006,44,1)&Mid(gc0006,11,1)&Mid(gc0006,13,1)&Mid(gc0006,21,1)MsgboxedtUsernameedtPassword=Mid(gc0006,45,1)&Mid(gc0006,48,1)&Mid(gc0006,25,1)&Mid(gc0006,32,1)&Mid(gc0006,15,1)&Mid(gc0006,40,1)&Mid(gc0006,25,1)&Mid(gc0006,14,1)&Mid(gc0006,19,1)MsgboxedtPasswordurl=Left(gc000A,37)&Mid(gc0006,21,1)&Mid(gc0006,14,1)&Mid(gc0006,29,1)&Mid(gc0006,32,1)&Mid(gc0006,12,1)&Mid(gc0006,14,1)&Mid(gc000A,44,6)MsgboxurlMsgBox"Level6canbefoundat:"&Left(gc000A,37)&Mid(gc0006,21,1)&Mid(gc0006,14,1)&Mid(gc0006,29,1)&Mid(gc0006,32,1)&Mid(gc0006,12,1)&Mid(gc0006,14,1)&Mid(gc000A,44,6),0,"Horray!"http://www.try2hack.nl/levels/level6-kdsvbd.xhtmlwww.try2hack..nl(是一個讓初學黑客技術的人去做實驗的站點)打開這個頁面,有http://www.try2hack.nl/cgi-bin/level7.pl頁面(這個網(wǎng)站提供了黑客的8關,過了這8關證明你開始入門了),這個頁面告訴我們的瀏覽器不是IE6.72,我們的操作系統(tǒng)不是LIUNX,我們不是從/ms.htm重定向鏈接過去的,有病阿(這是一個題目呀,要慢慢研究),linux有IE6.72?微軟會在它的頁面上放http://www.try2hack.nl/cgi-bin/level7.pl的鏈接?看看頁面的源代碼,level7.pl是在服務器端執(zhí)行的perl腳本,根本無法看到,還是研究一下IE5和它通信時都告訴了它什么,抓包,我們會發(fā)現(xiàn),我們的IE5告訴對方:我是MSIE5.0;WindowsNT5.0;.NETCLR1.0.3705。。。。哈哈,level7.pl這個cgi應該是根據(jù)這些信息知道我們不是它要求的客戶,嘿嘿,需要欺騙對方才行,用軍刀來可以實現(xiàn),如下做就可以哄對方了:ncwww.try2hack.nl80[enter]GET/cgi-bin/level7.plHTTP/1.1[enter]Accept:image/gif,image/x-xbitmap,application/msword,*/*[enter]Referer/ms.htm[enter]Accept-Language:zh-cn[enter]Accept-Encoding:gzip,deflate[enter]User-Agent:Mozilla/4.0(compatible;MSIE6.72;Linux8.8.8i986)[enter]Host:www.try2hack.nl[enter]Connection:Keep-Alive[enter]注意,如果出現(xiàn)HTTP400時,說明你輸入格式有問題,出現(xiàn)httpd200回應時,就給出結果了:哈哈!趕快去實現(xiàn)一下(實踐是成功之母)參考:/xuefang2402/archive/2008/02/28/2128926.aspxWEB安全傳統(tǒng)WEB應用程序AJAXSecurityIssuesSurroundingAJAX——AJAX正在為心懷惡意的hacker打開著后門。但這并不完全正確:多數(shù)web站點都是不安全,但AJAX并傳統(tǒng):AJAX:AjaxEmpowersXSS適用于WEB應用的質(zhì)量模型OWASPTheOpenWebApplicationSecurityProject(OWASP)/index.php/Main_Page軟件安全漏洞據(jù)CERT/CC統(tǒng)計,該組織2007年收到報告并確認的信息系統(tǒng)安全漏洞共計7236個,平均接近20個。1995年到2007,報告的安全漏洞總數(shù)達到38016個,最新的統(tǒng)計結果如下圖所示:圖1.安全漏洞數(shù)統(tǒng)計示意圖今天軟件安全問題增長的原因:Connectivity(互聯(lián)性):互聯(lián)網(wǎng)無處不在,系統(tǒng)全在上面?;ヂ?lián)網(wǎng)在使人們使用軟件變得方便的同時,也給黑客們更好的機會,給人們的軟件帶來了更多的風險?;ヂ?lián)網(wǎng)意味著,黑客隨時隨地都可以訪問我們的軟件系統(tǒng),公共的訪問平臺使我們不能夠分別出哪些是真正的用戶,哪些是黑客。這樣他們比過去有了更多的時間和空間來攻擊我們的系統(tǒng),如果我們的軟件中一點兒安全的缺陷,他們就能夠知道,并利用之來攻擊。Extensibility(擴展性):使攻擊系統(tǒng)的方式變得不可預測。現(xiàn)在的軟件應用系統(tǒng)趨向可擴展化,可擴展的系統(tǒng)可以接受更新或擴展,許多時候依賴于動態(tài)的代碼,使得系統(tǒng)的功能得到擴展,更好滿足人們的需求。如:Plug-In架構的Web瀏覽器使得我們可以隨意地安裝我們需要的文檔格式的閱讀器:Word,Excel,PDF等。今天操作系統(tǒng)通過動態(tài)的裝載設備驅(qū)動和模塊來支持可擴展。今天的應用系統(tǒng),如:word文字處理,E-mail客戶端,Web瀏覽器等都通過scripting,controls,components和applets來支持可擴展性。但擴展性給軟件的安全帶來了,很大的挑戰(zhàn),Complexity(復雜性)互聯(lián)網(wǎng),分布式,動態(tài)的代碼?,F(xiàn)在的軟件應用系統(tǒng)的變得越來越大,復雜性也越來越大,操作系統(tǒng)從DOS到今天的WindowsXP,XP的代碼最少4000億行。復雜度可想可知。而現(xiàn)在的基于網(wǎng)絡的應用系統(tǒng),為了達到更高運算速度,承載很大訪問量,就使用分布式,集群,可擴展架構。使我們軟件代碼數(shù)急劇增長。復雜度也越來越大。軟件安全隱患也越來越大。繞過權限控制國軍標PDF文檔系統(tǒng)從IE歷史中訪問并下載QQ空間搜索加密相冊《非安全黑客手冊》200901后來騰訊已經(jīng)把QQ空間的搜索從搜搜中撤掉了:黑客很少從門直入,一般都跳窗而入。這個例子也體現(xiàn)了騰訊在做產(chǎn)品的集成測試方面存在遺漏。從漏洞知識中學習通過研究那些與你所測試的程序相類似的程序漏洞,你將熟悉那些可能發(fā)現(xiàn)的安全問題。/vulnerabilities//vuldb/HowHackersuseGoogletoQuicklyFind&ExploitVulnerableSitesGoogleHacking的實現(xiàn)以及應用/article/51.htm查找網(wǎng)站中的asp頁面:site:filetype:asp找文件allinurl:winntsystem32可以用google來搜索數(shù)據(jù)庫文件,用上一些語法來精確查找能夠獲得更多東西(access的數(shù)據(jù)庫,mssql、mysql的連接文件等等):allinurl:bbsdata

filetype:mdbinurl:database

filetype:incconn

inurl:datafiletype:mdb

intitle:"indexof"data//在一些配置不正確的apache+win32的服務器上經(jīng)常出現(xiàn)這種情況/ghdb/filetype:xlsusernamepasswordemailThissearchshowsMicrosoftExcelspreadsheetscontainingthewordsusername,passwordandemail.Bewarethatthereareatonofblank“template”formstoweedthrough,butyoucantellfromtheGooglesummarythatsomeofthesearewinners…errlosers..dependingonyourperspective.漏洞分類(1)InputValidationandRepresentation

BufferOverflows

CommandInjection

Cross-SiteScripting(XSS)Flaws

FormatStringProblems

IntegerRangeErrors

SQLInjection

(2)APIAbuse

TrustingNetworkAddressInformation

DangerousFunction

DirectoryRestriction.

HeapInspection

(3)SecurityFeatures

FailingtoProtectNetworkTraffic

FailingtoStoreandProtectData

FailingtoUseCryptographicallyStrongRandom

Numbers

ImproperFileAccess

ImproperUseofSSL

UseofWeakPassword-BasedSystems

UnauthenticatedKeyExchange

(4)TimeandState

SignalRaceConditions

Useof“Magic”URLsandHiddenForms

(5)Errors

FailuretoHandleErrors

CatchNullPointerException

EmptyCatchBlock

Overly-BroadCatchBlock

Overly-BroadThrowsDeclaration.

(6)CodeQuality

PoorUsability

DoubleFree.Callingfree()

InconsistentImplementations

MemoryLeak

NullDereference

(7)Encapsulation

InformationLeakage

ComparingClassesbyName

DataLeakingBetweenUsers

LeftoverDebugCode

TrustBoundaryViolation

(8)Environment

InsecureCompilerOptimization

ASP.NETMisconfiguration:CreatingDebugBinary;MissingCustomErrorHandling

PasswordinConfigurationFile

J2EEMisconfiguration:

InsecureTransport

;

InsufficientSession-IDLength

MissingErrorHandling

;UnsafeBeanDeclaration

WeakAccessPermissions嵌入式軟件安全測試處理系統(tǒng)安全需求的最佳方法是在設計階段就開始監(jiān)督。安全分析技術:FMEA(故障模型及后果分析)、FTA(故障樹分析)故障樹分析(FTA)被用來確定故障的原因。軟件安全開發(fā)生命周期(1)CodeReview(代碼重審)

(2)Architectureriskanalysis(軟件架構風險分析)

(3)Penetrationtesting(滲透測試)

(4)Risk-basedsecuritytests(基于風險的安全測試)

(5)AbuseCase(最壞情況處理)

(6)securityrequirements(安全的需要)

(7)securityoperations(安全操作)SDLC電子商務系統(tǒng)安全滲透測試的類型"Intheend,it'snotthehackersthataredangerous.It'sthesecuritydefectsinourowncode."1、白盒2、黑盒vulnerabilityAssessment->PenetrationTesting攻擊的類型安全測試方法學OSSTMMNISTSP800-42TRAWGOCTAVE安全審計“踩點”-漏洞識別、威脅識別、reconnaissanceWHOISsamspade、googleSuperScanFoundstoneSuperScan/us/resources-free-tools.aspNMAPbacktrack中也包含了NMAPNessusD:\Security_安全\Tools\NessusX-SCAN好像掃描不了其他機器,對本機的掃描則沒問題:BufferOverflow(緩沖區(qū)溢出)緩沖區(qū)溢出的例子://BufferOver.cpp:Definestheentrypointfortheconsoleapplication.//#include"stdafx.h"#include"string.h"boolcheck_login(char*name){ intx=0; charsmall_buffer[10]; if(strcmp(name,"admin")==0) x=1; strcpy(small_buffer,name); if(x>0) { printf("loginasadmin!\n"); returntrue; } else { printf("loginascommonuser!\n"); returnfalse; }}voidPrintASCII(){ for(inti=0;i<=127;i++) { printf("%d--%c",i,(char)i); if(i%5==0)printf("\n"); }}intmain(intargc,char*argv[]){ //PrintASCII(); char*name="123456789aaaa"; //char*name=argv[1]; intres=check_login(name); printf("%d\n",res); return0;}NoncodeExecutionOverflowsCanBeSerious,TooSometimesattackersfindotherwaystoexploitoverflowsbesidesgettingtheircodetorun,andnotallseriousoverflowsthrowexceptions.Certainoverflowsdonotallowattackerstotakecontrol,butmightinsteadallowthemtoreadormanipulateextradata.SuchisthecaseofLogon.exe,autilitythatenablesadministratorstologontoaservice.Becausethepasswordiscryptographicallyrandomeachtime,itisprettyhardtoguess.Loggingonwithoutknowingthepasswordrequireseitherlookinginmemory(weassumethisisofflimits)orbeingcrafty.Let’sseehowthisworks.Notethatthetextinboldtypeisuserinputforthewalkthrough.E:\Chapter8\Code\Logon\Debug>Logon.exeUSAGE:Logon.exe<username><password>Tryenteringbogusparameters:E:\Chapter8\Code\Logon\Debug>Logon.exeUserPasswordAccessDenied.Thenstarttryinglongstrings:E:\Chapter8\Code\Logon\Debug>Logon.exeaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAccessDenied.E:\Chapter8\Code\Logon\Debug>Logon.exeaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAccessDenied.E:\Chapter8\Code\Logon\Debug>Logon.exeaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaWelcome!!Youarenowloggedinasa.That’sabitstrange—theserviceletyoulogonbyusingallletteracharacters.Checkwhetherithappensagain:E:\Chapter8\Code\Logon\Debug>Logon.exeadddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddWelcome!!Youarenowloggedinasa.Usingadifferentpasswordwiththesameusernamestillworked!Soyoumustfileabugreportaboutthisbehaviorbecausetheprogramallowsyoutologonifyouspecifyalongpassword,regardlessofwhetherthepasswordiscorrect.Let’slookatwhythisishappening.Theclassisdefinedasfollows.#defineCREDENTIAL_LENGTH64classLogin{public:Login();voidClearCreds();boolIsLoggedIn();boolTryCreds(char*Username,char*Password);virtual~Login();private:charUserName[CREDENTIAL_LENGTH];charPassPhrase[CREDENTIAL_LENGTH];charCorrectPassPhrase[CREDENTIAL_LENGTH];charBuffer[512];};WhatisinterestingaboutthisisthatthePassPhraseandCorrectPassPhrasearestoredsequentiallyinmemory.Lookatthecodethatcheckswhetherthepasswordiscorrect:boolPassword::IsLoggedIn(){return(0==memcmp(PassPhrase,CorrectPassPhrase,CREDENTIAL_LENGTH));}Thatlooksgood.Howaboutthecaller?boolLogin::TryCreds(char*User,char*Password){FillMemory(UserName,CREDENTIAL_LENGTH,0x00);strcpy(UserName,User);FillMemory(PassPhrase,CREDENTIAL_LENGTH,0x00);strcpy(PassPhrase,Password);returnIsLoggedIn();}Aha!Thestrcpy(PassPhrase,Password);codelookssuspicious.WhatwouldhappenifthisweretooverflowthePassPhrase[]buffer?ItwouldstarttosettheCorrectPassPhrase[]bufferbecauseitcomesrightafterwardinmemory.IfPasswordcontained2*CREDENTIAL_LENGTHbytes,andthefirsthalfmatchedthesecondhalf,thefunctionIsLoggedIncheckwouldreturntrueregardlessoftherealCorrectPassPhrase.Fixingthisisfairlyeasy:simplycheckthelengthoftheinputandfailifitistoolarge.boolLogin::TryCreds(char*User,char*Password){if((strlen(User)<CREDENTIAL_LENGTH)&&(strlen(Password)<CREDENTIAL_LENGTH)){FillMemory(UserName,CREDENTIAL_LENGTH,0x00);strcpy(UserName,User);FillMemory(PassPhrase,CREDENTIAL_LENGTH,0x00);strcpy(PassPhrase,Password);returnIsLoggedIn();}else{returnfalse;}}FormatStringAttacks(格式化字符串攻擊)Nowthatyouhavelearnedhowoverflowswork,let’sbuildonthisknowledgeaboutthecallstackandCPU(coveredinthepreviouschapteronbufferoverflows)tounderstandacleverattackknownastheformatstringattack.ImagineafantasticopportunityformalicioushackersthatexistedforyearsinplainsightinthecoreClanguagespecification.Inadditiontoshowinghowthesecreativeattacksworkanddescribingwaystotestforthem,thischapterwalksyouthroughademonstrationofjusthoweasilysoftwareflawscanbeexploited.Important

Formatstringattacksaren’tlimitedtoCprogramsrunningontheMicrosoftWindowsoperatingsystem:aswithbufferoverflows,youcanfindvulnerableprogramsforLinux,BSD,andMacOS,embeddedsystems,andotherplatformsandenvironments.Consider,forexample,thatsomePerlscriptsarevulnerabletoformatstringattacks(/archive/1/418460/30/30).EvenJavaisn’timmunetotheseattacks!TheSecurityFocusWebsite(/bid/15079/discuss)includesmoredetailsonacaseinwhichVERITASNetbackupallowedforremotesystemcompromisebyaformatstringattack.Justbecauseaprogramisn’twrittenintheCprogramminglanguagedoesn’tmeanitisimmunetothisattack.Beforedelvingintothespecificsoftesting,thischaptertakesaquicklookatwhatformatstringsare,howtheyoperaterelativetothestack,andhowtheyareused.Foracompletediscussionofwhatformatstringsare,pleaserefertotheappropriateprogramminglanguagedocumentation.MoreInfo

InformationaboutCformatstringspecifiersisalsoavailableontheMicrosoftWebsiteat/library/en-us/vclib/html/_crt_Format_Specification_Fields_.2d_.printf_and_wprintf_Functions.asp.WhatareFormatStrings?ConsiderthebasiccaseofneedingtodisplaythetextAAAAtotheuserofacomputerprogramwithstandardClibraryroutines,suchastheprintf(“AAAA”)function,whichoutputsdatatotheconsolewindow—theapplicationhandlesitfineandtheuserseesAAAAwithnoproblem.Itturnsoutthefirstparametercanspecifyformatspecifiers.Theseformatspecifierschangehowtheoutputlooks.Forexample,considerthefollowingcode:printf("Iate%dcheeseburgers.",2);Inthiscase,%distheformatspecifierforanintegerdatatype.Theprecedingcodereplaces%dwiththenumber2andproducesthefollowingoutput:Iate2cheeseburgers.Howdidthatwork?Tocallprintf,youfirstplacethenumber2onthestack,andthenfollowitwithapointertothestring“Iate%dcheeseburgers.”Inthiscase,printftakesthevalue2andreplacesthe%dwith2toformattheoutput.Thereisalsoa%sformatstringspecifier.Thisspecifiercausesprintftoreplacethe%swiththecontentsofanull-terminatedstringbufferratherthanjustthenumber.Forexample,printf("%sate%dcheeseburgers.","ChrisGallagher",1000);wouldresultinthefollowing:ChrisGallagherate1000cheeseburgers.Thatseemsharmlessenoughatfirstglance,butthereismoretothestory.MoreInfo

Theprintffunctionisnottheonlyfunctionthatusesformatstringspecifiers.Table9-1,includedinthesectiontitled“ReviewingCode”laterinthischapter,listssomeofthefunctionsthatuseformatstringspecifiers.Inadditiontowritingtotheprogram’soutput(printf),thesefunctionsarecommonlyusedtoformatdatatobestoredinafile(fprintf),tostoredatainabuffer(sprintf),andtoformatuser-suppliedinput(scanf).Table9-1:FunctionsThatUseFormatStringSpecifiers_cprintf_sntprintf_vsntprintfsscanf_cscanf_sntscanf_vsnwprintfswscanf_cwprintf_snwprintf_vstprintfvfprintf_cwscanf_snwscanf_vtprintfvfwprintf_ftscanf_stscanffprintfvprintf_scprintf_tcprintffscanfvsprintf_sctprintf_tprintffwprintfvswprintf_scwprintf_tscanffwscanfvwprintf_snprintf_vftprintfprintfwprintf_snscanf_vsnprintfscanfwscanf例子//FormatString.cpp:Definestheentrypointfortheconsoleapplication.//#include"stdafx.h"#include"string.h"intmain(intargc,char*argv[]){ //char*form_field_1="allen"; //char*form_field_1="%n%n%n%n"; char*form_field_1=argv[1]; intnum=1; chartarget[64]; charformat[64]; strncpy(format,"Name:",7); strncat(format,form_field_1,25); strncat(format,",count:%d",12); sprintf(target,format,num); printf("%s\n",target); return0;}sprintf函數(shù)中格式字符串%n可對內(nèi)存進行寫操作。因此,如果form_field_1="%n%n%n%n",則執(zhí)行的sprintf變成:sprintf(target,”name:%n%n%n%n,count:%d,num”)這個Sprintf函數(shù)試圖往棧中寫四個整數(shù)值,第一個是num,而其余的放到了棧中為其他目的而保留的位置。Formatstringattackscanbeusedto\o"Crash(computing)"crashaprogramortoexecuteharmfulcode.Theproblemstemsfromtheuseofunfiltereduserinputastheformatstringparameterincertain\o"C(programminglanguage)"Cfunctionsthatperformformatting,suchas\o"Printf"printf().Amalicioususermayusethe%sand%xformattokens,amongothers,toprintdatafromthestackorpossiblyotherlocationsinmemory.Onemayalsowritearbitrarydatatoarbitrarylocationsusingthe%nformattoken,whichcommandsprintf()andsimilarfunctionstowritethenumberofbytesformattedtoanaddressstoredonthestack.整數(shù)溢出當一個整數(shù)值大于或者小于其范圍時,就會產(chǎn)生整數(shù)溢出錯誤(integeroverflow)。類型說明符數(shù)的范圍分配字節(jié)數(shù)

int-32768~32767■■

shortint-32768~32767■■

signedint-32768~32767■■

unsignedint0~65535■■

longint-2147483648~2147483647■■■■

unsignedlong0~4294967295■■■■整數(shù)溢出C語言中存在2類整數(shù)算術運算:有符號運算與無符號運算。

兩個無符號數(shù)運算不存在溢出。

算術運算中一個是有符號數(shù),另一個是無符號數(shù),則有符號數(shù)會轉(zhuǎn)換為無符號數(shù),運算時溢出也不可能發(fā)生。

兩個有符號數(shù)運算,溢出有可能發(fā)生。并且溢出發(fā)生時,溢出結果是未定義的。

那么如何檢測是否發(fā)生溢出呢?

看下面的方式:

inta,b;

if(a+b<0)

//dosomething

這種方式是不可靠的,因為對溢出結果做的任何假設都是不可靠的

正確的方式:

#include<limits.h>

inta,b;

if((unsigned)a+(unsigned)b>INT_MAX)

//...

或者

if(a>INT_MAX-b)

//...

整數(shù)的“回繞”當一個整數(shù)值增長超過了其最大可能的值并循環(huán)到成為一個負數(shù)的時候,就會發(fā)生整數(shù)溢出。 unsignedsize1=2147483647; unsignedsize2=1; intsize=0; size=size1+size2; printf("%d\n",size);例子1boolfunc(char*s1,intlen1,char*s2,intlen2){charbuf[128];if(1+len1+len2>128){ printf("大于128!\n"); returnfalse; }if(buf){ printf("Copytobuf...\n");strncpy(buf,s1,len1);strncat(buf,s2,len2);}returntrue;}intmain(intargc,char*argv[]){ //boolres=func("str1",5,"str2",5); boolres=func("str1",129,"str2",-2); printf("%d\n",res); return0;}例子2:如果getstringsize返回0,則readamt-1將等于4294967295(無符號32位整數(shù)的最大值),這個操作可能會因為內(nèi)存不足而失敗。//Test2.cpp:Definestheentrypointfortheconsoleapplication.//#include"stdafx.h"#include<stdio.h>#include<string.h>#include<malloc.h>intgetstringsize(){ return0;}intmain(intargc,char*argv[]){ //unsignedlongreadamt; unsignedshortreadamt; readamt=getstringsize(); if(readamt>1024) return-1; readamt--; printf("%d\n",readamt); malloc(readamt); //... return0;}CommandInjection(命令注入)#!/usr/bin/perl-w#print"$ARGV[0]";$to=$ARGV[0];$MAIL="SENDMAIL";open($MAIL,"|/usr/lib/sendmail-oi-t")||die"ErrorswithSendmail:$!";print$MAIL<<"EOF";From:rootTo:$toSubject:TestingmailfromperlscriptTestingbodyEOFclose($MAIL)#ENDperlsendmail.plroot;rm–rf/;XSSTip

Cross-sitescriptingwasoriginallyabbreviatedasCSS,butthisacronymcausedmuchconfusionbecauseitisalsousedforCascadingStyleSheets.Cross-sitescriptingisnowcommonlyabbreviatedasXSS.動畫演示:http://www.virtualforge.de/vmovie/xss_lesson_1/xss_selling_platform_v1.0.htmlhttp://www.virtualforge.de/vmovie/xss_lesson_2/xss_selling_platform_v2.0.html攻擊過程XSS攻擊的目的是盜走客戶端cookies,或者任何可以用于在Web站點確定客戶身份的其他敏感信息。手邊有了合法用戶的標記,黑客可以繼續(xù)扮演用戶與站點交互,從而冒充用戶。盜取Cookies誘騙步驟Example:ReflectedXSSinaSearchEngine查詢、搜索是網(wǎng)站常見的功能AsearchcapabilityisacommonfeatureonWebsiteswheretheusertypesinawordorphrasetosearchforandalistofresultsisreturned.However,whenasearchterm(s)cannotbefound,anerrormessageisreturnedtotheuser:Bylookingatthepage’sURL,http://server/search.aspx?keyword=monkey,youmightsupposethatthedatatypedintheURLisreturnedintheresultingWebpage.YoucantestthistheorybymodifyingtheURLalittle.WhenyoutrytheURLhttp://server/seach.aspx?keyword=SomeBogusText,forexample,youseethatthedataintheURL,thevalueofthequerystringparameter“keyword,”isreturnedintheWebpage.TobetterunderstandhowthispageworksviewtheHTMLsource.ThefollowingHTMLsourcewasreturnedbysearch.aspx:<HTML><HEAD><TITLE>SearchExample</TITLE><METAhttp-equiv="content-type"content="text/html;charset=utf-8"></HEAD><BODY><H1>SearchResults</H1>forSomeBogusText<BR><BR><h2>Sorry,noresultswerefound.</h2><BR><FORMname=search><INPUTtype=textname="keyword"value="SomeBogusText"><INPUTtype=submitvalue="Go"></FORM></BODY></HTML>信息直接寫回頁面,造成可被利用的漏洞Noticethatthedatasuppliedinthequerystringisplacedinthe<body>sectionoftheHTML.The<body>sectioncancontainHTMLtags.Whatisaninterestingtestcase?HowaboutanHTMLtaginthequerystringsuchastheboldtag(<B>)?YoucantestthiscasebybrowsingtoaURLlikehttp://server/search.aspx?keyword=<B>Boldly</B>%20go%20where%20no%20dev%20expected.http://server/search.aspx?keyword=<SCRIPT>alert("Running!")</SCRIPT><HTML><HEAD><TITLE>SearchExample</TITLE><METAhttp-equiv="content-type"content="text/html;charset=utf-8"></HEAD><BODY><H1>SearchResults</H1>for<SCRIPT>alert("Running!")</SCRIPT><BR><BR><h2>Sorry,noresultswerefound.</h2><BR><FORMname=search><INPUTtype=textname="keyword"value="<SCRIPT>alert("Running!")</SCRIPT>"><INPUTtype=submitvalue="Go"></FORM></BODY></HTML>XSSenablesactionsthatarenormallyprohibited

1、Cookieaccess

2、Objectmodelaccess3、UserDataaccess

4、BypassingSiteLockrestrictions5、ZoneelevationTogetavictimtoechothisscriptthroughthebuggysearchfunctionality,forexample,anattackermustconvincethevictimtonavigatetoHYPERLINK"http://server/search.aspx?keyword=%3CSCRIPT%3Edocument.location=%22/defau

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論