a pentesters guide to hacking activemq based …...8 a pentesters guide to hacking activemq-based...

27
A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications 1 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER

Upload: others

Post on 29-Jun-2020

27 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

1 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

Page 2: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

2 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

Table of Contents

4 Introduction4 Messaging 1015 Anatomy of a JMS Message5 Message Broker6 Messaging Models7 JMS API8 Apache ActiveMQ Basics8 ActiveMQ Authentication Options10 ActiveMQ Authorization Controls11 ActiveMQ Administration Console11 Pentesting JMS Applications11 DiscoveryandConfiguration11 UnderstandingActiveMQConfigurationFile13 ReviewforWeakConfigurationandKnown Vulnerabilities14 Data Protection in Storage and Transit14 Insecure Communication14 Insecure Password Storage14 Weak Encryption Password15 UnencryptedKahaDB15 User Management and Authentication15 No Authentication15 Simple Authentication Plug-In15 JAAS Authentication Plug-In15 Account Lockout Testing

Author

This white paper was written by:Gursev Singh Kalra, Senior Principal Consultant,McAfee® Foundstone® Professional Services

Page 3: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

3 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

Table of Contents, continued

16 Data Validation and Error Handling16 Injection Attacks16 Attacking Other Clients17 Authorization17 DestinationAccess17 Exploitation17 Reading Queues with QueueBrowser18 RetrievingMessagesfromTopicswithTopicSubscriber18 RetrievingMessagesfromTopicswithDurable Subscribers19 AdditionalDurableSubscriberAttacks19 RetrievingStatisticsfortheBrokerandits Destinations20 DynamicDestinations20 JMSDigger―AGUI-BasedJMSAssessmentTool20 Generic JMS Operations20 ActiveMQSpecificOperations21 Conclusion22 Appendix A22 JMS API-Based Anonymous Authentication Check23 JMSAPI-BasedCredentialBruteForceCode24 ExamplePasswordandConfigurationFileDecryptionCode27 About The Author27 About McAfee Foundstone Professional Services27 About McAfee28 About McAfee

Page 4: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

WHITE PAPER

SustainableSecurityOperations

4 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

Optimize processes and tools to make the most of your team’s time and talent

IntroductionEnterprise Messaging Systems (EMS) form the transactionalbackboneofmanylargeorganizationsworldwide.Theyarehighlyreliable,flexible,andscalablesystems that allow asynchronous message processing betweentwoormoreapplications.Thispaperprovidesguidance on penetration testing techniques to assess the security of ActiveMQ1-basedEMSSystemswrittenusing Java Messaging Service ( JMS) API.2,3 Applications thathavebeenwrittenusingJMSAPIarealsoknownasJMS Applications.

ThepaperbeginswithanintroductiontoJMSconceptsthat are relevant to the penetration testing techniques discussedafterwards,andthenintroducesJMSDigger,4 an open-source tool to engage and assess ActiveMQ-basedJMSApplications.

Please note that this paper does not aim to provide a comprehensive tutorial on JMS concepts or on writing codebasedonJMSAPI.TherearemanyexcellentJMS5 and ActiveMQ6booksthatyoucanrefertoifyouareinterested.

Messaging 101Sun Microsystems created JSR-9147 as JMS API specificationwithanaimtoprovideanabstractinterfaceto communicate with messaging providers and to write portablemessagingclients(inJava)forJMS-compliantmessagebrokers.JMSapplicationsaremadeupofseveral JMS clients and generally one JMS provider. The JMS provider is also known as a messaging server. The JMS clients create messages and send those messages totheJMSprovider,whichinturnroutesthemessagestotheotherclientsbasedonitsconfigurationandbusinessrules.

Letusnowunderstandthestructureofamessage,messagingmodels,andtheJMSAPI.

Anatomy of a JMS MessageMessages are used to deliver application data and event notifications.AJMSMessageismadeupofmessageheaders,messageproperties,andamessagebodyasshownintheimagebelow.Messageheaderscontainmetadatathatdescribesmessageattributeslikemessagepriority,messageID,messagetype,messageroutinginformation,andmessageexpiry,amongothers.

Page 5: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

5 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

Message properties are the additional headers that can beaddedtoamessagebythedeveloperormessagebroker,orcanbeJMS-definedproperties.Themessagebodycontainstheactualcontentthatistobedelivered.

Messagesaredeliveredbetweentheclientsviavirtual channels called destinations that are hosted bythemessagebroker.JMSAPIsupportssixprimarymessage types:

1. Message: The Message type has no payload and is typicallyusedforeventnotifications.

2. TextMessage: The TextMessage type carries plaintextoritcanbeusedtocarryspecializeddataformatslikeXML,SOAP8messages,JSON,9 and others as its payload.

3. MapMessage: The MapMessage type contains name-value pairs as its payload.

4. BytesMessage: The ByteMessage type contains anarrayofprimitivebytesasitspayload.

5. ObjectMessage: The ObjectMessage type containsserializedJavaobjectsasitspayload.

6. StreamMessage: The StreamMessage type contains a stream of primitive Java types like byte,int,char,andothersasitspayload.

Messagesareneveraddressedtoanyspecificclientbutto the destinations. The message delivery mechanism is determinedbythemessagingmodel(discussedbelow)usedbyaparticularapplication.

Message BrokerMessagebrokersformthecoreoftheEnterpriseMessagingSystems.Messagesaretransmittedbetweenthemessagingclientsviavirtualchannelshostedbythemessagebrokers,alsocalledmessagingservers.These virtual channels are also called destinations. Themessagebrokersensurethatapplicationdataisdeliveredwithhighreliability,inanefficientmanner,andminimizecouplingbetweenmessagingclients.

AlargenumberofmessagebrokerslikeActiveMQ,RabbitMQ,SonicMQ,andIBMWebSphereMQsupportJMS API for message exchange.

Figure 1. A JMS Message.

Headers

Properties

Body

Page 6: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

6 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

Messaging ModelsMessagingmodelsrepresentdifferentapproachestomessaging.Amessagebrokermaysupporteitheroneorboththemessagingmodelsdiscussedbelow.Messagingmodels are also known as messaging domains.

Point-to-PointModelThe virtual channel used for communication in the point-to-point messaging model is called a Queue. In thismodel,theJMSclientsthatproducethemessagesarecalledthesenders,andtheclientsthatconsumethemessages are called the receivers. In the point-to-point messagingmodel,eachmessagecanbeconsumedonlyonce,anditgetsdiscardedafteritisdeliveredtoanyone receiver. The send-and-receive operations to and fromQueuescanbeperformedeitherinasynchronousor an asynchronous fashion. The receivers can also acknowledge message consumption to the sender. The point-to-point messaging model is also referred to as p2p model.

ThemessagesonaQueuebehavedifferentlywhenaQueueBrowser API is used to retrieve messages without disrupting a Queue’s contents. When a QueueBrowser isused,thequeryingJMSclientreceivesanenumerationofallmessagesontheQueueatapointintime,whichthe JMS client can iterate through and analyze Queue contentsforanybusinessdecisions.Thisfeatureisveryuseful as it allows one to analyze Queue content without losing any messages.

Publish-and-SubscribeModelThe virtual channel used for communication in the publish-and-subscribemessagingmodeliscalledaTopic. The JMS clients that produce messages are called thepublishersandtheJMSclientsthatconsumethemessagesarecalledthesubscribers.ThepublisherssendmessagestotheTopicandthesubscribersreadthemessagesofftheTopic.However,thereisnodirectcommunicationbetweentheJMSpublishersandsubscribers.Thepublish-and-subscribemessagingmodelisalsoreferredtoaspub/submodel.Thepub/submessagingmodelissubscriptionbased.

Figure 2. The image shows a point-to-point messaging model.

Sender

Queue

Receiver

Message

Acknowledgement

Message

Page 7: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

7 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

Therearetwotypesofsubscribersinthepublish-and-subscribemodel―nondurableanddurablesubscribers.

Thenondurablesubscribersreceivethemessagesonly when they are connected to and actively listening on a particular Topic. All messages during the period ofinactivityarelostforthenondurablesubscribers.Durablesubscribers,however,receiveallmessagesevenifthesubscriberisneitheractivenorconnectedtothemessagebroker.Durablesubscribersretainthemessagesuntilthemessagesareretrieved,oruntilthemessagesexpire,whicheveroccursfirst.Durablesubscriberscanbeeitherdynamicallyorstaticallycreatedbythebrokeradministratorsintheconfigurationfiles.Durablesubscribersareuniquelyidentifiedbyacombinationofaclientidentifier(fortheJMSclient)andadurablesubscribername.

JMS APIJMSisanAPIspecificationandnotawire-levelprotocol.Itisavendor-agnosticAPIthatcanbeusedwithanyJMS-compliantmessagingbroker.Dependingonthemessagebroker,theJMSAPIcanalsobeusedtocommunicatewith non-Java or non-JMS messaging clients as we willdiscussinthesectionsbelow.TheJMSAPIcanbeclassifiedintothreecategories:

1. The general API

2. Point-to-point API

3.Publish-and-subscribeAPI

TheAPIusedforwritingaJMSapplicationisbasedon the messaging model used. The April 2002 JMS 1.1specification,however,allowsthegeneralAPItosend and receive messages to and from Queues or Topics with some restrictions. Since the JMS API code isportable,itcanbeusedtoassessJMSapplicationscreatedusingdifferenttypesofmessagebrokers.

Figure 3. Image shows a publish-and-subscribe messaging model.

Subscriber

Subscriber

Publisher

TopicMessage Message

MessageSubscriber

Page 8: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

Apache ActiveMQ BasicsActiveMQisanopen-source,JMS-compliantmessagebrokerwithafullJMSclient.ItprovidesanumberofclientlibrariesindifferentprogramminglanguageslikeJava,Ruby,Python,C,C++,andC#andcanthereforebeusedtointegrateclientswrittenindifferentprogramminglanguages.Forexample,Java-basedJMSclientscantalktomessagingclientswritteninC/C++.Itsupportsarangeofcommunicationprotocolsincluding―butnotlimitedto―AMQP,OpenWire,WebSockets,andStompasshowninthelistbelow.

■ AMQP ■ RSS ■ HTTP ■ STOMP

■ REST ■ WebSockets ■ OpenWire ■ XMPP

ActiveMQishighlyconfigurable,andmostoftheconfigurationinformationlivesaschildnodesinsidethe brokerelementofitsconfigurationfile.Theconfigurationfilecanbereviewedtoobtaintheinformationsuchas:

1. Topic names

2. Queue names

3. Transportprotocolsenabled,assignedports,andtheirconfiguration

4. Credentials

5. AuthenticationandAuthorizationdetails,etc.

Figure 4. Image shows a Topic and Queue as seen in ActiveMQ

configuration file.

Figure 5. Image shows openwire and amqp transport protocols enabled in ActiveMQ configuration file.

ActiveMQ Authentication OptionsActiveMQ supports several mechanisms to authenticate JMS clients. ActiveMQ’s authentication schemes are plug-in-based,andtheycanbechangedonthebrokerwithalmostnoimpactontheJMSclientcode.Thisofferstremendousflexibilitytotheprogrammers.WewillnowlookatthedifferentauthenticationschemessupportedbyActiveMQ.

The Default (No Authentication)Whennoauthenticationplug-inisenabled,ActiveMQacceptsconnectionfromanyJMSclient,withorwithoutanyusernameandpassword,andallowstheclienttointeractwithQueuesandTopics,andperformotheractionspermittedaspertheJMSAPIspecification.Thismode is similar to anonymous authentication mode for FTP,anditoffersnosecurity.

Page 9: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

9 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

SimpleAuthenticationPlug-InActiveMQ does not allow anonymous authentication whenthisplug-inisenabled.Thesimpleauthenticationplug-in uses hardcoded usernames and passwords in theconfigurationfile.Thesimpleauthenticationdoesnotofferanymechanismtoenforceaccountlockoutswithfailedloginattempts.Additionally,thesimpleauthenticationplug-inisnotscalableandisinsecurebecauseitrequirescleartextusernameandpasswordstobehardcodedintheconfigurationfiles.

JAAS10-BasedAuthenticationActiveMQ can also support custom authentication mechanismswithitsJAASplug-insupport.Also,someorganizations may want to centrally manage ActiveMQ authentication rather than maintaining separate credentialsforthemessagingbrokers.Theycanleverage ActiveMQ’s JAAS plug-in and write their own authenticationroutinestoquerytheircentralLDAPserverortheircentralSQLdatabasesforauthentication.

Figure 6. Image shows simple authentication plug-in enabled in ActiveMQ configuration file.

Figure 7. Image shows JAAS plug-in enabled in ActiveMQ configuration file.

Page 10: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

10 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

ActiveMQ Authorization ControlsActiveMQ’s authorization engine applies the security policiesandenforcesthetypeofaccess(read,write,administer,etc.)aJMSclientisallowedfordifferentTopics,Queues,andthemessages.Itsupportstwotypesofauthorizationcontrols.Thefirstisatthedestinationlevel,andthesecondisatthemessagelevel.

Destination Level AuthorizationDestinationlevelauthorizationcontrolsrequiretheJMSclients to have a certain minimum level of privileges beforetheyareallowedtoconnecttoanyTopicorQueue. The access control rules can selectively allow or denyread,write,oradministrationaccesstodifferentJMSclientsforanyTopicorQueuebasedonActiveMQconfiguration.

Message Level AuthorizationMessagelevelauthorizationallowsfine-grainedaccesscontrolwheretheaccesschecksareenforcedbasedonthecontentsofamessage.Typically,theaccesscontrollogiciswrittenasaJavaplug-in,compiledandpackagedintoaJARfile,andthenaddedtoActiveMQ’sclasspath.Theplug-ininformationisthenspecifiedintheActiveMQconfigurationfile.

Figure 8. Image shows Queue authorization entry in ActiveMQ configuration file.

Figure 9. Image shows message level authorization plug-in configuration

Page 11: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

11 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

ActiveMQ Administration ConsoleActiveMQprovidesapowerfulweb-basedadministrationconsole which runs on Jetty.11 It allows you to manage severalaspectsofthemessagebrokerasmentionedbelow:

1. Create,read,update,ordeleteTopicsandQueues.

2. Createand/ordeletedurablesubscribers.

3. Viewactiveconnections.

4. Send messages to Topics and Queues.

Thedefaultwebconsoleconfigurationrunsoverplain-textHTTPprotocolandisprotectedbybasicauthentication starting with version 5.8.0.

Now that we have some understanding of ActiveMQ andJMSconcepts,wewillnowlookatthesecurityassessment methodology for JMS applications.

Pentesting JMS ApplicationsThePentestingmethodologydiscussedbelowismodeled around McAfee®Foundstone® Professional Services’ security assessment framework and assumes thattheenvironmentundertestisbasedonActiveMQ.

Please note that even though the methodology focuses onActiveMQ,thetechniquesaregenericandcanbeappliedtoassessmessagingapplicationsbasedonothermessagebrokers.

DiscoveryandConfigurationUnderstandingActiveMQConfigurationFileRequest the application owners to provide you with the ActiveMQconfigurationfileandanalyzeittoextractthefollowinginformation:

■ Authentication and Authorization mechanisms used ■ Topic and Queue names ■ Communicationprotocolsenabledandused ■ ActiveMQwebconsoleconfiguration ■ Network interfaces and corresponding listening ports

Analyze the installed ActiveMQ version for known configurationissuesandvulnerabilities.Asummaryofcommonconfigurationissuesandafewvulnerabilitiesthatwereidentifiedduringmyresearchisprovidedbelow.

1. ActiveMQversions5.8.0onwardsprotecttheirwebadministrationconsolewithbasicauthenticationwithdefaultcredentialsofadmin/adminwhichisseldomchanged.

2. Thewebadminconsolerunsoverplain-textHTTPprotocol,whichisinsecure.

Page 12: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

12 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

3. ActiveMQ’swebconsolepriorto5.8.0didnotrequireauthentication(seeCVE-2013-306012). Random Internet users could connect to ActiveMQ and perform administration functions like viewing contents of JMS destinations,deletingJMSdestinations,andcreatingnewJMSdestinationsanddurablesubscribers―among other operations. Unauthorized access to this interface can allow attackers to cause severe damagetothemessagingapplication,andanyonewho knows the administrative URL can potentially manage the ActiveMQ instance. Performing simple Internet searches reveals several open and exposed productionActiveMQinstancesasshowninFigures10and 11.

ReviewforWeakConfigurationandKnown Vulnerabilities

Figure 11. An unprotected ActiveMQ administrative interface available over the Internet shows active client connections.

Figure 10. An unprotected ActiveMQ administrative interface available over the Internet shows queue names.

Page 13: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

13 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

4. ActiveMQ’s transport connectors and administrative webconsoleapplicationareconfiguredbydefaulttolisten on 0.0.0.0.Becauseofthis,theystartlisteningon all network interfaces of the machine and end up exposed on the Internet.

This allows inadequately hardened ActiveMQ instancesonperimeterdevicestobesusceptibletoattacks originating from the Internet. The attackers couldpotentiallyconnecttoActiveMQserver,retrieveorsendmessages,editordeleteJMSdestinations,andperformotheractionspermittedbythebroker’sAPI.

5. Make sure to check ActiveMQ version for knownvulnerabilities.Forexample,MultipleXSSvulnerabilities(CVE-2013-1880,13CVE-2013-1879,14 CVE-2012-609215) were reported in ActiveMQ web console.

Figure 12. ActiveMQ openwire configuration to listen on 0.0.0.0.

Figure 14. Administrative web console of a production ActiveMQ instance available on the Internet.

Figure 13. Connection to an open ActiveMQ broker’s openwire interface over the Internet with ‘ActiveMQ’ string in response.

Page 14: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

14 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

Data Protection in Storage and TransitInsecure CommunicationActiveMQoptionallyofferstransportlayersecurity,whichcanbeimplementedfortheapplicationlayerprotocolsitsupports.However,thedefaultActiveMQconfigurationdoesnotenforcetransportlayersecurityandisvulnerabletoman-in-the-middle(MiTM)16 attacks whereanattackercancapture,monitor,andmodifyalltrafficflowingbetweentheJMSclientsandthemessage broker.

ThisvulnerabilitycanbespottedwhilereviewingActiveMQconfigurationfile,wheretheabsenceofsslContextelementgivesitaway.However,itisimportant to not rely on the presence of this header alonebuttothoroughlyreviewtheconfiguration.17

Iftheconfigurationfileisnotavailable,theJMSclientandmessagebrokercommunicationmustbereviewedwithhelpofpacketsnifferslikeWireshark.18

Insecure Password StorageThe simpleAuthenticationPlugin allows unencryptedusernamesandpasswordstobestoredinActiveMQconfigurationfiles.Also,thejaasAuthenticationPlugin allows for an externalfile withplaintextcredentialstobeusedfor authenticationusers.

ItisimportanttoreviewtheActiveMQconfigurationfilesandthejaasAuthenticationPlugin configurationdetailstoensurethatcredentialsarenotstoredinclearonthemachine.Also,ifthejaasAuthenticationPlugin uses an external databasetostorecredentials,itmustbereviewedforunencrypted storage.

Weak Encryption PasswordActiveMQoptionallyusespassword-basedencryption(jascrpyt19library’sStandardPBEStringEncryptor class) to encrypt and store login credentials in itsconfigurationfiles.Usingweakpasswordstoencrypt login credentials can potentially expose these credentials to anyone who has access to these configurationfiles.Systemadministratorsoftenrelyonpassword cracking tools like John the Ripper20 to audit passwordstrength.TheJMSDiggertool,whichwewillbrieflydiscussinthiswhitepaper,canalsoassistwithActiveMQ password audits.

Please see Appendix A for sample source code to decryptActiveMQ’sencryptedrecordsbybruteforce.

Figure 15. The image shows encrypted strings in the default credentials-enc.properties file that is shipped with ActiveMQ.

Page 15: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

15 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

Unencrypted KahaDBKahaDBisthedefaulthigh-performance,data-persistencedatabaseusedbyActiveMQ.Thisdatabaseisneitherencryptedbydefaultnorhasthecapabilitytoperformencryption.MakesureKahaDBinstanceisstoredonanencryptedfilesystempartitionforbetter security.

User Management and AuthenticationNo AuthenticationThedefaultActiveMQconfigurationdoesnotofferanyauthentication and hence there are no user credentials. ThiscanbetestedbyreviewingtheconfigurationfileforabsenceofsimpleAuthenticationPlugin and jaasAuthenticationPlugin plug-ins.

Duringablackboxpenetrationtest,youcanusethecode snipped from Appendix A to check for anonymous authentication,oryoucanalsoconsiderusingJMSDigger to check for the same.

SimpleAuthenticationPlug-InThe simple authentication plug-in uses hardcoded usernamesandpasswordsintheconfigurationfileandisconfirmedbythepresenceofsimpleAuthenticationPlugin child element in the configuration,alongwiththeusercredentials.

Thisplug-inmustnotbeusedsinceitcannotenforceaccount lockouts on repeated failed login attempts and henceoffersnoprotectionagainstpasswordbruteforce attacks.

Also,theonlymechanismtochangeuserpasswordsordisableaccountsistodirectlyedittheconfigurationfiles.

JAASAuthenticationPlug-InjaasAuthenticationPlugin relies on user-written JAAS plug-in to perform authentication decisions. An insecurely written plug-in can expose ActiveMQ authenticationtotypicalinjectionvulnerabilitieslikeSQLinjectionandLDAPinjection,amongothers,aswewillseeinthedata-validationsectionbelow.

Account Lockout TestingPleasenotethatthereisnomechanismtodifferentiatebetweensimpleAuthenticationPlugin and jaasAuthenticationPluginfromablackboxperspective unless jaasAuthenticationPlugin enforces account lockout on numerous failed login attempts. It is recommended that account lockout testingbeperformedusingthecustomcodeinAppendixAorbyusingJMSDigger.

Page 16: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

16 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

Data Validation and Error HandlingInjection AttacksActiveMQ-basedapplicationsmayoftenrelyoncustomcodetoimplementJAASplug-inforauthentication,custom authorization code to perform message level authorizationdecisions,etc.

Insecurely written code can expose ActiveMQ authenticationtotypicalinjectionvulnerabilitieslikeSQLinjectionandLDAPinjection,amongothers.Thevulnerableimplementationscanbeexploitedtobypassauthentication and gain access to critical resources. You canalsoleverageJMSDiggertotestandfuzzcustomauthentication implementation to discover potential injectionflaws.

The following image shows a SQL injection error in a JAASmodulethatusesMySQLforbackenddatabase.

Attacking Other ClientsMessaging applications often have their clients written indifferentprogramminglanguagesandtechnologies.Insecurelywrittenclientscanbetargetedtogainunauthorized access to other organization systems or infrastructure.Forexample,bufferoverflowvulnerabilityinaC/C++-basedmessagingclientcanleadtoremotecommandexecutionasdepictedinFigure17.

Asdiscussed,messagingclientsthatconsumemessagesfromotherclientscanbeexposedtomaliciousattacks.One such example is when TextMessage is used to exchangeXMLdatabetweentheclients.

WhenXMLdataisexchanged,failuretosanitizetheXMLandinsecureXMLparsingconfigurationcanleadtocross-client attacks like XML Entity Expansion21 or XML External Entity Injection22 attacks. Testers must keep an open eye for such scenarios.

Figure 16. In the image, box 1 shows a regular authentication failure, box 2 shows SQL error indicating SQL injection vulnerability.

Figure 17. Command execution on a remote client via a message.

Client B (C/C++)Client A

MessageBroker

/bin/sh

Message Message

Page 17: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

17 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

AuthorizationDestination AccessActiveMQ does not allow JMS clients to connect to a QueueorTopicthatthey’renotauthorizedtoaccess.ForeachattempttoconnecttoQueuesorTopics,thetestermustensurethatconnectionattemptsaredeniedbythemessagebroker.

A successful connection is indicative of missing or weak accesscontrols.Theconfigurationfilemustalsobereviewed for potentially weak authorization controls.

ExploitationOnce you have assessed Authorization controls and identifiedthevulnerabilities,thenextstepwillbetoperform active exploitation where you will retrieve messagesfromTopicand/orQueues.TheavailabilityoftheJMSAPIwithsomanydifferentmessagingproducts allows developers to quickly port their applicationsbetweendifferentmessagingproviders,andthisflexibilitycanalsobeleveragedtowritecodeforoffensivepurposeandtargetseveralmessagingproviders and messaging applications. Let us now look at some of the exploitation techniques using JMS API.

Reading Queues with QueueBrowserAJMSQueueremovesamessageonceitisreadbyanyofthequeuereceivers.AQueueBrowsercanbeusedto read messages from a Queue without removing themfromtheQueueandavoidbeingdetected.ItalsooffersaconsistentbehavioracrossdifferenttypesofJMS providers.

Steps to retrieve messages from a Queue with QueueBrowser:

1. Initialize the environment as per the JMS provider.

2. Create an InitialContext.

3. ObtainaConnectionFactoryviaJNDIlookup.

4. ObtaintheQueueobjectviaJNDIlookup.

5. Use ConnectionFactory from step 3 to create a new Connection.

6. Use the Connection created in step 5 to create a new Session.

7. Use the Session from step 6 to create a QueueBrowser.

8. Start the Connection.

9. ObtainanenumerationfromtheQueueBrowser’s getEnumeration method.

10. Iterate over the enumeration and write all the messages to a local storage.

YoucanalsouseJMSDiggertoachievethesame.

Page 18: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

18 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

Retrieving Messages from Topics with TopicSubscriberReadingmessagesofftheJMSTopicsiseasierthanretrieving them undetected from a QueueBrowser. A JMSclientcansubscribetoaTopicanditwillreceiveallmessagesaddressedtothespecificTopicwheneveritisconnectedtothemessagebroker.

Steps to retrieve messages from a Topic using TopicSubscriber:

Part A

1. Initialize the environment as per the JMS provider (similartobruteforceexampleabove).

2. Create an InitialContext.

3. ObtainaConnectionFactoryviaJNDIlookup.

4. ObtaintheTopicobjectusingJNDIlookup.

5. Use ConnectionFactory from step 3 to create a new Connection.

6. Use the Connection created in step 5 to create a new Session.

7. Use the Session from step 6 to create a TopicSubscriber.

8. Set the MessageListener for the TopicSubscriber.

9. Start the Connection.

Part B

10. Implement the MessageListener interface (onMessage method).

11. Code inside the onMessage method should write each method to a local storage.

YoucanuseJMSDiggertoachievethesameeffect.

Theexampleabovewasofanon-durablesubscriptionthat retrieves messages for as long as its session is alive.SinceyouneedtobeconnectedtothemessagebrokerwhenyouuseTopicSubscriberstoreadTopiccontents,anyactiveandliveconnectionsfromunknownIPaddressesmaybedetected.AnotherapproachofretrievingmessagesfromJMSTopicsisbyusingdurablesubscriptions.

Retrieving Messages from Topics with Durable SubscribersThere is no need to have a live connection when using durablesubscribersformessageretrieval.Thishelpsusavoid detection.

StepstoretrievemessagesfromaTopicusingdurablesubscribers:

1. Initialize the environment as per the JMS provider.

2. Create an InitialContext.

3. ObtainaConnectionFactoryobjectviaJNDIlookup.

4. ObtaintheTopicobjectviaJNDIlookup.

5. Use ConnectionFactory from step 3 to create a new Connection.

Page 19: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

19 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

6. Assign a client name to the Connection.

7. Use the Connection created from step 5 to create a new Session.

8. Use the Session from step 7 to create a “named” durablesubscriberincontextofaTopicobtainedinstep 4.

9. Start the connection.

10. Perform synchronous reads for one message at a time and write them to local storage.

Steps1through8willcreateanewdurablesubscriberiftheclientIDanddurablesubscribernamecombinationisnotunique,orelseconnecttoanexistingone.Steps9to 10 retrieve messages and write them to local storage.

JMSdoesnotenforceanyrestrictionsonclientIDusageordurablesubscribername,soitispossiblethat‘clientA’createsadurablesubscriberand‘clientB’(potentiallymalicious) reads data out of it.

Additional Durable Subscriber AttacksYoucancausearesourcestarvationDenialofServicebycreatingdurablesubscribersonmessagebrokerwithvery high transactional loads and disconnecting from themessagebroker.Themessagebrokerwillthenstartaccumulatingmessagesuntilthedurablesubscriberiserased,messagesexpire,ormessagesarereadfromit.

Additionally,itispossibletoerasedurablesubscribersbyspoofingtheclientIDandprovidingadurablesubscribernametocausedatalossforlegitimateclients.

Retrieving Statistics for the Broker and its DestinationsActiveMQ supports a statistics plug-in23thatcanbeusedtoretrievemetadataaboutthebrokeranditsdestinations. This plug-in also supports wildcard charactersthatcanretrieveinformationaboutallthedestinationsinonego.Criticalinformationobtainedcanthenbeleveragedtolaunchfurtherattacksonthebrokeranditsdestination.Forexample,brokerstatisticstypically include system name and ActiveMQ path as showninFigures18and19.

Figure 18. ActiveMQ broker statistics from a test instance using JMSDigger code.

Page 20: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

20 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

Dynamic DestinationsTheJSR914specificationsuggeststhatJMSdestinationsareadministeredobjectsthatcanonlybecreatedbysystemadministratorsandretrievedbytheJMSclientswithJNDI24beforeuse.However,ActiveMQdeviatesfromthespecificationandallowsdynamicdestinations,whichcanbeprogrammaticallycreatedandthenusedbytheJMS clients.

Suchbehaviorcanbeleveragedtocompromisethesecurityofthemessagebroker.Forexample:

1. Alargenumberofdestinationscouldbecreatedtoconsume ActiveMQ resources and potentially cause integrityandavailability(resourceconsumptionandDenialofService)issues.

2. Maliciousdestinationscanbecreatedoninsecurebrokersandthenusedforunauthorizedmessaging,botnetC&C,andtowardsotherendresults.

JMSDigger―AGUI-BasedJMSAssessmentToolJMSDiggerisanewGUI-basedtoolthatcanhelpsecurityprofessionalsengageandassessActiveMQbasedJMSapplications. It has the following features.

GenericJMSOperations1. Anonymous authentication check

2. Manual authentication check

3. Automatedcredentialbruteforceandfuzzing

4. RetrievemessagesfromTopics,Queues,anddurablesubscribers.

5. Createnewdurablesubscribers.

6. Eraseexistingdurablesubscribers.

ActiveMQSpecificOperations1. RetrieveActiveMQbrokeranddestinationstatistics

2. Create new destinations (Topics or Queues).

3. ActiveMQ password decryption

Figures20and21belowshowaJMSDiggerscreenshotand example message retrieval from the test application.

Figure 19. Image shows TestQueue statistics retrieved using JMSDigger.

Page 21: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

21 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

ConclusionJMSApplicationshavebeendeployedfarandwideandsupportseverallargeorganizationsworldwide.However,theyhavenotbeenextensivelyexploredforsecurityissues. Penetration testers are encouraged to review JMSAPI,familiarizethemselveswithmessagebrokersoftheirchoice,andgainadeeperunderstandingofthetechnologies so they can help secure their applications.

Figure 20. Image shows JMSDigger configuration check. Figure 21. JMS destination’s StreamMessage dump with JMSDigger.

Page 22: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

22 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

Appendix AJMSAPI-BasedAnonymousAuthenticationCheck

package com.mcafee;

import javax.jms.JMSSecurityException;

import javax.jms.Connection;

import javax.jms.ConnectionFactory;

import javax.naming.InitialContext;

import javax.jms.JMSException;

import java.util.Properties;

public class Bruteforce {

public static void main(String... args) throws Exception{

InitialContext ctx;

String cfName = “ConnectionFactory”;

Connection conn = null;

ConnectionFactory cFact = null;

// Prepare the environment

Properties env = new Properties();

// Edit the environment properties for different brokers

env.setProperty(“java.naming.factory.initial”, “org.apache.activemq.jndi.ActiveMQInitialContextFactory”);

env.setProperty(“java.naming.provider.url”, “tcp://localhost:61616”);

env.setProperty(“connectionFactoryNames”, cfName);

// Create Initial Context

ctx = new InitialContext(env);

cFact = (ConnectionFactory) (ctx.lookup(cfName));

try {

conn = cFact.createConnection(); // Attempts anonymous connection

conn.start();

//Control reaches here only if the connection is successful

System.out.println(“Anonymous authentication supported”);

System.exit(0);

Page 23: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

23 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

}

catch(JMSException ex) {

System.out.println(ex.getMessage());

}

br.close();

}

}

JMSAPI-BasedCredentialBruteForceCodepackage com.mcafee;

import java.io.BufferedReader;

import java.io.FileReader;

import javax.jms.JMSSecurityException;

import javax.jms.Connection;

import javax.jms.ConnectionFactory;

import javax.naming.InitialContext;

import javax.jms.JMSException;

import java.util.Properties;

public class Bruteforce {

public static void main(String... args) throws Exception{

InitialContext ctx;

// File with 1000 different passwords (each password in a new line)

String filename = “1000Passwords.txt”;

String password;

String cfName = “ConnectionFactory”;

Connection conn = null;

ConnectionFactory cFact = null;

BufferedReader br = new BufferedReader(new FileReader(filename));

// Prepare the environment

Properties env = new Properties();

// Edit the environment properties for different brokers

env.setProperty(“java.naming.factory.initial”, “org.apache.activemq.jndi.ActiveMQInitialContextFactory”);

env.setProperty(“java.naming.provider.url”, “tcp://localhost:61616”);

env.setProperty(“connectionFactoryNames”, cfName);

Page 24: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

24 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

// Create Initial Context

ctx = new InitialContext(env);

cFact = (ConnectionFactory) (ctx.lookup(cfName));

while((password = br.readLine()) != null) {

System.out.println(“Trying password => “ + password);

try {

conn = cFact.createConnection(“system”, password);

// conn = cFact.createConnection(); Attempts anonymous connection

conn.start();

//Control reaches here only if the connection is successful

System.out.println(“Password found => “ + line);

System.exit(0);

}

catch(JMSException ex) {

System.out.println(ex.getMessage());

}

}

br.close();

}

}

ExamplePasswordandConfigurationFileDecryption CodeTheexampleJavaclassbelowacceptsalistofpasswordsandoneencryptedstringfromtheconfigurationfile.Itthentriestodecrypttheencryptedstringuntilitidentifiesthe correct password and returns it. Otherwise null isreturned.Allcredentialscanbeextractedfromtheconfigurationfileonceacorrectpasswordisguessed.

package com.mcafee;

import java.util.ArrayList;

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;

import org.jasypt.exceptions.EncryptionOperationNotPossibleException;

public class JmsPasswordOps {

private ArrayList<String> passwords = new ArrayList<String>();

private StandardPBEStringEncryptor encryptor = new

Page 25: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

25 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

StandardPBEStringEncryptor();

public void addPassword(String password) {

if(password == null)

throw new IllegalArgumentException(“Password cannot be null”);

this.passwords.add(password);

}

public void addPasswordList(ArrayList<String> passwords) {

if(passwords == null || passwords.size() == 0)

throw new IllegalArgumentException(“Password ArrayList cannot be null or of zero length”);

for(String pass: passwords) {

if(pass != null)

this.passwords.add(pass);

}

}

public void clearPasswords() {

passwords.clear();

}

public String decrypt(String encryptedText) throws JmsDiggerException {

String result = null;

if(encryptedText == null)

throw new IllegalArgumentException(“Encrypted text cannot be null”);

if(passwords.size() == 0)

throw new IllegalArgumentException(“No password provided”);

String pass;

for(pass : passwords) {

//New object is required for each decryption attempt

encryptor = new StandardPBEStringEncryptor();

try {

encryptor.setPassword(pass);

Page 26: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

26 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications

WHITE PAPER

result = encryptor.decrypt(encryptedText);

} catch (EncryptionOperationNotPossibleException ex) {

//Absorb this to be able to run through a large number of passwords

}

}

if(result == null)

return null;

return pass; // returns null if password could not be decrypted

}

}

About The AuthorGursevSinghKalraservesasaSeniorPrincipalwithMcAfeeFoundstoneProfessionalServices,adivisionofMcAfee. Gursev has authored several security-related whitepapersandhisresearchhasbeenvotedamongthetoptenwebhackingtechniquesof2011and2012.He loves to code and has authored several free security toolslikeJMSDigger,TesserCap,Oyedata,SSLSmart,and clipcaptcha. He has spoken at conferences such as BlackHat,ToorCon,OWASP,NullCon,InfosecSouthwest,and more.

About McAfee Foundstone Professional ServicesMcAfeeFoundstoneProfessionalServices,adivisionofMcAfee,offersexpertservicesandeducationtohelporganizationscontinuouslyandmeasurablyprotecttheirmost important assets from the most critical threats. Throughastrategicapproachtosecurity,McAfeeFoundstoneidentifiesandimplementstherightbalanceoftechnology,people,andprocesstomanagedigitalriskandleveragesecurityinvestmentsmoreeffectively.The company’s professional services team consists of recognizedsecurityexpertsandauthorswithbroadsecurityexperiencewithmultinationalcorporations,thepublicsector,andtheUSmilitary. http://www.mcafee.com/us/services/mcafee-foundstone-practice.aspx

1. http://activemq.apache.org/2. http://en.wikipedia.org/wiki/Java_Message_Service3. http://jcp.org/aboutJava/communityprocess/final/jsr914/index.html4. https://github.com/OpenSecurityResearch/jmsdigger5. Java Messaging Service, O’Reilly Media6. http://www.manning.com/snyder/7. https://www.jcp.org/en/jsr/detail?id=9148. http://en.wikipedia.org/wiki/SOAP9. http://en.wikipedia.org/wiki/JSON10. http://en.wikipedia.org/wiki/Java_Authentication_and_Authorization_Service11. http://www.eclipse.org/jetty/12. http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2013-306013. http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2013-188014. http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2013-187915. http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2012-609216. http://en.wikipedia.org/wiki/Man-in-the-middle_attack17. http://activemq.apache.org/how-do-i-use-ssl.html18. http://www.wireshark.org/19. http://www.jasypt.org/20. http://www.openwall.com/john/21. https://www.owasp.org/index.php/Testing_for_XML_Injection_(OWASP-DV-008)22. http://projects.webappsec.org/w/page/13247003/XML External Entities23.http://activemq.apache.org/statisticsplugin.html24. http://en.wikipedia.org/wiki/Java_Naming_and_Directory_Interface

Page 27: A Pentesters guide to Hacking ActiveMQ Based …...8 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications WHITE PAPER Apache ActiveMQ Basics ActiveMQ is an open-source, JMS-compliant

About McAfeeMcAfee is one of the world’s leading independent cybersecuritycompanies.Inspiredbythepowerofworkingtogether,McAfeecreatesbusinessandconsumer solutions that make the world a safer place. Bybuildingsolutionsthatworkwithothercompanies’products,McAfeehelpsbusinessesorchestratecyberenvironmentsthataretrulyintegrated,whereprotection,detectionandcorrectionofthreatshappensimultaneouslyandcollaboratively.Byprotectingconsumersacrossalltheirdevices,McAfeesecurestheirdigital lifestyle at home and away. By working with other securityplayers,McAfeeisleadingtheefforttouniteagainstcybercriminalsforthebenefitofall.

www.mcafee.com.

McAfee and the McAfee logo, and Foundstone are trademarks or registered trademarks of McAfee, LLC or its subsidiaries in the US and other countries. Other marks and brands may be claimed as the property of others. Copyright © 2014 McAfee, LLC. 61343_1014OCTOBER 2014

LicenseThe images and content of this white paper, “A Pentesters Guide to Hacking ActiveMQ Based JMS Applications” by Gursev Singh Kalra, are licensed under the Creative Commons Attribution-ShareAlike 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/4.0/.

2821 Mission College BoulevardSanta Clara, CA 95054888 847 8766www.mcafee.com

27 A Pentesters Guide to Hacking ActiveMQ-Based JMS Applications