KGRKJGETMRETU895U-589TY5MIGM5JGB5SDFESFREWTGR54TY
Server : Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8e-fips-rhel5 DAV/2 PHP/5.2.17
System : Linux localhost 2.6.18-419.el5 #1 SMP Fri Feb 24 22:47:42 UTC 2017 x86_64
User : nobody ( 99)
PHP Version : 5.2.17
Disable Function : NONE
Directory :  /proc/21573/root/usr/lib/python2.4/site-packages/setroubleshoot/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : //proc/21573/root/usr/lib/python2.4/site-packages/setroubleshoot/server.py
# Authors: John Dennis <jdennis@redhat.com>
#
# Copyright (C) 2006,2007,2008 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

__all__ = ['RunFaultServer',
           'ClientConnectionHandler',
           'get_host_database',
           'send_alert_notification',
           'ConnectionPool',
          ]


import gobject
gobject.threads_init()
from dbus import glib
import dbus.service
import errno as Errno
import os
import pwd
import Queue
import signal
from stat import *
import sys
import syslog
import time
import threading
from types import *

from setroubleshoot.access_control import *
from setroubleshoot.analyze import *
from setroubleshoot.config import get_config
if get_config('general', 'use_auparse', bool):
    from setroubleshoot.avc_auparse import *
else:
    from setroubleshoot.avc_audit import *
from setroubleshoot.errcode import *
from setroubleshoot.email_alert import *
from setroubleshoot.log import *
from setroubleshoot.rpc import *
from setroubleshoot.rpc_interfaces import *
from setroubleshoot.signature import *
from setroubleshoot.util import *
from setroubleshoot.html_util import *

#------------------------------ Utility Functions -----------------------------
    

def sighandler(signum, frame):
    if debug:
        log_server.debug("received signal=%s", signum)
    import setroubleshoot.config as config
    if signum == signal.SIGHUP:
        log_server.warning("reloading configuration file")
        config.config_init()
        return
    
    sys.exit()

def make_instance_id():
    hostname = get_hostname()
    pid = os.getpid()
    stamp = str(time.time())
    return '%s:%s:%s' % (hostname, pid, stamp)

def get_host_database():
    return host_database

# FIXME: this should be part of ClientNotifier
def send_alert_notification(siginfo):
    for client in connection_pool.clients('sealert'):
        client.alert(siginfo)

#------------------------------ Variables -------------------------------

host_database = None
analysis_queue = None
email_recipients = None
email_recipients_filepath = get_config('email', 'recipients_filepath')
pkg_version = get_config('general','pkg_version')
rpc_version = get_config('general','rpc_version')
instance_id = make_instance_id()


#-----------------------------------------------------------------------------

class ConnectionPool(object):
    def __init__(self):
        self.client_pool = {}

    def add_client(self, handler):
        if self.client_pool.has_key(handler):
            log_rpc.warning("add_client: client (%s) already in client pool" % handler)
            return
        self.client_pool[handler] = None

    def remove_client(self, handler):
        if not self.client_pool.has_key(handler):
            log_rpc.warning("remove_client: client (%s) not in client pool" % handler)
            return
        del(self.client_pool[handler])

    def clients(self, channel_type=None):
        for client in self.client_pool:
            if channel_type is None:
                yield client
            elif client.channel_type == channel_type:
                yield client

    def close_all(self, channel_type=None):
        for client in self.client_pool(channel_type):
            client.close_connection()

connection_pool = ConnectionPool()

#------------------------------------------------------------------------------

class AlertPluginReportReceiver(PluginReportReceiver):
    def __init__(self, database):
        super(AlertPluginReportReceiver, self).__init__(database)

    def report_problem(self, siginfo):
        siginfo = super(AlertPluginReportReceiver, self).report_problem(siginfo)

        if email_recipients is not None:
            to_addrs = []
            for recipient in email_recipients.recipient_list:
                username = "email:%s" % recipient.address
                action = siginfo.evaluate_filter_for_user(username, recipient.filter_type)
                if action != "ignore":
                    if debug:
                        log_email.debug("siginfo.sig=%s", siginfo.sig)
                    to_addrs.append(recipient.address)

            if len(to_addrs):
                email_alert(siginfo, to_addrs)
        
        if debug:
            log_alert.debug("sending alert to all clients")
        send_alert_notification(siginfo)

        # FIXME: should this be using our logging objects in log.py?
        summary = html_to_text(siginfo.solution.summary, 1024)
        syslog.syslog(summary + _(" For complete SELinux messages. run sealert -l %s" % siginfo.local_id ))
        return siginfo

#-----------------------------------------------------------------------------

class ClientConnectionHandler(RpcChannel):
    def __init__(self, socket_address):
        RpcChannel.__init__(self, 'sealert')
        self.socket_address = socket_address.copy()
        self.connection_state.connect('changed', self.on_connection_state_change)

    def on_connection_state_change(self, connection_state, flags, flags_added, flags_removed):
        if debug:
            log_communication.debug("%s.on_connection_state_change: connection_state=%s flags_added=%s flags_removed=%s address=%s",
                              self.__class__.__name__, connection_state,
                              connection_state.flags_to_string(flags_added), connection_state.flags_to_string(flags_removed),
                              self.socket_address)

        if flags_removed & ConnectionState.OPEN:
            connection_pool.remove_client(self)

        if flags_added & ConnectionState.OPEN:
            connection_pool.add_client(self)

    def open(self, socket, socket_address):
        if self.connection_state.flags & ConnectionState.OPEN:
            return True
        self.socket_address.socket = socket
        self.connection_state.update(ConnectionState.OPEN)
        self.io_watch_add(self.handle_client_io)


#-----------------------------------------------------------------------------

class SetroubleshootdClientConnectionHandler(ClientConnectionHandler,
                                             SETroubleshootServerInterface,
                                             SETroubleshootDatabaseNotifyInterface,
                                             SEAlertInterface,
                                             ):
    def __init__(self, socket_address):
        ClientConnectionHandler.__init__(self, socket_address)

        self.database = get_host_database()

        self.connect_rpc_interface('SETroubleshootServer', self)
        self.connect_rpc_interface('SETroubleshootDatabase', self)

        self.access = ServerAccess()
        self.username = None
        self.uid = None
        self.gid = None

    def on_connection_state_change(self, connection_state, flags, flags_added, flags_removed):
        if debug:
            log_communication.debug("%s.on_connection_state_change: connection_state=%s flags_added=%s flags_removed=%s address=%s",
                                    self.__class__.__name__, connection_state,
                                    connection_state.flags_to_string(flags_added), connection_state.flags_to_string(flags_removed),
                                    self.socket_address)

        if flags_removed & ConnectionState.OPEN:
            connection_pool.remove_client(self)

        if flags_added & ConnectionState.OPEN:
            self.uid, self.gid = self.access.get_credentials(self.socket_address.socket)
            log_communication.debug("%s.on_connection_state_change: open, socket credentials: uid=%s gid=%s", 
                                    self.__class__.__name__, self.uid, self.gid)
            connection_pool.add_client(self)

    def open(self, socket, socket_address):
        if self.connection_state.flags & ConnectionState.OPEN:
            return True
        self.socket_address.socket = socket
        self.connection_state.update(ConnectionState.OPEN)
        self.io_watch_add(self.handle_client_io)


    # ---- SETroubleshootServerInterface Methods ----

    def database_bind(self, database_name):
        if not (self.connection_state.flags & ConnectionState.AUTHENTICATED):
            raise ProgramError(ERR_NOT_AUTHENTICATED)

        host_database = get_host_database()
        if host_database.properties.name == database_name:
            return [host_database.properties]
        raise ProgramError(ERR_DATABASE_NOT_FOUND, "database (%s) not found" % database_name)
        

    def logon(self, type, username, password):
        if debug:
            log_rpc.debug("logon(%s) type=%s username=%s", self, type, username)

        if username != get_identity(self.uid):
            raise ProgramError(ERR_USER_LOOKUP, detail="uid=s does not match logon username (%s)" % (self.uid, username))

        if type == 'sealert':
            privilege = 'client'
        else:
            privilege = None

        if not self.access.user_allowed(privilege, username):
            raise ProgramError(ERR_USER_PROHIBITED)

        self.channel_type = type
        self.channel_name = username
        self.username = username
        self.user = self.database.get_user(username)
        if self.user is None:
            self.database.add_user(username)

        self.connection_state.update(ConnectionState.AUTHENTICATED)
        return [pkg_version, rpc_version]

    def query_email_recipients(self):
        if not (self.connection_state.flags & ConnectionState.AUTHENTICATED):
            raise ProgramError(ERR_NOT_AUTHENTICATED)

        return [email_recipients]

    def set_email_recipients(self, recipients):
        global email_recipients

        if debug:
            log_email.debug("set_email_recipients: %s", recipients)

        if not (self.connection_state.flags & ConnectionState.AUTHENTICATED):
            raise ProgramError(ERR_NOT_AUTHENTICATED)

        email_recipients = recipients
        email_recipients.write_recipient_file(email_recipients_filepath)

    # ----  SETroubleshootDatabaseInterface Methods ----

    def delete_signature(self, sig):
        if debug:
            log_rpc.debug("delete_signature: sig=%s", sig)

        if not (self.connection_state.flags & ConnectionState.AUTHENTICATED):
            raise ProgramError(ERR_NOT_AUTHENTICATED)

        siginfo = self.database.delete_signature(sig)
        return None
        
    def get_properties(self):
        if debug:
            log_rpc.debug("get_properties")

        if not (self.connection_state.flags & ConnectionState.AUTHENTICATED):
            raise ProgramError(ERR_NOT_AUTHENTICATED)

        properties = self.database.get_properties()
        return [properties]

    def evaluate_alert_filter(self, sig, username):
        if debug:
            log_rpc.debug("evaluate_alert_filter: username=%s sig=%s", username, sig)

        if not (self.connection_state.flags & ConnectionState.AUTHENTICATED):
            raise ProgramError(ERR_NOT_AUTHENTICATED)

        action = self.database.evaluate_alert_filter(sig, username)
        return [action]

    def lookup_local_id(self, local_id):
        if debug:
            log_rpc.debug("lookup_local_id: %s", local_id)

        if not (self.connection_state.flags & ConnectionState.AUTHENTICATED):
            raise ProgramError(ERR_NOT_AUTHENTICATED)

        siginfo = self.database.lookup_local_id(local_id)
        return [siginfo]

    def query_alerts(self, criteria):
        if debug:
            log_rpc.debug("query_alerts: criteria=%s", criteria)

        if not (self.connection_state.flags & ConnectionState.AUTHENTICATED):
            raise ProgramError(ERR_NOT_AUTHENTICATED)

        sigs = self.database.query_alerts(criteria)
        return [sigs]

    def set_filter(self, sig, username, filter_type, data = "" ):
        if debug:
            log_rpc.debug("set_filter: username=%s filter_type=%s sig=\n%s",
                          username, filter_type, sig)

        if not (self.connection_state.flags & ConnectionState.AUTHENTICATED):
            raise ProgramError(ERR_NOT_AUTHENTICATED)

        if username != self.username:
            raise ProgramError(ERR_USER_PERMISSION, detail=_("The user (%s) cannot modify data for (%s)") % (self.username, username))
        
        self.database.set_filter(sig, username, filter_type, data)
        return None


    def set_user_data(self, sig, username, item, data):
        if debug:
            log_rpc.debug("set_user_data: username=%s item=%s data=%s sig=\n%s",
                          username, item, data, sig)

        if not (self.connection_state.flags & ConnectionState.AUTHENTICATED):
            raise ProgramError(ERR_NOT_AUTHENTICATED)

        self.database.set_user_data(sig, username, item, data)
        return None

#------------------------------------------------------------------------------

class ClientNotifier(object):
    def __init__(self, connection_pool):
        self.connection_pool = connection_pool

    # ----  SETroubleshootDatabaseNotifyInterface Methods ----

    def signatures_updated(self, type, item):
        for client in self.connection_pool.clients('sealert'):
            client.signatures_updated(type, item)



#------------------------------------------------------------------------------

dbus_system_bus_name = get_config('system_dbus','bus_name')
dbus_system_object_path = get_config('system_dbus','object_path')
dbus_system_interface = get_config('system_dbus','interface')

class SetroubleshootdDBusObject(dbus.service.Object):
    def __init__(self, bus_name, object_path):
        dbus.service.Object.__init__(self, bus_name, object_path)

    @dbus.service.signal(dbus_system_interface)
    def restart(self, reason):
        pass

class SetroubleshootdDBus:
    def __init__(self):
        try:
            log_server.info("creating system dbus: bus_name=%s object_path=%s interface=%s",
                            dbus_system_bus_name, dbus_system_object_path, dbus_system_interface)
            self.bus = dbus.SystemBus()
            self.bus_name = dbus.service.BusName(dbus_system_bus_name, bus=self.bus)
            self.dbus_obj = SetroubleshootdDBusObject(self.bus_name, dbus_system_object_path)
        except Exception, e:
            log_server.error("cannot start systen DBus service: %s" % e)

    def do_restart(self):
        self.dbus_obj.restart("daemon request")
        return True

#------------------------------------------------------------------------------

def RunFaultServer():
    # FIXME
    global host_database, analysis_queue, email_recipients

    signal.signal(signal.SIGHUP, sighandler)
    signal.signal(signal.SIGQUIT, sighandler)
    signal.signal(signal.SIGTERM, sighandler)

    #interface_registry.dump_interfaces()

    try:
        # FIXME: should this be using our logging objects in log.py?
        # currently syslog is only used for putting an alert into
        # the syslog with it's id

        pkg_name = get_config('general','pkg_name')
        syslog.openlog(pkg_name)

        # Create an object responsible for sending notifications to clients
        client_notifier = ClientNotifier(connection_pool)

        # Create a database local to this host

        database_filename = get_config('database','filename')
        database_filepath = make_database_filepath(database_filename)
        assure_file_ownership_permissions(database_filepath, 0600, 'root', 'root')
        host_database = SETroubleshootDatabase(database_filepath, database_filename,
                                               friendly_name=_("Audit Listener"))
        host_database.set_notify(client_notifier)

        # Attach the local database to an object which will send alerts
        # specific to this host

        if not get_config('test', 'analyze', bool):
            alert_receiver = AlertPluginReportReceiver(host_database)
        else:
            alert_receiver = TestPluginReportReceiver(host_database)

        # Create a synchronized queue for analysis requests

        analysis_queue = Queue.Queue(0)

        # Create a thread to peform analysis, it takes AVC objects off
        # the the analysis queue and runs the plugins against the
        # AVC. Analysis requests in the queue may arrive from a
        # variety of places; from the audit system, from a log file
        # scan, etc. The disposition of the analysis (e.g. where the
        # results of the analysis are to go) are included in the queued
        # object along with the data to analyze.

        analyze_thread = AnalyzeThread(analysis_queue)
        analyze_thread.setDaemon(True)
        analyze_thread.start()
    
        # Create a thread to receive messages from the audit system.
        # This is a time sensitive operation, the primary job of this
        # thread is to receive the audit message as quickly as
        # possible and return to listening on the audit socket. When
        # it receives a complete audit event it places it in the
        # analysis queue where another thread will process it
        # independently.

        audit_socket_thread = AuditSocketReceiverThread(analysis_queue, alert_receiver)
        audit_socket_thread.setDaemon(True)
        audit_socket_thread.start()

        # Initialize the email recipient list
        email_recipients = SEEmailRecipientSet()
        assure_file_ownership_permissions(email_recipients_filepath, 0600, 'root', 'root')
        try:
            email_recipients.parse_recipient_file(email_recipients_filepath)
        except ProgramError, e:
            if e.errno == ERR_FILE_OPEN:
                log_email.warning(e.strerror)
            else:
                raise e

        # Create a server to listen for alert clients and then run.
        listen_addresses = get_socket_list_from_config('listen_for_client')
        for listen_address in listen_addresses:
            listening_server = ListeningServer(listen_address, SetroubleshootdClientConnectionHandler)
            listening_server.open()

        setroubleshootd_dbus = SetroubleshootdDBus()
        
        main_loop = gobject.MainLoop()
        main_loop.run()

    except KeyboardInterrupt, e:
        if debug:
            log_server.debug("KeyboardInterrupt in RunFaultServer")

    except SystemExit, e:
        if debug:
            log_server.debug("raising SystemExit in RunFaultServer")

    except Exception, e:
        log_rpc.exception("exception %s: %s",e.__class__.__name__, str(e))

if __name__=='__main__':
    RunFaultServer()


Anon7 - 2021