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

3元/首月香港便宜vps究竟是什么货。

便宜的香港vps多少钱?现在国外VPS主机的价格已经很便宜了,美国VPS主机最低一个月只要十几元,但同样免备案的香港VPS价格贵不贵呢?或者说便宜的香港VPS多少钱?香港vps主机价格要比美国机房的贵一些,但比国内的又便宜不少,所以目前情况是同等配置下,美国VPS比香港的便宜,香港VPS比国内(指大陆地区)的便宜。目前,最便宜香港vps低至3元/首月、18元/月起,今天云服务器网(www.yunt...

优林70/月,西南高防地区最低70/月

优林怎么样?优林好不好?优林 是一家国人VPS主机商,成立于2016年,主营国内外服务器产品。云服务器基于hyper-v和kvm虚拟架构,国内速度还不错。今天优林给我们带来促销的是国内西南地区高防云服务器!全部是独享带宽!续费同价!官方网站:https://www.idc857.com​地区CPU内存硬盘流量带宽防御价格购买地址德阳高防4核4g50G无限流量10M100G70元/月点击购买德阳高防...

腾讯云爆款秒杀:1C2G5M服务器38元/年,CDN流量包6元起

农历春节将至,腾讯云开启了热门爆款云产品首单特惠秒杀活动,上海/北京/广州1核2G云服务器首年仅38元起,上架了新的首单优惠活动,每天三场秒杀,长期有效,其中轻量应用服务器2G内存5M带宽仅需年费38元起,其他产品比如CDN流量包、短信包、MySQL、直播流量包、标准存储等等产品也参与活动,腾讯云官网已注册且完成实名认证的国内站用户均可参与。活动页面:https://cloud.tencent.c...

phpwind为你推荐
internalservererrorinternal server error在线代理怎么样设置代理,让别人看我的IP是别的地方,不是我真实的IP?闪拍网闪拍网是真的吗工具条手机的工具栏怎么在任务栏里?怎么把工具栏调到手机下面?如何发帖子手机百度贴吧怎么发帖子?账号通谁知道帐号通怎么解 我的号被盗号的帮了无忧登陆无忧登陆怎么用??谷歌新漏洞google hacking 技术有哪些无忧验证码驾驶无忧登录手机号后,密码是哪个密码管理员密码请输入管理员密码什么意思
asp虚拟主机 韩国服务器租用 上海服务器租用 大庆服务器租用 西安电信测速 z.com 香港机房托管 免费cdn加速 天猫双十一秒杀 日本空间 全能主机 长沙服务器 云鼎网络 个人域名 韩国名字大全 789电视网 世界测速 卡巴斯基破解版 四核服务器 360云服务 更多