COMMON REST API SECURITYPITFALLS - OWASP · §And sometimes, it’s just not the API’s...

Post on 03-Aug-2020

4 views 0 download

transcript

@PhilippeDeRyck

PhilippeDeRyck

COMMON RESTAPISECURITY PITFALLS

OWASPBeNeLux days2017

POST/api/login{“username”:“philippe”,“password”:“Pass1234!”}

Loadtheapplication

https://github.com/OWASP/Top10/blob/master/2017/drafts/OWASP%20Top%2010%20-%202017%20RC1-English.pdf

ABOUT ME – PHILIPPE DE RYCK

§Mygoalistohelpyoubuildsecurewebapplications−Coursesandtrainingprograms− Talksatvariousdeveloperconferences− Slides,videosandblogpostsonhttps://www.websec.be

§ AuthoroftheWebSecurityFundamentalscourse− FreeonlinecourseontheedX platform−Allinfoonhttps://mooc.websec.be

§ CoursecuratorfortheSecAppDev course− Securitycoursetargetedtowardsdevelopers,architects,…−Week-longcoursetaughtbyinternationalexpertsintheirdomain

secappdev.org

HTTPS

OFFER YOUR APIOVER HTTPS

§ ThereisnovalidexcusetonotuseHTTPSanymore− Let’sEncryptoffersfreecertificatesforall−Performanceisnolongeranissue

§ APIsareaccesseddirectlyfromwithinanapplication−MakessettingupHTTPSeasier,asyoudonotneedtosupportaredirectfromHTTP− SimplydisableHTTPforyourAPIendpointsaltogether

§Network-basedattackscanstillattemptafallbacktoHTTP−ConfigureHTTPStrictTransportSecurity (HSTS)topreventthisfromhappening−HSTSwilltellthebrowsertouseHTTPSforeveryrequest,regardlessofthescheme

Strict-Transport-Security: max-age=31536000

SECURITY PITFALL

AllowingaccesstoyourAPIoverHTTP

APIsareaccessedfromcode,sothereisnoneedtosupportaredirectfromHTTPtoHTTPS.LockyourAPIfurther

downbyenablingHSTS

https://motherboard.vice.com/en_us/article/wjx3e4/t-mobile-website-allowed-hackers-to-access-your-account-data-with-just-your-phone-number

https://www.codementor.io/olatundegaruba/nodejs-restful-apis-in-10-minutes-q0sgsfhbd

INSECURE DIRECT OBJECT REFERENCES

§ Predictableidentifiersenabletheenumerationofresources−Dangerousifresourcesarenotshieldedbystrictauthorizationchecks−ManyAPIsonlycheckauthenticationstatus,butnotwhich userisauthenticated

§ Theonlypropermitigationisimplementingproperauthorizationchecks− E.g.checkingifthecurrentuseristheowneroftheresource

§ Theuseofnon-predictableidentifiersisacomplementarystrategy−UUIDsareagoodexampleofsuchanidentifier− Justbecarefulaboutusingthemasprimarykeysinthedatabase

SECURITY PITFALL

Usinginsecuredirectobjectreferences

Alwayscomplementabasicauthenticationcheckwithappropriateauthorizationchecks(e.g.ownershipofaresource)

1234

1234

1

2

3

4

THE TRUST LEVELS OF SESSION DATA

§ Server-sidesessionsshareanIDwiththeclientandstoredataontheserver−AttacksonsessionmanagementfocusonguessingorstealingtheID− Thedatastoredintheserver-sidesessionobjectcanbeconsideredtrusted

§ Client-sidesessionsareacompletelydifferentparadigm− Theactualdataisstoredontheclient,soitcanbeeasilyaccessed− Thedatacomesinfromtheclient,andisuntrustedbydefault

§ Client-sidesessionsrequireadditionaldataprotectionmeasures−Mandatoryintegritycheckstodetecttamperingwiththedata−Optionalconfidentialitymechanismstopreventdisclosureofinformation

SECURITY PITFALL

Mishandlingclient-sidesessiondata

Client-sidesessiondatacanbereadandmanipulated,soyouneedtoensureconfidentialityandintegrity

https://jwt.io/

JWTTOKENS IN PRACTICE

§ JWTtokensonlyrepresentclaimstobeexchangedsecurely− Thedataisbase64-encoded,whichoffersnoprotectionatall− TheJWTspecssupportintegrity(signing)andconfidentiality(encryption)

§ ThedefaultmodeofoperationissigningJWTs− Thesignatureispartofthetoken,andcanonlybegeneratedbytheissuer−AvalidsignatureindicatesthatthedataoftheJWTtokenhasnotbeenchanged

§Manylibrariesofferdecodefunctionsthatdonotcheckintegrity− Failingtofullyunderstandtheimportanceofintegritywillcausemisuse−Decodingisalsoaloteasierthanverifyingtheintegrity

https://github.com/auth0/java-jwt

SECURITY PITFALL

NotverifyingtheintegrityofyourJWTtokens

ManyJWTlibrariesofferfunctionstogetthedatafromatokenwithoutverifyingitsintegrity.Neverusetheminthebackend

Payloaddata

Payloaddata

sign verify

Signingwithasharedsecret Signingwithapublic/privatekeypair

Payloaddata

Payloaddata

sign verify

privatekey publickey

SIGNATURE SCHEMES FOR JWTTOKENS

§ManydevelopersonlyknowaboutsigningJWTswithasharedsecret− Thisisperfectlyvalidwithinoneapplicationorevenwithinonetrustboundary−Breaksdownwhentokensneedtobeverifiedoutsideofyourtrustboundary

§ Thesharedsecretcanneverleaveyourbackendapplication−Donotshareitwithyourclientapplication,or“friendly”APIs− Ifyouneedverificationinthosecases,signtheJWTwithaprivatekeyinstead

§ Theissuershouldbetheonlyoneknowingtheprivatekey− Thepublickeycanbedistributedtoanyone− Tokensaresignedwiththeprivatekey,andverifiedwiththepublickey

SECURITY PITFALL

UsingthewrongsignatureschemeonJWTtokens

SharedsecretsforverifyingJWTtokensareforusewithintheboundariesoftheapplication.Otherwise,useapublic/privatekeypair

https://connect2id.com/blog/using-openid-connect-to-make-assertions-about-end-users

SECURITY PITFALL

Notpropagatingidentityinformation

Callsareoftendelegatedtointernalsystemsorservices.Ensurethattheseservicespossessallrelevantidentityinformationformaking

authorizationdecisionsandcreatinganaudittrail

Cookie:JWT=eyJhbGciOiJIUzI1Ni…

Authorization:BeareryJhbGciOiJIUzI1Ni…

THE PROPERTIES OF COOKIES

§ Cookiesareamess,buttheyarecompatiblewiththeweb−Browsersstoreandsendcookiesautomatically−Cookiesarepresentonallrequests,includingthosecomingfromDOMelements−CookiesarecompatiblewithwebmechanismssuchasCORS,SSE,WebSockets,…

§ Securingcookie-basedmechanismsrequiresalotofeffort−Cookiesecurityflagsneedtobeconfiguredcorrectly−Cookieprefixesofferadditionalsecurity,butrequiremodifyingthename−CookiesenableanastyattackcalledCross-SiteRequestForgery(CSRF)

§ Cookiesareanightmaretosupportinnon-webapplications

THE PROPERTIES OF CUSTOM HEADERS

§ Customheadersarestraightforward,butcanbehardtouse−Nothandledautomatically,sotheapplicationneedstostoreandsendthevalue− ThebrowserwillnotattachittorequestscomingfromDOMelements− TheuseofmechanismssuchasCORS,SSE,WebSockets,… becomesmoredifficult

§ Securingheader-basedmechanismsisalsosurprisinglydifficult− Youhavetodecidewheretostorethedataintheclientapplication− You’relikelytomessupattachingtheheadertooutgoingrequests−ButthegoodnewsisthatcustomheadersdonotsufferfromCSRF

§ Customheadersareabreezetouseinnon-webapplications

https://www.toptal.com/web/cookie-free-authentication-with-json-web-tokens-an-example-in-laravel-and-angularjs

SECURITY PITFALL

Minimizingtheimpactofthetransportmechanism

CookiesareoftenfrowneduponinanAPIworld,andcustomheadersarepreferred.Bothhavevastlydifferentsecurityproperties,

somakesureyouunderstandthemfully

THE UNDERESTIMATED THREAT OF CSRF

websec.be

anysite.io

loginasPhilippe

Welcomepage

Showmessages

Latestmessages

Showobligatorycatpics

Kittensfromhell

https://arstechnica.com/information-technology/2014/03/hackers-hijack-300000-plus-wireless-routers-make-malicious-changes/

CROSS-SITE REQUEST FORGERY

§ CSRFexistsbecausethebrowserhandlescookiesveryliberally− Theyareautomaticallyattachedtoanyoutgoingrequest−Bydefault,there’snomechanismtoindicatethesourceorintentofarequest

§ManyAPIsareunawarethatanycontextcansendrequests−GETandPOSTrequestsareeasytotriggerusingDOMelementsorXHR−PUTandDELETErequestsareadifferentstory−DefendingagainstCSRFrequiresexplicitactionbythedeveloper

§ AtraditionalCSRFdefenseisusinghiddenformtokens

DEFENDING YOUR APIAGAINST CSRFwebsec.be

anysite.io

loginasPhilippe

Welcome,Philippe

Postmessage

Surething,Philippe

Showobligatorycatpics

Kittensfromhell

POST …Cookie: SID=123, XSRF-TOKEN=abcX-XSRF-TOKEN: abc

CookievalueiscopiedtoaheaderbyJavaScriptcode

THE RELATION BETWEEN CSRFAND CORS

§ Cross-originHTTPrequestshavealwaysexistedintheweb− Examplesareloadingimagesfromotherorigins,orsubmittingformsacrossorigins

§ CSRFmattersinanAPIsupporting“traditional”HTTPrequests−GET/POSTrequestswithtraditionalcontenttypesandnocustomheaders− TheserequestscaneasilybeforgedusingtraditionalHTMLelements

§ APIsusing“non-traditional”HTTPrequestsfallundertheprotectionofCORS− SucharequestcanonlybesentfromJavaScriptusingXMLHttpRequest− SucharequesttriggerstheCross-OriginResourceSharing(CORS) securitypolicy− Sucharequestwillonlybeallowediftheserverexplicitlyapprovesit

Content-Type:application/json

X-Show-Me:TheMoney

SECURITY PITFALL

UnderestimatingtheprevalenceofCSRFCSRFattacksexistwhencookiesareusedforkeepingsessionstate.Verifyifyou’revulnerableandimplementappropriatedefenses.

Ifyoudonotusecookies,youdonotneedtoworryaboutCSRF

/users/1’%20OR%20’1’=‘1

statement = conn.prepareStatement("SELECT * FROM BeersWHERE name LIKE ?");

statement.setString(0, parameter);

INPUT VALIDATION IS AN IMPORTANT FIRST LINE OF DEFENSE

§ Limitingthenumberofvalidinputsreducestheattacksurface−Untrusteddatashouldbevalidatedbeforeusingit− Therestrictionsthatcanbeimposeddependonthetypeofcontent

§ Bestpracticesforinputvalidation−Onlyacceptcontenttypesthatyouexpect,andrejecteverythingelse−Validateeveryinputagainstitsexpecteddatatype− Imposesensiblelengthrestrictions,andalwayssetastrictupperbound−Alwaysuseasecureparsertoprocessinput

BUT INPUT VALIDATION ONLY GETS YOU SO FAR

§ Inputvalidationtargetssymptoms,nottherootcauseoftheissue− Injectionneedstobeaddressedinthecode,notattheinputlevel

§Oncethedataiscomplexenough,validationbypasseswillexist−Validationorsanitizationishardtogetright,sodonotsolelyrelyonthem−AgoodexamplearethehugeXSSfilterevasioncheatsheets

§ Andsometimes,it’sjustnottheAPI’sresponsibility−Cross-sitescriptinginwebapplicationsistheperfectexample− TheAPIhasnoideawherethedatawillbeused,soitcannotrenderitsafe− Theclient-sideapplicationneedstohandlethis,ase.g.Angulardoesoutofthebox

SECURITY PITFALL

Overorunderestimatinginputvalidation

Eventhoughinputvalidationisagoodfirstlineofdefense,itwillfailastheonlydefense.Donotrelyoninputvalidationalone

QuestionEverythingHowisthisdifferentfromwhatweusedtodo?

Dowereallyunderstandwhatwe’redoing?

Havewevalidatedtheintegrityandformatofthatdata?

NOW IT’S UP TO YOU …

Secure Share@PhilippeDeRyck