!'UIDETO"UILDING3ECURE7EB!PPLICATIONS

phpwind  时间:2021-02-13  阅读:()
!
'UIDET#HRIS3HImETT%SSENTIAL0(03ECURITY%SSENTIAL03ECURITYThisistheTitleoftheBook,eMatterEditionCopyright2005O'Reilly&Associates,Inc.
Allrightsreserved.
40Chapter4CHAPTER4SessionsandCookiesThischapterdiscussessessionsandtheinherentrisksassociatedwithstatefulwebapplications.
Youwillfirstlearnthefundamentalsofstate,cookies,andsessions;thenIwilldiscussseveralconcerns—cookietheft,exposedsessiondata,sessionfixa-tion,andsessionhijacking—alongwithpracticesthatyoucanemploytohelppre-ventthem.
Therumorsaretrue:HTTPisastatelessprotocol.
ThisdescriptionrecognizesthelackofassociationbetweenanytwoHTTPrequests.
Becausetheprotocoldoesnotprovideanymethodthattheclientcanusetoidentifyitself,theservercannotdistin-guishbetweenclients.
WhilethestatelessnatureofHTTPhassomeimportantbenefits—afterall,maintain-ingstaterequiressomeoverhead—itpresentsauniquechallengetodeveloperswhoneedtocreatestatefulwebapplications.
Withnowaytoidentifytheclient,itisimpossibletodeterminewhethertheuserisalreadyloggedin,hasitemsinashop-pingcart,orneedstoregister.
Anelegantsolutiontothisproblem,originallyconceivedbyNetscape,isastateman-agementmechanismcalledcookies.
CookiesareanextensionoftheHTTPprotocol.
Moreprecisely,theyconsistoftwoHTTPheaders:theSet-CookieresponseheaderandtheCookierequestheader.
WhenaclientsendsarequestforaparticularURL,theservercanopttoincludeaSet-Cookieheaderintheresponse.
Thisisarequestfortheclienttoincludeacorre-spondingCookieheaderinitsfuturerequests.
Figure4-1illustratesthisbasicexchange.
Ifyouusethisconcepttoallowauniqueidentifiertobeincludedineachrequest(inaCookieheader),youcanbegintouniquelyidentifyclientsandassociatetheirrequeststogether.
Thisisallthatisrequiredforstate,andthisistheprimaryuseofthemechanism.
,ch04.
847Page40Friday,October14,200511:27AMThisistheTitleoftheBook,eMatterEditionCopyright2005O'Reilly&Associates,Inc.
Allrightsreserved.
CookieTheft|41ThebestreferenceforcookiesisstillthespecificationprovidedbyNetscapeathttp://wp.
netscape.
com/newsref/std/cookie_spec.
html.
Thismostcloselyresemblesindustrysupport.
Theconceptofsessionmanagementbuildsupontheabilitytomaintainstatebymaintainingdataassociatedwitheachuniqueclient.
Thisdataiskeptinasessiondatastore,anditisupdatedoneachrequest.
Becausetheuniqueidentifierspecifiesaparticularrecordinthesessiondatastore,it'smostoftencalledthesessionidentifier.
IfyouusePHP'snativesessionmechanism,allofthiscomplexityishandledforyou.
Whenyoucallsession_start(),PHPfirstdetermineswhetherasessionidentifierisincludedinthecurrentrequest.
Ifoneis,thesessiondataforthatparticularsessionisreadandprovidedtoyouinthe$_SESSIONsuperglobalarray.
Ifoneisnot,PHPgeneratesasessionidentifierandcreatesanewrecordinthesessiondatastore.
Italsohandlespropagatingthesessionidentifierandupdatingthesessiondatastoreoneachrequest.
Figure4-2illustratesthisprocess.
Whilethisconvenienceishelpful,itisimportanttorealizethatitisnotacompletesolution.
ThereisnoinherentsecurityinPHP'ssessionmechanism,asidefromthefactthatthesessionidentifieritgeneratesissufficientlyrandom,therebyeliminatingthepracticalityofprediction.
Youmustprovideyourownsafeguardstoprotectagainstallothersessionattacks.
Iwillshowyouafewproblemsandsolutionsinthischapter.
CookieTheftOneriskassociatedwiththeuseofcookiesisthatauser'scookiescanbestolenbyanattacker.
Ifthesessionidentifieriskeptinacookie,cookiedisclosureisaseriousrisk,becauseitcanleadtosessionhijacking.
Figure4-1.
AcompletecookieexchangethatinvolvestwoHTTPtransactionsClientServer1HTTPrequestHTTPresponse&Set-Cookie2HTTPrequest&CookieHTTPresponse,ch04.
847Page41Friday,October14,200511:27AMThisistheTitleoftheBook,eMatterEditionCopyright2005O'Reilly&Associates,Inc.
Allrightsreserved.
42|Chapter4:SessionsandCookiesThetwomostcommoncausesofcookiedisclosurearebrowservulnerabilitiesandcross-sitescripting(discussedinChapter2).
Whilenosuchbrowservulnerabilitiesareknownatthistime,therehavebeenafewinthepast—themostnotableonesareinInternetExplorerVersions4.
0,5.
0,5.
5,and6.
0(correctivepatchesareavailableforeachofthesevulnerabilities).
Whilebrowservulnerabilitiesarecertainlynotthefaultofwebdevelopers,youmaybeabletotakestepstomitigatetherisktoyourusers.
Insomecases,youmaybeabletoimplementsafeguardsthatpracticallyeliminatetherisk.
Attheveryleast,youcantrytoeducateyourusersanddirectthemtoapatchtofixthevulnerability.
Forthesereasons,itisgoodtobeawareofnewvulnerabilities.
Thereareafewwebsitesandmailingliststhatyoucankeepupwith,andmanyservicesarebeginningtoofferRSSfeeds,sothatyoucansimplysubscribetothefeedandbealertedtonewvulnerabilities.
SecurityFocusmaintainsalistofsoftwarevulnerabilitiesathttp://online.
securityfocus.
com/vulnerabilities,andyoucanfiltertheseadvisoriesbyvendor,title,andversion.
ThePHPSecurityConsortiumalsomaintainssummariesoftheSecurityFocusnewslettersathttp://phpsec.
org/projects/vulnerabilities/securityfocus.
html.
Figure4-2.
PHPhandlesthecomplexityofsessionmanagementforyouPHPSESSIDincookiePHPSESSIDinquerystringGeneratenewPHPSESSIDFetchsessiondataandpopulate$_SESSIONSetcookieandcachingheadersRewriteURLSStoresessiondataNoYesYesCodePHP,ch04.
847Page42Friday,October14,200511:27AMThisistheTitleoftheBook,eMatterEditionCopyright2005O'Reilly&Associates,Inc.
Allrightsreserved.
SessionFixation|43Cross-sitescriptingisamorecommonapproachusedbyattackerstostealcookies.
Anattackercanuseseveralapproaches,oneofwhichisdescribedinChapter2.
Becauseclient-sidescriptshaveaccesstocookies,allanattackermustdoiswriteascriptthatdeliversthisinformation.
Creativityistheonlylimitingfactor.
Protectingyourusersfromcookietheftisthereforeacombinationofavoidingcross-sitescriptingvulnerabilitiesanddetectingbrowserswithsecurityvulnerabilitiesthatcanleadtocookieexposure.
Becausethelatterissouncommon(withanyluck,thesetypesofvulnerabilitieswillremainararity),itisnottheprimaryconcernbutrathersomethingtokeepinmind.
ExposedSessionDataSessiondataoftenconsistsofpersonalinformationandothersensitivedata.
Forthisreason,theexposureofsessiondataisacommonconcern.
Ingeneral,theexposureisminimal,becausethesessiondatastoreresidesintheserverenvironment,whetherinadatabaseorthefilesystem.
Therefore,sessiondataisnotinherentlysubjecttopublicexposure.
EnablingSSLisaparticularlyusefulwaytominimizetheexposureofdatabeingsentbetweentheclientandtheserver,andthisisveryimportantforapplicationsthatexchangesensitivedatawiththeclient.
SSLprovidesalayerofsecuritybeneathHTTP,sothatalldatawithinHTTPrequestsandresponsesisprotected.
Ifyouareconcernedaboutthesecurityofthesessiondatastoreitself,youcanencryptitsothatsessiondatacannotbereadwithouttheappropriatekey.
ThisismosteasilyachievedinPHPbyusingsession_set_save_handler()andwritingyourownsessionstorageandretrievalfunctionsthatencryptsessiondatabeingstoredanddecryptsessiondatabeingread.
SeeAppendixCformoreinformationaboutencryptingasessiondatastore.
SessionFixationAmajorconcernregardingsessionsisthesecrecyofthesessionidentifier.
Ifthisiskeptsecret,thereisnopracticalriskofsessionhijacking.
Withavalidsessionidenti-fier,anattackerismuchmorelikelytosuccessfullyimpersonateoneofyourusers.
Anattackercanusethreeprimarymethodstoobtainavalidsessionidentifier:PredictionCaptureFixation,ch04.
847Page43Friday,October14,200511:27AMThisistheTitleoftheBook,eMatterEditionCopyright2005O'Reilly&Associates,Inc.
Allrightsreserved.
44|Chapter4:SessionsandCookiesPHPgeneratesaveryrandomsessionidentifier,sopredictionisnotapracticalrisk.
Capturingasessionidentifierismorecommon—minimizingtheexposureoftheses-sionidentifier,usingSSL,andkeepingupwithbrowservulnerabilitiescanhelpyoumitigatetheriskofcapture.
KeepinmindthatabrowserincludesaCookieheaderinallrequeststhatsatisfytherequirementssetforthinapreviousSet-Cookieheader.
Quitecommonly,thesessionidentifierisbeingexposedunnecessarilyinrequestsforembeddedresources,suchasimages.
Forexample,torequestawebpagewith10images,thesessionidentifierisbeingsentbythebrowserin11differentrequests,butitisneededforonly1ofthose.
Toavoidthisunnecessaryexposure,youmightconsiderserv-ingallembeddedresourcesfromaserverwithadifferentdomainname.
Sessionfixationisanattackthattricksthevictimintousingasessionidentifiercho-senbytheattacker.
Itisthesimplestmethodbywhichtheattackercanobtainavalidsessionidentifier.
Inthesimplestcase,asessionfixationattackusesalink:ClickHereAnotherapproachistouseaprotocol-levelredirect:TheRefreshheadercanalsobeused—providedasanactualHTTPheaderorinthehttp-equivattributeofametatag.
Theattacker'sgoalistogettheusertovisitaURLthatincludesasessionidentifieroftheattacker'schoosing.
Thisisthefirststepinabasicattack;thecompleteattackisillustratedinFigure4-3.
Figure4-3.
AsessionfixationattackusesasessionidentifierchosenbytheattackerVictimexample.
org123target.
example.
orgGET/login.
phpPHPSESSID=123HTTP/1.
1HOST:target.
example.
orgClickHere,ch04.
847Page44Friday,October14,200511:27AMThisistheTitleoftheBook,eMatterEditionCopyright2005O'Reilly&Associates,Inc.
Allrightsreserved.
SessionFixation|45Ifsuccessful,theattackerisabletoavoidthenecessityofcapturingorpredictingavalidsessionidentifier,anditispossibletolaunchadditionalandmoredangeroustypesofattacks.
Agoodwaytobetterunderstandthisistotryityourself.
Beginwithascriptnamedfixation.
php:Ensurethatyoudonothaveanyexistingcookiesforthecurrenthost,orclearallcookiestobecertain.
Visitfixation.
phpandincludePHPSESSIDintheURL:http://example.
org/fixation.
phpPHPSESSID=1234Thiscreatesasessionvariable(username)withavalueofchris.
Aninspectionofthesessiondatastorerevealsthat1234isthesessionidentifierassociatedwiththisdata:$cat/tmp/sess_1234username|s:5:"chris";Createasecondscript,test.
php,thatoutputsthevalueof$_SESSION['username']ifitexists:VisitthisURLusingadifferentcomputer,oratleastadifferentbrowser,andincludethesamesessionidentifierintheURL:http://example.
org/test.
phpPHPSESSID=1234Thiscausesyoutoresumethesessionyoubeganwhenyouvisitedfixation.
php,andtheuseofadifferentcomputer(ordifferentbrowser)mimicsanattacker'sposition.
Youhavesuccessfullyhijackedasession,andthisisexactlywhatanattackercando.
Clearly,thisisnotdesirable.
Becauseofthisbehavior,anattackercanprovidealinktoyourapplication,andanyonewhousesthislinktovisityoursitewilluseasessionidentifierchosenbytheattacker.
,ch04.
847Page45Friday,October14,200511:27AMThisistheTitleoftheBook,eMatterEditionCopyright2005O'Reilly&Associates,Inc.
Allrightsreserved.
46|Chapter4:SessionsandCookiesOnecauseofthisproblemisthatasessionidentifierintheURLisusedtocreateanewsession—evenwhenthereisnoexistingsessionforthatparticularsessioniden-tifier,PHPcreatesone.
Thisprovidesaconvenientopeningforanattacker.
Luckily,thesession_regenerate_id()functioncanbeusedtohelppreventthis:Thisensuresthatafreshsessionidentifierisusedwheneverasessionisinitiated.
However,thisisnotaneffectivesolutionbecauseasessionfixationattackcanstillbesuccessful.
Theattackercansimplyvisityourwebsite,determinethesessionidenti-fierthatPHPassigns,andusethatsessionidentifierinthesessionfixationattack.
Thisdoeseliminatetheopportunityforanattackertoassignasimplesessionidenti-fiersuchas1234,buttheattackercanstillexaminethecookieorURL(dependinguponthemethodofpropagation)togetthesessionidentifierassignedbyPHP.
ThisapproachisillustratedinFigure4-4.
Toaddressthisweakness,ithelpstounderstandthescopeoftheproblem.
Sessionfixationismerelyastepping-stone—thepurposeoftheattackistogetasessioniden-tifierthatcanbeusedtohijackasession.
Thisismostusefulwhenthesessionbeinghijackedhasahigherlevelofprivilegethantheattackercanobtainthroughlegiti-matemeans.
Thislevelofprivilegecanbeassimpleasbeingloggedin.
Ifthesessionidentifierisregeneratedeverytimethereisachangeinthelevelofprivi-lege,theriskofsessionfixationispracticallyeliminated:,ch04.
847Page46Friday,October14,200511:27AMThisistheTitleoftheBook,eMatterEditionCopyright2005O'Reilly&Associates,Inc.
Allrightsreserved.
SessionFixation|47Idonotrecommendregeneratingthesessionidentifieroneverypage.
Whilethisseemslikeasecureapproach—anditis—itprovidesnomoreprotectionthanregeneratingthesessionidentifierwheneverthereisachangeinthelevelofprivilege.
Moreimportantly,itcanadverselyaffectyourlegitimateusers,especiallyifthesessionidenti-fierisbeingpropagatedintheURL.
Ausermightusethebrowser'shistorymechanismtoreturntoapreviouspage,andthelinksonthatpagewillreferenceasessionidentifierthatnolongerexists.
Ifyouregeneratethesessionidentifieronlywhenthereisachangeinthelevelofprivilege,thesamesituationispossible,butauserwhoreturnstoapagepriortothechangeinthelevelofprivilegeislesslikelytobesurprisedbyalossofsession,andthissituationisalsolesscommon.
Figure4-4.
AsessionfixationattackcanfirstinitializethesessionAttacker1target.
example.
orgHTTP/1.
1200OKSet-Cookie:PHPSESSID=412e11d52Victim4example.
org53AttackerAttackerupdatescontenttoincludealinkwithanembeddedPHPSESSIDtarget.
example.
org6GET/login.
phpPHPSESSID=412e11d5HTTP/1.
1Host:target.
example.
org,ch04.
847Page47Friday,October14,200511:27AMThisistheTitleoftheBook,eMatterEditionCopyright2005O'Reilly&Associates,Inc.
Allrightsreserved.
48|Chapter4:SessionsandCookiesSessionHijackingThemostcommonsessionattackissessionhijacking.
Thisreferstoanymethodthatanattackercanusetoaccessanotheruser'ssession.
Thefirststepforanyattackeristoobtainavalidsessionidentifier,andthereforethesecrecyofthesessionidentifierisparamount.
Theprevioussectionsonexposureandfixationcanhelpyoutokeepthesessionidentifierasharedsecretbetweentheserverandalegitimateuser.
TheprincipleofDefenseinDepth(describedinChapter1)canbeappliedtoses-sions—someminorsafeguardscanoffersomeprotectionintheunfortunatecasethatthesessionidentifierisknownbyanattacker.
Asasecurity-consciousdeveloper,yourgoalistocomplicateimpersonation.
Everyobstacle,howeverminor,offerssomeprotection.
Thekeytocomplicatingimpersonationistostrengthenidentification.
Thesessionidentifieristheprimarymeansofidentification,andyouwanttoselectotherdatathatyoucanusetoaugmentthis.
TheonlydatayouhaveavailableisthedatawithineachHTTPrequest:GET/HTTP/1.
1Host:example.
orgUser-Agent:Firefox/1.
0Accept:text/html,image/png,image/jpeg,image/gif,*/*Cookie:PHPSESSID=1234Youwanttorecognizeconsistencyinrequestsandtreatanyinconsistentbehaviorwithsuspicion.
Forexample,whiletheUser-Agentheaderisoptional,clientsthatsenditdonotoftenalteritsvalue.
Iftheuserwithasessionidentifierof1234hasbeenusingMozillaFirefoxconsistentlysinceloggingin,asuddenswitchtoInternetExplorershouldbetreatedwithsuspicion.
Forexample,promptingforthepass-wordisaneffectivewaytomitigatetheriskwithminimalimpacttoyourlegitimateusersinthecaseofafalsealarm.
YoucancheckforUser-Agentconsistencyasfollows:,ch04.
847Page48Friday,October14,200511:27AMThisistheTitleoftheBook,eMatterEditionCopyright2005O'Reilly&Associates,Inc.
Allrightsreserved.
SessionHijacking|49IhaveobservedthatsomeversionsofInternetExplorersendadiffer-entAcceptheaderdependinguponwhethertheuserrefreshesthebrowser,soAcceptshouldnotberelieduponforconsistency.
RequiringaconsistentUser-Agenthelps,butifthesessionidentifierisbeingpropa-gatedinacookie(therecommendedapproach),itisreasonabletoassumethat,ifanattackercancapturethesessionidentifier,hecanmostlikelycapturethevalueofallotherHTTPheadersaswell.
Becausecookiedisclosuretypicallyinvolvesabrowservulnerabilityorcross-sitescripting,thevictimhasmostlikelyvisitedtheattacker'swebsite,disclosingallheaders.
AllanattackermustdoisreproduceallofthesetoavoidanyconsistencycheckthatusesHTTPheaders.
AbetterapproachistopropagateatokenintheURL—somethingthatcanbecon-sideredasecond(albeitmuchweaker)formofidentification.
Thispropagationtakessomework—thereisnofeatureofPHPthatdoesitforyou.
Forexample,assumingthetokenisstoredin$token,allinternallinksinyourapplicationneedtoincludeit:">ClickHereTomakepropagationabiteasiertomanage,youmightconsiderkeep-ingtheentirequerystringinavariable.
Youcanappendthisvariabletoallofyourlinks,whichmakesiteasytorefactoryourcodelater,evenifyoudon'timplementthistechniqueinitially.
Thetokenneedstobesomethingthatcannotbepredicted,evenundertheconditionthattheattackerknowsalloftheHTTPheadersthatthevictim'sbrowsertypicallysends.
Onewaytoachievethisistogeneratethetokenusingarandomstring:,ch04.
847Page49Friday,October14,200511:27AMThisistheTitleoftheBook,eMatterEditionCopyright2005O'Reilly&Associates,Inc.
Allrightsreserved.
50|Chapter4:SessionsandCookiesWhenyouusearandomstring(SHIFLETTinthisexample),predictionisimpractical.
Inthiscase,capturingthetokeniseasierthanpredictingit,andbypropagatingthetokenintheURLandthesessionidentifierinacookie,multipleattacksareneededtocaptureboth.
Theexceptioniswhentheattackercanobservethevictim'srawHTTPrequestsastheyaresenttoyourapplication,becausethisdisclosesevery-thing.
Thistypeofattackismoredifficult(andthereforelesslikely),anditcanbemitigatedbyusingSSL.
SomeexpertswarnagainstrelyingontheconsistencyofUser-Agent.
TheconcernisthatanHTTPproxyinaclustercanmodifyUser-Agentinconsistentlywithotherproxiesinthesamecluster.
IfyoudonotwanttodependonUser-Agentconsistency,youcangeneratearandomtoken:Thisapproachisslightlyweaker,butitismuchmorereliable.
Bothmethodsprovideastrongdefenseagainstsessionhijacking.
Theappropriatebalancebetweensecurityandreliabilityisuptoyou.
,ch04.
847Page50Friday,October14,200511:27AM

90IDC-香港云主机,美国服务器,日本KVM高性能云主机,创建高性能CLOUD只需60秒即可开通使用!

官方网站:点击访问90IDC官方网站优惠码:云八五折优惠劵:90IDCHK85,仅适用于香港CLOUD主机含特惠型。活动方案:年付特惠服务器:CPU均为Intel Xeon两颗,纯CN2永不混线,让您的网站更快一步。香港大浦CN2測速網址: http://194.105.63.191美国三网CN2測速網址: http://154.7.13.95香港购买地址:https://www.90idc.ne...

VirtVPS抗投诉瑞士VPS上线10美元/月

专心做抗投诉服务器的VirtVPS上线瑞士机房,看中的就是瑞士对隐私的保护,有需要欧洲抗投诉VPS的朋友不要错过了。VirtVPS这次上新的瑞士服务器采用E-2276G处理器,Windows/Linux操作系统可选。VirtVPS成立于2018年,主营荷兰、芬兰、德国、英国机房的离岸虚拟主机托管、VPS、独立服务器、游戏服务器和外汇服务器业务。VirtVPS 提供世界上最全面的安全、完全受保护和私...

热网互联33元/月,香港/日本/洛杉矶/韩国CN2高速线路云主机

热网互联怎么样?热网互联(hotiis)是随客云计算(Suike.Cloud)成立于2009年,增值电信业务经营许可证:B1-20203716)旗下平台。热网互联云主机是CN2高速回国线路,香港/日本/洛杉矶/韩国CN2高速线路云主机,最低33元/月;热网互联国内BGP高防服务器,香港服务器,日本服务器全线活动中,大量七五折来袭!点击进入:热网互联官方网站地址热网互联香港/日本/洛杉矶/韩国cn2...

phpwind为你推荐
toupian粤语有几个拼音字母?现有新的ios更新可用请从ios14be苹果手机更新不了最新14系统是怎么回事?苹果appstore宕机最近app store一直不能用 怎么回事啊 改dns也不能用 持续好久好久了三友网怎么是“三友”瑞东集团海澜集团有限公司怎么样?地址栏图标网站添加地址栏图标代码怎么写?地址栏图标地址栏中网址前面的图标代表着什么?关闭评论怎样关闭评论?一键备份如何一键备份安卓手机操作系统配送区域什么是配送模式,配送模式有哪几种
域名主机 重庆虚拟空间 vps论坛 坐公交投2700元 东莞数据中心 世界测速 tna官网 卡巴斯基免费试用版 工信部网站备案查询 美国迈阿密 云服务是什么意思 域名和主机 葫芦机 nic 傲盾代理 德国代理 在线tracert ddos攻击软件 小米电视主机 56折扣网 更多