!'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
优林怎么样?优林好不好?优林 是一家国人VPS主机商,成立于2016年,主营国内外服务器产品。云服务器基于hyper-v和kvm虚拟架构,国内速度还不错。今天优林给我们带来促销的是国内西南地区高防云服务器!全部是独享带宽!续费同价!官方网站:https://www.idc857.com地区CPU内存硬盘流量带宽防御价格购买地址德阳高防4核4g50G无限流量10M100G70元/月点击购买德阳高防...
优惠码年付一次性5折优惠码:TYO-Lite-Open-Beta-1y-50OFF永久8折优惠码:TYO-Lite-Open-Beta-Recur-20OFF日本vpsCPU内存SSD流量带宽价格购买1核1.5G20 GB4 TB1Gbps$10.9/月购买2核2 G40 GB6 TB1Gbps$16.9/月购买2核4 G60 GB8 TB1Gbps$21.9/月购买4核4 G80 GB12 TB...
ReadyDedis是一家2018年成立的国外VPS商家,由印度人开设,主要提供VPS和独立服务器租用等,可选数据中心包括美国洛杉矶、西雅图、亚特兰大、纽约、拉斯维加斯、杰克逊维尔、印度和德国等。目前,商家针对全部VPS主机提供新年5折优惠码,优惠后最低套餐1GB内存每月仅需2美元起,所有VPS均为1Gbps端口不限流量方式。下面列出几款主机配置信息。CPU:1core内存:1GB硬盘:25GB ...
phpwind为你推荐
uctools我的UC上不去。好急呀,请帮帮我。http500http://bb500.com 这个电影网站安全不?为什么?有人能告诉我吗?不懂的人表乱说浪费你我的时间谢谢空间文章空间的文章被人推荐有什么好处360和搜狗360浏览器和搜狗浏览器哪个好用?dell服务器bios设置dell怎样进入bios设置界面sns网站有哪些有哪些好的SNS商务社交类网站?三友网怎么是“三友”三五互联科技股份有限公司三五互联 网站做的怎么样 公司打算做网站,近来接到电话,不知道网站做的如何,水平怎么样,后期的服务呢可信网站可信网站认证一定要办吗billboardchina美国Billboard公告牌年度10大金曲最新华丽合辑
汉邦高科域名注册 域名查询系统 linuxapache虚拟主机 中国域名交易中心 什么是域名地址 七牛优惠码 163网 美国php空间 轻量 骨干网络 柚子舍官网 adroit 免费全能主机 yundun 上海电信测速网站 德隆中文网 全能空间 服务器论坛 ledlamp winserver2008 更多