!'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
昔日数据,国内商家,成立于2020年,主要销售湖北十堰和香港HKBN的云服务器,采用KVM虚拟化技术构架,不限制流量。当前夏季促销活动,全部首月5折促销,活动截止于8月11日。官方网站:https://www.xrapi.cn/5折优惠码:XR2021湖北十堰云服务器托管于湖北十堰市IDC数据中心,母鸡采用e5 2651v2,SSD MLC企业硬盘、 rdid5阵列为数据护航,100G高防,超出防...
棉花云官网棉花云隶属于江西乐网科技有限公司,前身是2014年就运营的2014IDC,专注海外线路已有7年有余,是国内较早从事海外专线的互联网基础服务提供商。公司专注为用户提供低价高性能云计算产品,致力于云计算应用的易用性开发,并引导云计算在国内普及。目前公司研发以及运营云服务基础设施服务平台(IaaS),面向全球客户提供基于云计算的IT解决方案与客户服务(SaaS),拥有丰富的国内BGP、双线高防...
目前云服务器市场竞争是相当的大的,比如我们在年中活动中看到各大服务商都找准这个噱头的活动发布各种活动,有的甚至就是平时的活动价格,只是换一个说法而已。可见这个行业确实竞争很大,当然我们也可以看到很多主机商几个月就消失,也有看到很多个人商家捣鼓几个品牌然后忽悠一圈跑路的。当然,个人建议在选择服务商的时候尽量选择老牌商家,这样性能更为稳定一些。近期可能会准备重新整理Vultr商家的一些信息和教程。以前...
phpwind为你推荐
操作http全国企业信息查询有没有可以查全国企业信息的工商查询网站重庆杨家坪猪肉摊主杀人重庆九龙坡区治安好么重庆电信dns重庆的DNS服务器地址是多少?大飞资讯手机出现热点资讯怎么关闭三友网怎么是“三友”12306.com如何登录12306网站方案设计求一篇校园网络设计的方案如何发帖子手机百度贴吧怎么发帖子?什么是seo小红妹 seo是什么意思?seo网站优化该怎 随机阅读 seo是什么意思
香港主机租用 韩国vps俄罗斯美女 最新代理服务器ip 新网域名解析 justhost virpus godaddy优惠码 wdcp evssl证书 线路工具 申请空间 韩国网名大全 智能骨干网 dd444 京东商城0元抢购 大容量存储器 韩国名字大全 新家坡 服务器干什么用的 新睿云 更多