def process_ssh_loginfail(strInfo):
    #Jun 16 09:10:43 localhost sshd[19679]: Failed password for test from 172.16.140.151 port 53307 ssh2
    #Jun 27 05:46:38 localhost sshd[8715]: Failed password for invalid user 234 from 172.16.140.151 port 57583 ssh2
    strList=strInfo.split(' ')

    if strInfo.find('from')<0:
        PrntLog.error('Failed process_ssh_loginfail: %s'%strInfo)
        return
    (usrname,clientIp,clientPort)= ['', '', '']
    for i in range(len(strList)):
        if strList[i] == 'from':
            usrname=strList[i-1]
            clientIp=strList[i+1]
            clientPort=strList[i+3]
            break

    linkInfo={}
    linkInfo['USER_NAME'] = usrname
    linkInfo['CLIENT_IP'] = clientIp
    linkInfo['CLIENT_PORT'] = clientPort
    linkInfo['LOCAL_IP'] = get_host_ip()
    linkInfo['time'] = get_cuurent_time()

    (status, output) = commands.getstatusoutput('/usr/local/sagent-3000-ns/netstat -tpn|grep ' + clientIp + ':' + clientPort + '| awk \'{print $4}\'')
    localPort = output.split(':')[-1]
    proc_failed_login(clientIp, usrname, time.time(), localPort)
    #发送登录失败报文
    strMsg = MsgWrap( linkInfo ).Msg_SSH_LogFail_Data( )
    pf_oper.sendmsg( strMsg )
    PrntLog.info('SSH login failed!  usrname=%s clientIp=%s clientPort=%s '%(usrname,clientIp,clientPort))
Exemple #2
0
    def run(self):
        #从agent.conf中获取文件监视列表
        watchList = []
        try:
            configList = Config_agent.items('echo_cmd_watchlist')
        except Exception as e:
            PrntLog.error('inotify_log get watchList Failed. ')
            raise Exception('inotify_log get watchList Failed.')

        for info in configList:
            watchList.append(info[1])

        for strPath in watchList:
            if not os.path.exists(strPath):
                os.makedirs(strPath)
                if os.path.exists(strPath):
                    command = "chmod 777 " + strPath
                    os.system(command)
                    command = "chmod a+t " + strPath
                    os.system(command)

        wm = pyinotify.WatchManager()
        #mask = pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MODIFY | pyinotify.IN_MOVED_FROM
        mask = pyinotify.IN_MODIFY
        notifier = pyinotify.ThreadedNotifier(wm, OnIOHandler())
        notifier.start()
        wm.add_watch(watchList, mask, rec=True, auto_add=True)

        PrntLog.info('cmd and echo: Start monitoring %s' % watchList)
        while True:
            #try:
            notifier.process_events()
            if notifier.check_events():
                notifier.read_events()
Exemple #3
0
    def ChangePasswd(self, info):
        resInfo = {}
        resInfo['ID'] = info['ID']
        resInfo['IP'] = info['IP']
        resInfo['USER_NAME'] = info['USER_NAME']

        salt = getsalt()
        passwd = crypt.crypt(info['PASSWD'], salt)
        cmdline = 'usermod -p %s %s' % (passwd, info['USER_NAME'])
        ret = os.system(cmdline)
        ret >>= 8

        if ret == 0:
            resInfo['RESULT'] = 0
            PrntLog.info('user %s change passwd successful ' %
                         info['USER_NAME'])
        elif ret == 6:
            # 用户不存在
            resInfo['RESULT'] = 1
            PrntLog.error('user %s dose not exists ' % info['USER_NAME'])
        else:
            resInfo['RESULT'] = 2
        PrntLog.info('Msg_ChangePasswd_Res_Data %s ' % resInfo)
        strMsg = opermsgpaser.Msg_ChangePasswd_Res_Data(resInfo)
        pf_oper.sendmsg(strMsg)
        return
def read_cmd_from_cmdfile_sendMsg(logPath, logName,linkInfo,itemDict):
    try:
        itemDict['ECHO_SIZE']=getEchofileSize(logPath,logName)
        fullFileName = os.path.join( logPath, logName )
        f = open( fullFileName, 'r' )
        f.seek(itemDict['CMD_OFFSET'])
        offset_flag=itemDict['CMD_OFFSET']
        for i in range( 1000 ):
            line = f.readline( ).rstrip('\n')
            if line == '':
                break
            #跳过第一行
            if(offset_flag==0):
                offset_flag = f.tell( )
                continue
            PrntLog.info(line)
            #获取信息,发送操作报文
            strMsg = MsgWrap( linkInfo, itemDict ).Msg_Cmd_DATA( line )
            if strMsg!='':
                pf_oper.sendmsg( strMsg )
        offset=f.tell()
        f.close()
        return offset
    except Exception as e:
        PrntLog.error('Failed read_cmd_from_cmdfile_sendMsg: %s '%e)
        PrntLog.error( "read_cmd_from_cmdfile_sendMsg fail: %s" % traceback.format_exc( ) )
        if 'f' in locals( ):
            f.close( )
def get_ssh_linkInfo_from_logname(logName):
    strSplit=logName.split('-')
    if len(strSplit) != 7:
        PrntLog.error("Failed:get_ssh_linkInfo_from_logname %s " %logName)
        return False
    linkInfo = {}
    linkInfo['LOGIN_TYPE']   = 'ssh'
    linkInfo['CLIENT_IP']    = strSplit[0]
    linkInfo['CLIENT_PORT']  = strSplit[1]
    linkInfo['USER_NAME']    = strSplit[2]
    linkInfo['time']          = strSplit[3]
    linkInfo['TTY']           = strSplit[4]
    linkInfo['LOCAL_IP']     = strSplit[5]
    pos=0
    for str in linkInfo['TTY']:
        if str.isdigit( ):
            break
        pos=pos+1

    tty=linkInfo['TTY'][:pos]+'/'+linkInfo['TTY'][pos:]
    cmdline="ps -ef |grep -v grep |grep sshd |grep " + linkInfo['USER_NAME'] +" |grep "+tty +" | awk '{print $2}'"

    fp=os.popen(cmdline)
    linkInfo['PID_NUM'] = fp.readline( ).rstrip('\n')
    fp.close()
    if  linkInfo['PID_NUM']== '':
        return False

    return linkInfo
Exemple #6
0
    def ChangeAccountName(self, info):
        resInfo = {}
        resInfo['ID'] = info['ID']
        resInfo['IP'] = info['IP']
        resInfo['USER_NAME'] = info['NEW_USERNAME']

        cmdline = 'usermod -l %s %s' % (info['NEW_USERNAME'],
                                        info['USER_NAME'])
        ret = os.system(cmdline)
        ret >>= 8

        if ret == 0:
            resInfo['RESULT'] = 0
            global gCreateAccountrSet
            gCreateAccountrSet.remove(info['USER_NAME'])
            gCreateAccountrSet.add(info['NEW_USERNAME'])
            userListTofile()
            PrntLog.info('change account name %s to %s successful ' %
                         (info['USER_NAME'], info['NEW_USERNAME']))
        elif ret == 6:
            # 用户不存在
            resInfo['RESULT'] = 1
            PrntLog.error('user %s dose not exists ' % info['USER_NAME'])
        elif ret == 9:
            # 用户已存在
            resInfo['RESULT'] = 2
            PrntLog.error('user %s already exists ' % info['NEW_USERNAME'])
        else:
            resInfo['RESULT'] = 3
        PrntLog.info('Msg_ChangeAccountName_Res_Data %s ' % resInfo)
        strMsg = opermsgpaser.Msg_ChangeAccountName_Res_Data(resInfo)
        pf_oper.sendmsg(strMsg)
        return
Exemple #7
0
    def DelAccount(self, info):
        resInfo = {}
        resInfo['ID'] = info['ID']
        resInfo['IP'] = info['IP']
        resInfo['USER_NAME'] = info['USER_NAME']

        cmdline = 'userdel %s' % (info['USER_NAME'])
        ret = os.system(cmdline)
        ret >>= 8

        if ret == 0:
            resInfo['RESULT'] = 0
            global gCreateAccountrSet
            gCreateAccountrSet.remove(info['USER_NAME'])
            userListTofile()
            PrntLog.info('Del account %s successful ' % info['USER_NAME'])
        elif ret == 6:
            # 用户不存在
            resInfo['RESULT'] = 1
            PrntLog.error('Del account :user %s dose not exists ' %
                          info['USER_NAME'])
        else:
            resInfo['RESULT'] = 2
        PrntLog.info('Msg_DelAccount_Res_Data %s ' % resInfo)
        strMsg = opermsgpaser.Msg_DelAccount_Res_Data(resInfo)
        pf_oper.sendmsg(strMsg)
        return
Exemple #8
0
def liccheckfunc():
    global liblic
    ptr = liblic.lic_check()
    ret = ctypes.cast(ptr, ctypes.c_char_p).value
    havelicense = int(ret.split(' ')[0])
    outdatetimestamp = int(ret.split(' ')[1])
    liblic.freeme(ptr)

    outdate = datetime.fromtimestamp(outdatetimestamp).strftime(
        "%Y-%m-%d %H:%M:%S")

    if havelicense == 0:
        str = "You have not installed any license file yet!"
        PrntLog.error(str)
        print str
        licsystemnotify('')
        sys.exit(1)
    elif havelicense == 1:
        # 剩余30天开始提醒
        if outdatetimestamp < time.time():
            str = "Your license file expired in [" + outdate + "]!"
            licsystemnotify(str)
            PrntLog.error(str)
        elif (outdatetimestamp - 30 * 24 * 3600) < time.time():
            str = "Your license file will expire in [" + outdate + "]!"
            licsystemnotify(str)
            PrntLog.info(str)
        else:
            licsystemnotify('')
    return
    def HearBeat(self):
        try:
            global gLinkList
            # 做个链路保活检查
            check_linkInfo_isAlive()
            for i in range( len( gLinkList ) - 1, -1, -1 ):
                item = gLinkList[i]
                if item['LOGIN_TYPE'] == 'ssh':
                    #发送心跳报文
                    strMsg=MsgWrap(item).Msg_SSH_HeartBeat()
                    pf_oper.sendmsg(strMsg)
                    # 测试阻断操作
                    #strMsg = MsgWrap( item ).Msg_SSH_TestStopLink( )
                    #pf_oper.sendmsg( strMsg )
                    PrntLog.info('ssh heart beat: %s' %item)
                elif item['LOGIN_TYPE'] == 'x11':
                    strMsg = MsgWrap( item ).Msg_X11_HeartBeat( )
                    pf_oper.sendmsg( strMsg )
                    #测试阻断操作
                    #strMsg = MsgWrap( item ).Msg_X11_TestStopLink( )
                    #pf_oper.sendmsg( strMsg )
                    PrntLog.info('x11 heart beat: %s' %item)
                elif item['LOGIN_TYPE'] == 'local':
                    # 发送心跳报文
                    strMsg = MsgWrap( item ).Msg_LOCAL_HeartBeat( )
                    pf_oper.sendmsg( strMsg )
                    PrntLog.info('local heart beat: %s'%item)
        except Exception as e:
            PrntLog.error('Failed HearBeat: %s '%e)

        '''
def process_tty_loginfail(strInfo):
    #Jun 23 06:35:13 localhost login: pam_unix(login:auth): authentication failure; logname=LOGIN uid=0 euid=0 tty=tty2 ruser= rhost=  user=root  -kylin
    #Jul 10 03:48:20 localhost login: FAILED LOGIN 2 FROM (null) FOR root, Authentication failure
    #Jul 10 04:12:43 localhost login: FAILED LOGIN 2 FROM (null) FOR reeewt, User not known to the underlying authentication module
    #Jan 31 03:31:43 nari-desktop login[32569]: FAILED LOGIN (1) on '/dev/tty2' FOR 'nari', Authentication failure  -----ubuntu10
    #Feb  1 21:57:37 debian login[1589]: FAILED LOGIN (1) on '/dev/tty3' FOR 'root', Authentication failure  -----debian6.0
    strList = strInfo.split( ' ' )
    usrname=''
    if os_version["type"] == "debian" :
        for i in range( len( strList ) ):
            if strList[i] =='LOGIN' and strList[i+2] =='on' and strList[i+4] =='FOR' :
                usrname=strList[i+5].rstrip(',').strip('\'')
                break
    else:
        for i in range( len( strList ) ):
            if strList[i] =='LOGIN' and strList[i+2] =='FROM' and strList[i+4] =='FOR' :
                usrname=strList[i+5].rstrip(',')
                break

    if usrname=='':
        PrntLog.error('Failed process_tty_loginfail! strInfo= %s'%strInfo)
        return

    linkInfo = {}
    linkInfo['USER_NAME'] = usrname
    linkInfo['time'] = get_cuurent_time( )
    linkInfo['LOCAL_IP'] = get_host_ip( )

    PrntLog.info('tty login failed! usrname= %s '%usrname)
    # 发送tty登录失败报文
    strMsg = MsgWrap( linkInfo ).Msg_LOCAL_LogFail_Data( )
    pf_oper.sendmsg( strMsg )
    def Parser_Log_Secure(self):
        global g_POS_LOG_SECURE
        try:
            # debian ubuntu
            if os_version["type"] == "debian":
                f = open( '/var/log/auth.log', 'r' )
            # redhat centos and others
            else:
                f = open( '/var/log/secure', 'r' )

            f.seek( 0, 2 )
            endPos = f.tell( )
            # secure日志轮转
            if (g_POS_LOG_SECURE > endPos):
                g_POS_LOG_SECURE = 0

            f.seek( g_POS_LOG_SECURE )
            for i in range( 1000 ):
                line = f.readline( ).rstrip( '\n' )
                if line == '':
                    break
                PrntLog.info( line )
                if 'session closed for user' in line and 'sshd' not in line:
                    # 图形界面退出 包括本地和x11
                    process_session_loginout( line )
                elif 'session closed for user' in line and 'sshd['  in line:
                    # SSH退出登录流程
                    process_ssh_logout( line )
                elif 'session opened for user' in line and 'sshd' not in line:
                    #图形界面登录 包括本地和x11
                    process_session_login(line)
                    '''
                elif 'Received disconnect from' in line and 'sshd' in line:
                    # SSH退出登录流程
                    PrntLog.info(line)
                    process_ssh_logout( line )
                    '''
                elif 'Failed password for ' in line and  'sshd[' in line:
                    #SSH登录失败
                    process_ssh_loginfail(line)
                elif ('pam: gdm-password:'******'(gdm-password:auth)' in line) \
                    or ('gdm[' in line and '(gdm:auth)' in line)\
					or ('(gdm-password:auth)' in line and 'gdm-password]' in line) \
                	or ('gdm-session-worker[' in line and ('(gdm:auth)' in line or '(gdm3:auth)' in line)):
                    #x11 本地图形 登录失败
                    process_session_loginfail(line)
                elif ('login: FAILED LOGIN' in line) or ('FAILED LOGIN' in line and 'login[' in line) :
                    #tty 登录失败
                    process_tty_loginfail( line )

            g_POS_LOG_SECURE = f.tell( )
        except Exception as e:
            PrntLog.error( 'Failed Parser_Log_Secure: %s' % e )
            PrntLog.error( "Parser_Log_Secure fail: %s" % traceback.format_exc( ) )

        finally:
            if 'f' in locals( ):
                f.close( )
Exemple #12
0
 def run(self):
     while True:
         try:
             message = sys_base.consume_data()
             for str in message:
                 PrntLog.info('sys_base Recv kafka Msg:')
                 operpaser.OperParserMsg(str.value)
         except Exception as e:
             PrntLog.error('Failed recvBaseCheckMsgFromKafka %s ' % e)
             time.sleep(5)
Exemple #13
0
def verifyconfigfile():
    if not os.path.exists('.agent.conf'):
        PrntLog.error('config file has not been protected!')
        sys.exit(1)
    output = commands.getoutput('diff agent.conf .agent.conf')
    if output != '':
        PrntLog.error(
            'config file has been illegal modified! Recover original file!')
        output = commands.getoutput('rm -rf agent.conf')
        output = commands.getoutput('cp .agent.conf agent.conf')
        sys.exit(1)
Exemple #14
0
 def Msg_Echo_DATA(self, strLine):
     try:
         if self.LinkInfo['LOGIN_TYPE'] == 'ssh':
             return self.Msg_SSH_Echo_DATA(strLine)
         elif self.LinkInfo['LOGIN_TYPE'] == 'x11':
             return self.Msg_X11_Echo_DATA(strLine)
         elif self.LinkInfo['LOGIN_TYPE'] == 'local':
             return self.Msg_LOCAL_Echo_DATA(strLine)
     except Exception as e:
         PrntLog.error('Failed Msg_Echo_DATA: %s  (Error:%s) ' %
                       (strLine, e))
 def Init_Log_Secure_Pos(self):
     global g_POS_LOG_SECURE
     try:
         # debian ubuntu
         if os_version["type"] == "debian":
             f = open( '/var/log/auth.log', 'r' )
         # redhat centos and others
         else:
             f = open( '/var/log/secure', 'r' )
         f.seek( 0, 2 )
         g_POS_LOG_SECURE = f.tell( )
     except Exception as e:
         PrntLog.error('Failed Init_Log_Secure_Pos: %s'%e)
     finally:
         if 'f' in locals( ):
             f.close( )
def dec_lib(libname, outfile):
    try:
        f = open(outfile)
        line = f.readline()
        f.close()

        out = xor_decrypt(line, 'WgQv^^!QSk*m')
        md5 = get_md5(libname)

        if out == md5:
            return 0
        else:
            return -1
    except Exception as e:
        PrntLog.error('dec_lib exception[%s]' % e)
        return -1
def get_local_linkInfo_from_logname(logName ):
    strSplit = logName.split( '-' )
    if len( strSplit ) != 5:
        PrntLog.error("Failed:get_local_linkInfo_from_logname %s" % logName)
        return False
    linkInfo = {}
    linkInfo['LOGIN_TYPE'] = 'local'
    linkInfo['USER_NAME'] = strSplit[0]
    linkInfo['time']       = strSplit[1]
    linkInfo['TTY']        = strSplit[2]
    linkInfo['LOCAL_TYPE'] = strSplit[3]
    linkInfo['LOCAL_IP']  = get_host_ip()
    if not linkInfo['LOCAL_IP']:
        PrntLog.error('Failed: get_host_ip. %s ' % logName)
        return False

    #print(linkInfo)
    return linkInfo
def process_session_console_login(usrname):
    global gLinkList
    linkInfo = {}
    linkInfo['LOGIN_TYPE'] = 'local'
    linkInfo['LOCAL_TYPE'] = 'gdm'
    linkInfo['USER_NAME'] = usrname
    linkInfo['time'] = get_cuurent_time()
    linkInfo['LOCAL_IP'] = get_host_ip( )
    if not linkInfo['LOCAL_IP']:
        PrntLog.error('Failed: get_host_ip. %s ' % usrname)
        return False

    gLinkList.append( linkInfo )
    PrntLog.info('Add local session :%s'%linkInfo)
    # 发送本地登录消息报文
    strMsg = MsgWrap( linkInfo ).Msg_LOCAL_Login_Data( )
    pf_oper.sendmsg( strMsg )
    PrntLog.info('local session login : usrname =%s localip=%s'%( usrname ,linkInfo['LOCAL_IP']))
Exemple #19
0
    def Msg_StopLink_Res_DATA(self):
        if self.LinkInfo['LOGIN_TYPE'] == 'ssh':
            msgType = 0x08
        elif self.LinkInfo['LOGIN_TYPE'] == 'x11':
            msgType = 0x1b
        else:
            PrntLog.error('Failed Msg_StopLink_Res_DATA: %s' %
                          self.LinkInfo['LOGIN_TYPE'])
            return

        strMsg = struct.pack('<B32s4sH4sQQ', msgType, self.LinkInfo['ID'],
                             covert_ipaddr(self.LinkInfo['CLIENT_IP']),
                             int(self.LinkInfo['CLIENT_PORT']),
                             covert_ipaddr(self.LinkInfo['LOCAL_IP']),
                             int(self.LinkInfo['time'].replace('_', '')[:-3]),
                             int(get_cuurent_time().replace('_', '')[:-3]))
        PrntLog.info(PrtMsg(strMsg))
        return strMsg
 def stopLinkAndSendRes(self,operlinkInfo):
     try:
         global gLinkList
         PrntLog.info ('stopLinkAndSendRes: %s '% operlinkInfo)
         for i in range( len( gLinkList ) - 1, -1, -1 ):
             linkInfo = gLinkList[i]
             if operlinkInfo['IP'] == linkInfo['LOCAL_IP'] and operlinkInfo['PID_NUM'] == linkInfo['PID_NUM']:
                 # 杀死指定进程
                 str = 'kill -16 ' + operlinkInfo['PID_NUM']
                 PrntLog.info(str)
                 ret = os.system( str )
                 linkInfo['ID'] = operlinkInfo['ID']
                 # 发送响应报文
                 strMsg = MsgWrap( linkInfo ).Msg_StopLink_Res_DATA()
                 pf_oper.sendmsg( strMsg )
                 gLinkList.remove( linkInfo )
                 PrntLog.info('Remove Link %s'%linkInfo)
     except Exception as e:
         PrntLog.error('Failed stopLinkAndSendRes: %s ' %e)
    def Parser_Log(self,action, logPath, logName):
        try:
            #非log日志不处理
            if logName[0] == '.'or logName.split('.')[-1] != 'log':
                return

            linkInfo = get_linkInfo_from_logname( logPath, logName )
            if not linkInfo:
                PrntLog.info('Failed: get_linkInfo_from_logname %s'%logName)
                return False

            if (logPath.find( '/ssh' ) >= 0):
                parser_log_ssh(logPath, logName,linkInfo)
            elif (logPath.find( '/local' ) >= 0):
                parser_log_local( logPath, logName, linkInfo )
            elif (logPath.find( '/x11' ) >= 0):
                parser_log_x11( logPath, logName, linkInfo )
        except Exception as e:
            PrntLog.error('Failed Parser_Log: %s %s %s %s'%(action,logPath,logName,e))
            PrntLog.error("Parser_Log fail: %s" % traceback.format_exc())
 def report(self):
     try:
         pf_monitor.sendmsg("<5> " + get_prefix() + " " +
                            self.cpuConfigInfo())
         pf_monitor.sendmsg("<5> " + get_prefix() + " " +
                            self.memConfigInfo())
         pf_monitor.sendmsg("<5> " + get_prefix() + " " +
                            self.DiskSizeInfo())
         pf_monitor.sendmsg("<5> " + get_prefix() + " " + self.ModemInfo())
         pf_monitor.sendmsg("<5> " + get_prefix() + " " +
                            self.USBCountInfo())
         pf_monitor.sendmsg("<5> " + get_prefix() + " " +
                            self.SerialCount())
         #pf_monitor.sendmsg("<5> " + get_prefix() + " " + self.ParaCount())
         pf_monitor.sendmsg("<5> " + get_prefix() + " " + self.ethInfo())
         pf_monitor.sendmsg("<5> " + get_prefix() + " " + self.OSInfo())
     except Exception as e:
         PrntLog.error('ConfigInfor failed:%s' % e)
         PrntLog.error("ConfigInfor fail: %s" % traceback.format_exc())
     return
def read_echo_from_echofile_sendMsg(logPath, logName,linkInfo,itemDict):
    try:
        fullFileName = os.path.join( logPath, logName )
        f = open( fullFileName, 'r' )
        fsize = os.path.getsize( fullFileName )
        #print('ECHO_SIZE %s  fsize %s  %s'%(itemDict['ECHO_SIZE'],fsize,fullFileName))
        if itemDict['ECHO_SIZE'] + 6*1024 < fsize :
            f.seek( 0, 2 )
            offset = f.tell( )
            f.close( )
            return offset
     
        f.seek(itemDict['ECHO_OFFSET'],0)
        
        for i in range( 100 ):
            strLine=''
            for i in range(10):
                line = f.readline( )
                #print('aa',line)
                if line == '':
                    break
                else:
                    strLine = strLine + line

            if strLine == '':
                break
            #PrntLog.info( strLine )
            #获取信息,发送操作报文
            strMsg = MsgWrap( linkInfo, itemDict).Msg_Echo_DATA(strLine)
            pf_oper.sendmsg( strMsg )
        offset=f.tell()
        f.close()
        return offset
    except Exception as e:
        PrntLog.error('Failed read_echo_from_echofile_sendMsg: %s '%e)
        PrntLog.error( "read_echo_from_echofile_sendMsg fail: %s" % traceback.format_exc( ) )
        if 'f' in locals( ):
            f.close( )
def user_perm_change(perf):
    try:
        user_info()
        watchList = ['/etc/']
        wm = pyinotify.WatchManager()
        mask = pyinotify.IN_MODIFY
        #notifier = pyinotify.ThreadedNotifier(wm, OnIOHandler())
        notifier = pyinotify.Notifier(wm, OnIOHandler())
        #notifier.start()
        wm.add_watch(watchList, mask, rec=True, auto_add=True)
        PrntLog.info('user_perm_change: Start monitoring %s' % watchList)
    except Exception as e:
        PrntLog.error('user_perm_change init failed:%s' % e)
        PrntLog.error("user_perm_change fail: %s" % traceback.format_exc())

    while True:
        try:
            notifier.process_events()
            if notifier.check_events():
                notifier.read_events()
        except KeyboardInterrupt:
            notifier.stop()
            break
Exemple #25
0
    def run(self):
        global g_EventListSet, mutexEventSet
        while True:
            try:
                if len(g_EventListSet) > 0:
                    if mutexEventSet.acquire(5):
                        eventpathname = g_EventListSet.pop()
                        mutexEventSet.release()

                        filename = os.path.basename(eventpathname)
                        filepath = os.path.dirname(eventpathname)

                        if ('secure' == filename):
                            logparser.Parser_Log_Secure()
                        elif (filepath.find('/tmp/.record') >= 0):
                            #prtstr = ("%s :Action modify file: %s " % (threading.current_thread().name,os.path.join( filepath, filename )))
                            #print(prtstr)
                            #PrntLog.info( prtstr )
                            logparser.Parser_Log('modify', filepath, filename)

                time.sleep(1)
            except Exception as e:
                PrntLog.error('Failed ProcessNotifyEvent %s ' % e)
def critical_file_perm_change(perf):
    try:
        global AllDirDict
        global AllFileDict
        watchList = []
        try:
            configList = Config_agent.items('critical_file_list')
        except Exception as e:
            PrntLog.error('critical_file_perm_change get watchList Failed. ')
            raise Exception('critical_file_perm_change get watchList Failed.')

        for info in configList:
            #对监控文件添加审计规则
            auditOper.add_audit_to_file(info[1])
            watchList.append(info[1])

        #add by sunboyan 2017/8/17
        (AllDirDict, AllFileDict) = getWatchListDict(watchList)

        mask = pyinotify.IN_MODIFY | pyinotify.IN_ATTRIB | pyinotify.IN_MOVED_FROM | pyinotify.IN_MOVED_TO | pyinotify.IN_CREATE | pyinotify.IN_DELETE
        watch_delay_call(watchList, delay_callback, mask)

    except Exception as e:
        PrntLog.error('critical_file_perm_change init failed:%s' % e)
Exemple #27
0
def stopnetcard(info):
    import time
    time.sleep(5)
    PrntLog.info('stopnetcard :%s' % info)
    resInfo = {}
    resInfo['ID'] = info['ID']
    resInfo['IP'] = info['IP']

    netcard_info = get_netcard()
    for netinfo in netcard_info:
        cmdline = 'ifdown %s' % (netinfo[0])
        ret = os.system(cmdline)
        ret >>= 8
        if ret != 0:
            resInfo['RESULT'] = 0
            PrntLog.error('stopnetcard failed!  %s %s ' %
                          (netinfo[0], netinfo[1]))
            strMsg = opermsgpaser.Msg_StopNetcard_Res_Data(resInfo)
            pf_oper.sendmsg(strMsg)
        else:
            PrntLog.info('stopnetcard sucessful!  %s %s ' %
                         (netinfo[0], netinfo[1]))

    return
Exemple #28
0
    def BaseLineCheck(self, info):
        resInfo = {}
        if '.xml' in info['XML_NAME']:
            info['XML_NAME'] = info['XML_NAME'].rstrip('.xml')
        resInfo['XML_NAME'] = info['XML_NAME']
        cmdline = 'bash %s %s %s %s' % (info['SHELL_NAME'], info['IP'],
                                        info['CHECKLIST'], info['XML_NAME'])
        PrntLog.info('BaseLineCheck cmdline=%s' % cmdline)
        ret = os.system(cmdline)
        ret >>= 8

        if ret == 0:
            resInfo['RESULT'] = 0
            PrntLog.info('excute baseline check successful!')
        elif ret == 127:
            resInfo['RESULT'] = -1
            PrntLog.error('no such shell file')
        elif ret == 2:
            resInfo['RESULT'] = -2
            PrntLog.error('shell excute failed')
        else:
            resInfo['RESULT'] = -3
            PrntLog.error('shell excute failed because of other causes ')

        # 获取xml文件大小
        resInfo['XML_FILE'] = ''
        filename = r'/tmp/%s.xml' % info['XML_NAME']
        if ret == 0 and os.path.exists(filename):
            # 读取文件内容
            f = open(filename, 'r')
            for strline in f.readlines():
                resInfo['XML_FILE'] = resInfo['XML_FILE'] + strline
            f.close()
            resInfo['XML_LENGTH'] = len(resInfo['XML_FILE'])
        else:
            resInfo['XML_LENGTH'] = 0
            PrntLog.error('Failed BaseLineCheck')

        PrntLog.info('BaseLineCheck resInfo: %s' % resInfo)
        strMsg = opermsgpaser.Msg_Shell_Excute_Result(resInfo)
        pf_base.sendmsg(strMsg)
        return
Exemple #29
0
    def OperParserMsg(self, str):
        try:
            operlinkInfo = opermsgpaser.MsgParser(str)
        except Exception as e:
            PrntLog.error('OperParser Failed: %s' % e)
            return

        try:
            #检查消息是否属于本主机
            if not operlinkInfo.has_key('IP'):
                return
            if not judge_ip_localhost(operlinkInfo['IP']):
                PrntLog.info('It is not own command.return. operlinkIp=%s' %
                             (operlinkInfo['IP']))
                return

            PrntLog.info('%s' % operlinkInfo)
            #阻断链路
            if operlinkInfo['MsgType'] == 0x00 or operlinkInfo[
                    'MsgType'] == 0x1A:
                logparser.stopLinkAndSendRes(operlinkInfo)

            #增加用户
            elif operlinkInfo['MsgType'] == 0x40:
                self.AddNewAccount(operlinkInfo)

            #修改密码
            elif operlinkInfo['MsgType'] == 0x42:
                self.ChangePasswd(operlinkInfo)

            #修改用户名
            elif operlinkInfo['MsgType'] == 0x47:
                self.ChangeAccountName(operlinkInfo)
            #删除用户
            elif operlinkInfo['MsgType'] == 0x44:
                self.DelAccount(operlinkInfo)
            #获取平台创建的用户列表
            elif operlinkInfo['MsgType'] == 0x46:
                self.getCreateAccountList(operlinkInfo)

            # 基线核查
            elif operlinkInfo['MsgType'] == 0x11:
                self.BaseLineCheck(operlinkInfo)
            #禁用网卡
            elif operlinkInfo['MsgType'] == 0x50:
                #启动线程阻断网卡,并sleep 5,以保证kafka消费此条消息
                threading.Thread(target=stopnetcard,
                                 args=(operlinkInfo, )).start()
        except Exception as e:
            PrntLog.error('Failed OperParser %s' % e)
            PrntLog.error("OperParser fail: %s" % traceback.format_exc())
Exemple #30
0
    def AddNewAccount(self, info):
        resInfo = {}
        resInfo['ID'] = info['ID']
        resInfo['IP'] = info['IP']

        cmdline = 'useradd %s' % info['USER_NAME']
        ret = os.system(cmdline)
        ret >>= 8

        if ret == 9:
            #用户已存在
            resInfo['RESULT'] = 1
            strMsg = opermsgpaser.Msg_AddNewCount_Res_Data(resInfo)
            pf_oper.sendmsg(strMsg)
            PrntLog.error('user %s  already exists' % info['USER_NAME'])
            return
        elif ret != 0:
            #其他错误
            resInfo['RESULT'] = 2
            strMsg = opermsgpaser.Msg_AddNewCount_Res_Data(resInfo)
            pf_oper.sendmsg(strMsg)
            PrntLog.error('useradd %s unkown error!' % info['USER_NAME'])
            return

        #设置密码
        salt = getsalt()
        passwd = crypt.crypt(info['PASSWD'], salt)
        cmdline = 'usermod -p %s %s' % (passwd, info['USER_NAME'])
        ret = os.system(cmdline)
        ret >>= 8

        if ret == 0:
            #成功
            resInfo['RESULT'] = 0
            global gCreateAccountrSet
            gCreateAccountrSet.add(info['USER_NAME'])
            userListTofile()
            PrntLog.info('Msg_AddNewCount_Res_Data %s ' % resInfo)
            strMsg = opermsgpaser.Msg_AddNewCount_Res_Data(resInfo)
            pf_oper.sendmsg(strMsg)
            PrntLog.info('user %s add successful' % info['USER_NAME'])
            return
        else:
            resInfo['RESULT'] = 2
            PrntLog.info('Msg_AddNewCount_Res_Data %s ' % resInfo)
            strMsg = opermsgpaser.Msg_AddNewCount_Res_Data(resInfo)
            pf_oper.sendmsg(strMsg)
            PrntLog.error('user %s set passwd failed ' % info['USER_NAME'])
            return