Transcription of PostgreSQL PassTheHash protocol design weakness
1 PostgreSQL pass The hash protocol design weakness Date: Monday, 2nd March 2015 Version tested: PostgreSQL , older ones are affected as well Credits: Jens Steube: __AT__ Philipp Schmidt: __AT__ ThePostgreSQLC hallenge ResponseAuthenticationusingtheAUTH_REQ_M D5methodor simplyconfiguring"md5"astheHostBasedAuth entication(HBA) defaultsettingonmanylinuxdistributionsas wellasrecommendedinthedefault configuration on github: METHOD can be "trust", "reject", "md5", "password", "gss", "sspi", "ident", "peer", "pam", "ldap", "radius" or "cert". Note that "password" sends passwords in clear text "md5" is preferred since it sends encrypted passwords. ,andthatwe candemonstratewithaproofofconcept(POC)co de,isalsoknownasapass the hash (PTH) vulnerability [1].
2 ThebasicideaandproblemofPTHisthatanattac kercanauthenticatetoaservice(inthis casetothePostgreSQLdatabaseserver) informationheneedstoknowisavalidcombinat ionofusernameandthehashedpassword ,froma databasebackuporcouldoriginatefromaveryd ifferentdatabaseincasethecredentials (username and password) were reused. PTHismostprominentlyknownfrommimikatz[2] whereitisusedtoauthenticatetowindows services(forinstancethentlmandoldersamba protocols).Ingeneral,theinformationsecur ity industryclassifiesaPTHvulnerabilityasave rycriticalandsevereproblemsincetheattack er doesnotneedtoinvestmanyresources(money,h ardware,timeetc)toguesstheplaintextof thehashtocomeupwiththeactualpassword[3].
3 Instead,theservicelogincanbesimply accomplishedbygettingandsendingthehashas is,withoutanyneedtohaveknowledgeof the users credentials. ThefactthatthePostgreSQLprotocolisableto useanencryptedcommunicationusingSSL does not affect the ability to exploit the PTH weakness . Technical description of the weakness in PostgreSQL PostgreSQL server store user passwords in the following salted and hashed format: MD5 ($ pass . $username) where$usernamedenotesthePostgreSQLaccoun t(role)and$passistheactualplaintext $saltand$usernameindistinguishable theconcatenation of $ pass and $username will be denoted by P (except if the contrary is explicitly stated).
4 ThecurrentPostgreSQLC hallenge ResponseAuthenticationprotocolusing AUTH_REQ_MD5 works like this: generates R = 4 random bytes sends R to the client computes F_c = H(H(P) . R) sends F_c to the server has H(P) stored in the database computes F_s = H(H(P) . R) and compares F_s with F_c Notes: The hashing algorithm H is always MD5 for the AUTH_REQ_MD5 method F_candF_sshouldbeidenticalbutweredisting uishedherewithasuffixtoemphasize thatF_cisalwayscomputedonclientside,whil eF_sisnewlyandindependently computed on server side Byanalyzingstepnumber3,onecaneasilyident ifythemainweaknessofthisprotocol, theH(P)valueishashedagain(byconcatenatin gthechallenge)butduringthewhole communication(step1to6)anattackerdoesnot needtoproofthathehastheactualPvalue (password).
5 AnattackerjustneedstohaveH(P)whichdoesno tdirectlyproofthatheknows thepassword(forthereasonsmentionedbefore ).Furthermore,H(P)isdirectlystoredinthe serverdatabase,thisdoesweakentheprotocol evenmore,sincetheclient/attackercould have obtained H(P) from there. Therefore,wewouldsaythatthisproblemcould beseenasaprotocoldesignflawandto proofthis,wewillattachapatch/difftothisd ocumentsuchthatitiseasiertounderstandthe actual"shortcut"theattackercouldusetocir cumventthesecureauthentication(whichshou ld always ensure that the actual user credentials were indeed involved on client side). Demonstration Thefollowingstep by convenience,wedidapplythechanges(apatch) directlytothelibsinPostgreSQL.
6 Alternativeanattackercouldsimplybuildast andaloneutilitythatbehaveslike"psql"or "pg_dumpall" etc. Theattacheddifffileisnotapatchtosolvethi sproblem,insteaditisademonstrationofthe weakness . It will only modify the code of the client. (wedidusegitcommitwithsha1 checksums up to ee4ddcb38a0abfdb8f7302bbc332a1cb92888ed1 ): git clone the PostgreSQL directory: cd PostgreSQL the patch: git apply the PostgreSQL project: ./configure make: make && make install on your distro (and installation path), you may need to set $PATH: export PATH=$PATH:/usr/local/pgsql/bin/ the database (here we use a temp directory ~/postgres_data/): pg_ctl D ~/postgres_data/ init (AUTH_REQ_MD5),ifnot editthefile~/postgres_ checkthat"md5"isusedas METHOD: vim ~/postgres_ the PostgreSQL database server: postgres D ~/postgres_data (herewedidusetheunpatchedpsqlbinarybutit doesn't really matter).
7 Psql template1 CREATE ROLE postgres WITH PASSWORD 'hashcat' ALTER ROLE postgres WITH LOGIN (thiswon'trequiretheusertoinputtheactual password,weonlyneedthe" hash "intheformat" md5"+the32hexadecimalMD5 hash ): psql U postgres Notes: Whilewedemonstrateherespecificallywithth epsqlutilitywhichcanexploitthisPTH weakness ,weactuallymeanalltheotherPostgr eSQLtoolsthatusethisfront endlibs too(andasnotedaboveitisnotlimitedtothis, attackerscoulddevelopstandalone tools) The modified psql utility will ask for a hash instead of a password on the prompt: hash : or in case the U switch is used: hash for user [username]: We have developed two different patch files: thefirstone ismeanttobecompleteandincludes some additional and unrequired front end tweaks Theseconddifffile wasinsteaddesignedtoinclude just the changes that are necessarily required for this demonstration to work Anattackerneedstoinputthehashasdemonstra tedbelow, "md5" followed by 32 hexadecimal characters (the actual MD5 hash ) Toconcludethisproofofconceptdemonstratio n,hereisanexamplehowanattackerwould et onwhichhegained access already: postgres@et:~$ pg_dumpall r.
8 CREATE ROLE postgres ALTER ROLE postgres WITH SUPERUSER INHERIT CREATEROLE CREATEDB LOGIN REPLICATION PASSWORD 'md5a6343a68d964ca596d9752250d54bb8a' Now that the attacker knows the hash , here's an example how he can use the information to connect to a different remote database on host sf using our patched client. The client will ask for the hash instead of the password. postgres@et:~$ psql h sf hash : md5a6343a68d964ca596d9752250d54bb8a psql ( , server ) SSL connection ( protocol : , cipher: DHE RSA AES256 GCM SHA384, bits: 256, compression: off) Type "help" for help. postgres=# Just as a side note the password used for this demo is "hashcat" and user is "postgres": postgres@et:~$ echo n hashcatpostgres | md5sum a6343a68d964ca596d9752250d54bb8a Transitioning to a more secure hash (Preparation) BeforewearegoingtoshowhowtosolvethePTHis sueitselflet sdiscusshowtotransition handy within the PTH solution.
9 HashthecurrentMD5valuewithahashalgorithm Hofyourchoiceandreplaceitwith ,justforexample,storebcrypt(MD5(P))inste adof justMD5(P).Thisenablestheservertoautomat icallyconvertallexistinghashesasit testthecurrenthashinthedatabaseonstartup ,findoutifthehashisstillstoredinthe "old"format(forinstanceifthesignaturesta rtswith"md5")andthenautomatically convert all hashes manypeoplesay,thereputationofMD5isdamage dandthereareenoughfreeand much more secure alternatives. The advantage of this is you can use H(P) whenever we stated H(H(P)) The disadvantage of this is that you have to ask the user for a new password Intheprotocoldescriptionbelowweassumetha ttheserverdatabaseonlystores H(H(P))anddoesneitherknowH(P),norisiteas ytoderiveH(P)fromH(H(P)).
10 The onlyreasonablewayanattackercouldcomeupwi thH(P)istoguessthepasswordP itself and this should be made very hard by using a secure hashing algorithm the username. This has the following effect: Ifauserisgettingrenamed, userisforcedtosupplyanewpassword(orthesa meoneagain).Howeveryou can not do these changes without user interaction InabiggernetworkwithseveralPostgreSQLdat abaseinstallationsitislikely thatoneandthesamepersonhasaccesstosevera ldatabasesusingthesame ,byexploitingthePTHissue,it senoughto havethedumpofoneofthedatabasestoaccessal ldatabasesbecausethe salt is not unique for each database.