!'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

随风云25元/月 ,德阳高防云服务器 2核2G 10M 75元/月 内蒙古三线BGP服务器 2核2G 5M

公司介绍成都随风云科技有限公司成立于2021年,是国内领先的互联网业务平台服务提供商。公司专注为用户提供低价高性能云计算产品,致力于云计算应用的易用性开发,并引导云计算在国内普及。目前公司研发以及运营云服务基础设施服务平台(IaaS),面向全球客户提供基于云计算的IT解决方案与客户服务,拥有丰富的国内BGP、双线高防、香港等优质的IDC资源。公司一直秉承”以人为本、客户为尊、永续创新&...

Stablehost 美国主机商黑五虚拟主机四折

如今我们网友可能较多的会选择云服务器、VPS主机,对于虚拟主机的话可能很多人不会选择。但是我们有些外贸业务用途的建站项目还是会有选择虚拟主机的。今天看到的Stablehost 商家虚拟主机在黑五期间也有四折优惠,对于这个服务商而言不是特别的喜欢,虽然他们商家和我们熟悉的老鹰主机商有些类似,且在后来老鹰主机改版和方案后,Stablehost 商家也会跟随改版,但是性价比认为不如老鹰主机。这次黑色星期...

香港E3-1230v2 16GB 30M 326元/月 数脉科技

官方网站:https://www.shuhost.com/公司名:LucidaCloud Limited尊敬的新老客户:艰难的2021年即将结束,年终辞旧迎新之际,我们准备了持续优惠、及首月优惠,为中小企业及个人客户降低IT业务成本。我们将持续努力提供给客户更好的品质与服务,在新的一年期待与您有美好的合作。# 下列价钱首月八折优惠码: 20211280OFF (每客户限用1次) * 自助购买可复制...

phpwind为你推荐
2014年软件产品登记名单(6月第二批)thinksns在thinksns 中集成UCenter过程中,按照教程做的,但是出现 通信失败,请问如何处理,谢谢2019支付宝五福支付宝5褔过了开奖时间怎么办苹果appstore宕机苹果手机为什么显示无法连接到appstoregoogleprGOOGLE PR是什么意思申请支付宝账户申请支付宝账号注册360防火墙在哪里设置360防火墙怎么开启啊 我要9.3的补贴esetJoinsql最土团购程序公司要开设一个团购项目,应该如何运作?
冰山互联 gateone 云图标 免费全能空间 爱奇艺vip免费领取 双线机房 主机管理系统 中国域名 阿里云邮箱登陆地址 免备案jsp空间 美国十大啦 shuangshiyi vim 大硬盘补丁 宿主机 电脑主机声音大 主机声音大 百度空间登陆首页 视频监控服务器 网络存储服务器 更多