def report_session_loginfail(usrname, rhost): linkInfo = {} linkInfo['USER_NAME'] = usrname linkInfo['time'] = get_cuurent_time( ) linkInfo['LOCAL_IP'] = get_host_ip( ) PrntLog.info('session login fail. usrname=%s rhost=%s'%(usrname,rhost)) if rhost =='': # 发送本地session登录失败报文 strMsg = MsgWrap( linkInfo ).Msg_LOCAL_LogFail_Data( ) else: if os_version["type"] == "redhat": if os_version["version"] == 5: keystr = 'gdm-binary' elif os_version["name"] =='centos' and os_version["version"] == 7: keystr = 'lightdm-gtk' elif os_version["name"] =='redhat' and os_version["version"] == 7: keystr = 'lightdm' else: keystr = '-session' else: keystr = '-session' linkInfo['CLIENT_IP'] = rhost cmdline="/usr/local/sagent-3000-ns/netstat -ntp | grep %s | grep %s: | head -n 1|awk '{print $5}'" % (keystr,rhost) (status, output) = commands.getstatusoutput(cmdline) linkInfo['CLIENT_PORT'] = output.split(':')[-1] cmdline="/usr/local/sagent-3000-ns/netstat -ntp | grep %s | grep %s: | head -n 1|awk '{print $4}'" %(keystr,rhost) (status, output) = commands.getstatusoutput(cmdline) localPort = output.split(':')[-1] # 发送x11登录失败报文 strMsg = MsgWrap( linkInfo ).Msg_X11_LogFail_Data( ) proc_failed_login(rhost, usrname, time.time(), localPort) pf_oper.sendmsg( strMsg )
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))
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 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
def USBCountInfo(self): #TODO 此处处理了移动盘,移动介质是否还包含其他? (status, output) = commands.getstatusoutput( 'ls -l /dev/disk/by-path/*-usb-* | fgrep -v part') #print output if output == '' or re.search('ls: ', output): PrntLog.info('USBCountInfo:3 6 0') return "3 6 0" lines = [] count = 0 while '\n' in output: line, output = output.split('\n', 1) line = line.split(' -> ../../')[1] lines.append(line) count = count + 1 output = output.split(' -> ../../')[1] lines.append(output) count = count + 1 ret = str(count) + ' ' for line in lines: with open('/proc/partitions', 'r') as dp: for disk in dp.readlines(): if re.search(line + '\n', disk): blknum = disk.strip().split(' ')[-2] ret = ret + str(round(float(blknum) / 1024 / 1024, 2)) + ' ' PrntLog.info('USBCountInfo:3 6 %s' % ret) return "3 6 " + ret
def report(pathname, mode, oldperm, newperm): username = auditOper.get_file_change_usrname(pathname) strings = "<4> " + get_prefix() + " 5 34 " + get_host_ip( ) + ' ' + username + ' ' + pathname + ' ' + mode + ' ' + oldperm + ' ' + newperm PrntLog.info(strings) #print "report:",strings pf_monitor.sendmsg(strings)
def OSInfo(self): #var=platform.dist() uname = platform.uname() #('Linux', 'nari-rhel7', '3.10.0-229.el7.x86_64', '#1 SMP Thu Jan 29 18:37:38 EST 2015', 'x86_64', 'x86_64') ostye = "2" ''' with open('/etc/issue', 'r') as dp: for line in dp.readlines(): type = line.strip().split(' ')[0] break #TODO 凝思版本号是啥? if "Linx" in type: osversion = "0" elif "Kylin" in type: osversion = "1" num = line.strip().split(' ')[2] else: osversion = "2" num = line.strip().split(' ')[-2] ''' PrntLog.info('OSInfo:3 10 %s %s %s' % (ostye, str(os_version["version"]), uname[2])) return "3 10 " + ostye + " " + str( os_version["version"]) + " " + uname[2]
def memConfigInfo(self): info1 = psutil.virtual_memory() info2 = psutil.swap_memory() str1 = str(float(info1.total) / 1024 / 1024 / 1024) str2 = str(float(info2.total) / 1024 / 1024 / 1024) PrntLog.info('memConfigInfo:"3 2 %s %s' % (str1, str2)) return "3 2 " + str1 + " " + str2
def Msg_ChangeAccountName_Res_Data(self, info): msgType = 0x48 strMsg = struct.pack('<B32s4s32sB', msgType, info['ID'], covert_ipaddr(info['IP']), info['USER_NAME'], info['RESULT']) PrntLog.info(PrtMsg(strMsg)) return strMsg
def Msg_LOCAL_HeartBeat(self): msgType = 0x13 strMsg = struct.pack('<B4sQ', msgType, covert_ipaddr(self.LinkInfo['LOCAL_IP']), int(self.LinkInfo['time'].replace('_', '')[:-3])) PrntLog.info(PrtMsg(strMsg)) return strMsg
def Msg_SSH_Client_Data(self): msgType = 0 if self.LinkInfo['LOGIN_TYPE'] == 'ssh': upSSHLink = struct.pack( '<4sH4sQ', covert_ipaddr(self.LinkInfo['CLIENT_IP']), int(self.LinkInfo['CLIENT_PORT']), covert_ipaddr(self.LinkInfo['LOCAL_IP']), int(self.LinkInfo['time'].replace('_', '')[:-3])) else: upSSHLink = struct.pack('<18s', '') locaSSHlLink = struct.pack( '<4sH4sQ', covert_ipaddr(self.LinkInfo['LOCAL_IP']), int(self.LinkInfo['FORWARD_PORT']), covert_ipaddr(self.LinkInfo['REMOTE_IP']), int(self.LinkInfo['REMOTE_DT'].replace('_', '')[:-3])) if self.LinkInfo['LOGIN_TYPE'] == 'x11': upX11Link = struct.pack( '<4sH4sQ', covert_ipaddr(self.LinkInfo['CLIENT_IP']), int(self.LinkInfo['CLIENT_PORT']), covert_ipaddr(self.LinkInfo['LOCAL_IP']), int(self.LinkInfo['time'].replace('_', '')[:-3])) else: upX11Link = struct.pack('<18s', '') strMsg = struct.pack('<B18s18s18s4s256s', msgType, upSSHLink, locaSSHlLink, upX11Link, '', '') PrntLog.info(PrtMsg(strMsg)) return strMsg
def ModemInfo(self): (status, count ) = commands.getstatusoutput('ls /dev/modem* | grep -v "ls" | wc -l') if "modem" in count: count = "0" PrntLog.info('ModemInfo:3 5 %s 0' % count) return "3 5 " + count + " 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()
def Msg_LOCAL_Login_Data(self): msgType = 0x0C strMsg = struct.pack('<B4sQ32s', msgType, covert_ipaddr(self.LinkInfo['LOCAL_IP']), int(self.LinkInfo['time'].replace('_', '')[:-3]), self.LinkInfo['USER_NAME']) PrntLog.info(PrtMsg(strMsg)) return strMsg
def Msg_SSH_TestStopLink(self): msgType = 0x00 idString = '123456789' strMsg = struct.pack('<B32s4sI', msgType, idString, covert_ipaddr(self.LinkInfo['LOCAL_IP']), int(self.LinkInfo['PID_NUM'])) PrntLog.info(PrtMsg(strMsg)) return strMsg
def process_session_loginout(strInfo): #Jun 21 01:38:22 localhost gdm[23268]: pam_unix(gdm:session): session closed for user root --- kylin #Jun 21 07:58:57 localhost login: pam_unix(login:session): session closed for user nari #Jul 4 22:52:15 localhost pam: gdm-password: pam_unix(gdm-password:session): session closed for user root --rhel6.4 #Aug 4 15:38:49 localhost gdm[3081]: pam_unix(gdm:session): session closed for user root ----rhel5.6 #Jan 31 03:27:31 nari-desktop gdm-session-worker[25067]: pam_unix(gdm:session): session closed for user nari ----ubuntu10 strList = strInfo.split(' ') if strList[-1] == 'lightdm' or strList[-1] == 'gdm': return ''' if os_version["type"] == "redhat" and os_version["version"] == 5: keystr = 'gdm[' elif os_version["name"] == "redhat" and os_version["version"] == 7: keystr = 'gdm-password]' elif os_version["name"] == "centos" and os_version["version"] == 7: if strInfo.find('login:'******':session' else: keystr = 'dm:session' elif os_version["type"] == "debian": #ubuntu10 keystr = 'gdm-session-worker[' else: keystr = 'pam:' pos = strInfo.find( keystr ) if pos < 0: if strInfo.find( 'login:'******''' username = strInfo.split( ' ' )[-1] if strInfo.find( 'login:'******'"kdeinit4: ksm"' else: keystr = '-sessio' else: keystr = '-sessio' x11List = get_x11_linkInfo_by_ProcessName( keystr ) ret=find_linkInfo_for_logout(x11List) if not ret: #没有x11链路退出,则为本地图形界面退出处理 process_local_session_logout( username ) else: global gLinkList linkInfo=ret strMsg = MsgWrap( linkInfo ).Msg_X11_Loginout_Data( ) pf_oper.sendmsg( strMsg ) gLinkList.remove( linkInfo ) PrntLog.info( 'Remove x11 logout %s' % linkInfo )
def test_getCreatAccountList_Data(self): msgType = 0x46 idString = 'abcdefghijk' ipString = '192.168.0.91' strMsg = struct.pack('<B32s4s', msgType, idString, covert_ipaddr(ipString)) PrntLog.info('test_getCreatAccountList_Data send: ') PrntLog.info(PrtMsg(strMsg)) return strMsg
def test_stopnetcard(self, ipString): msgType = 0x50 idString = 'abcdefghijk' #ipString = '192.168.0.91' strMsg = struct.pack('<B32s4s', msgType, idString, covert_ipaddr(ipString)) PrntLog.info('test_stopnetcard send: ') PrntLog.info(PrtMsg(strMsg)) return strMsg
def Msg_X11_LogFail_Data(self): msgType = 0x19 strMsg = struct.pack('<B4sH4sQ32s', msgType, covert_ipaddr(self.LinkInfo['CLIENT_IP']), int(self.LinkInfo['CLIENT_PORT']), covert_ipaddr(self.LinkInfo['LOCAL_IP']), int(self.LinkInfo['time'].replace('_', '')[:-3]), self.LinkInfo['USER_NAME']) PrntLog.info(PrtMsg(strMsg)) return strMsg
def judge_ssh_link_exist(pid): cmdline = "ps -ef |grep -v grep |grep sshd |grep " + pid PrntLog.info(cmdline) fp = os.popen( cmdline ) for line in fp: if pid in line and 'sshd' in line: fp.close() return True fp.close() return False
def ParaCount(self): (status, dd) = commands.getstatusoutput('ls /dev/lp*') list = dd.split('\n') count = 0 for lp in list: (result, tmp) = commands.getstatusoutput('echo "test" >' + lp) if result == 0: count = count + 1 PrntLog.info('ParaCount:3 8 %s' % str(count)) return "3 8 " + str(count)
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)
def Msg_SSH_Logout_Data(self): msgType = 0x04 strMsg = struct.pack('<B4sH4sQ', msgType, covert_ipaddr(self.LinkInfo['CLIENT_IP']), int(self.LinkInfo['CLIENT_PORT']), covert_ipaddr(self.LinkInfo['LOCAL_IP']), int(self.LinkInfo['time'].replace('_', '')[:-3])) PrntLog.info(PrtMsg(strMsg)) return strMsg
def test_DelAccount_Data(self): msgType = 0x44 idString = 'abcdefghijk' ipString = '192.168.0.91' usrname = 'test4' strMsg = struct.pack('<B32s4s32s', msgType, idString, covert_ipaddr(ipString), usrname) PrntLog.info('test_DelAccount_Data send: ') PrntLog.info((PrtMsg(strMsg))) return strMsg
def MsgParser(self, msgStr): PrntLog.info(PrtMsg(msgStr)) operlinkInfo = {} MsgType = struct.unpack("<B", msgStr[0]) operlinkInfo['MsgType'] = MsgType[0] #ssh和x11链路阻断 if MsgType[0] == 0x00 or MsgType[0] == 0x1A: ret = struct.unpack("<B32s4sI", msgStr[:41]) operlinkInfo['ID'] = ret[1] operlinkInfo['IP'] = recovert_ipaddr(ret[2]) operlinkInfo['PID_NUM'] = str(ret[3]) #添加用户 修改密码 elif MsgType[0] == 0x40 or MsgType[0] == 0x42: ret = struct.unpack("<B32s4s32s20s", msgStr[:89]) operlinkInfo['ID'] = ret[1] operlinkInfo['IP'] = recovert_ipaddr(ret[2]) operlinkInfo['USER_NAME'] = ret[3].rstrip('\0') operlinkInfo['PASSWD'] = ret[4].rstrip('\0') #修改用户 elif MsgType[0] == 0x47: ret = struct.unpack("<B32s4s32s32s", msgStr[:101]) operlinkInfo['ID'] = ret[1] operlinkInfo['IP'] = recovert_ipaddr(ret[2]) operlinkInfo['USER_NAME'] = ret[3].rstrip('\0') operlinkInfo['NEW_USERNAME'] = ret[4].rstrip('\0') #删除用户 elif MsgType[0] == 0x44: ret = struct.unpack("<B32s4s32s", msgStr[:69]) operlinkInfo['ID'] = ret[1] operlinkInfo['IP'] = recovert_ipaddr(ret[2]) operlinkInfo['USER_NAME'] = ret[3].rstrip('\0') #获取平台创建的用户列表 elif MsgType[0] == 0x46: ret = struct.unpack("<B32s4s", msgStr[:37]) operlinkInfo['ID'] = ret[1] operlinkInfo['IP'] = recovert_ipaddr(ret[2]) # 基线核查 add by sunboyan start from here in 2017/6/30 elif MsgType[0] == 0x11: ret = struct.unpack("<B32s4s50sI", msgStr[:91]) operlinkInfo['SHELL_NAME'] = ret[1].rstrip('\0') operlinkInfo['IP'] = recovert_ipaddr(ret[2]) operlinkInfo['XML_NAME'] = ret[3].rstrip('\0') operlinkInfo['CHECKLIST_LEN'] = ret[4] msgStr_length = 91 + operlinkInfo['CHECKLIST_LEN'] formatString = '<B32s4s50sI%ds' % operlinkInfo['CHECKLIST_LEN'] ret_again = struct.unpack(formatString, msgStr[:msgStr_length]) operlinkInfo['CHECKLIST'] = ret_again[5].rstrip('\0') # 基线核查 add by sunboyan end in here in 2017/6/30 #禁用网卡请求 elif MsgType[0] == 0x50: ret = struct.unpack("<B32s4s", msgStr[:37]) operlinkInfo['ID'] = ret[1] operlinkInfo['IP'] = recovert_ipaddr(ret[2]) return operlinkInfo
def test_ChangePasswd_Data(self): msgType = 0x42 idString = 'abcdefghijk' ipString = '192.168.0.91' usrname = 'test4' passwd = 'kylin.2017' strMsg = struct.pack('<B32s4s32s20s', msgType, idString, covert_ipaddr(ipString), usrname, passwd) PrntLog.info('test_ChangePasswd_Data send: ') PrntLog.info(PrtMsg(strMsg)) return strMsg
def test_ChangeAccountName_Data(self): msgType = 0x47 idString = 'abcdefghijk' ipString = '192.168.0.91' usrname = 'test4' newusername = '******' strMsg = struct.pack('<B32s4s32s32s', msgType, idString, covert_ipaddr(ipString), usrname, newusername) PrntLog.info('test_ChangeAccountName_Data send: ') PrntLog.info(PrtMsg(strMsg)) return strMsg
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)
def config_check(): config_md5 = get_md5("./agent.conf") while True: time.sleep(1) new_md5 = get_md5("./agent.conf") if new_md5 != config_md5: str = "agent.conf was modified!" PrntLog.warning(str) print str config_md5 = new_md5 return
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))