def sendto(self, subject, msg): if str(self.avr['type']) == 'ssl': try: self.sslsend(subject, msg) save_log('MAIL', 'Send mail Success.') except Exception, e: save_log('MAIL', 'Send mail failed to: %s' % e)
def _unblock(self): for li in DB_Conn("ddos").select("select target,connections from block where time <= now() - %s" % (self.avr['blockTimeIP'])): self._unblock_act(li['target']) try: DB_Conn("ddos").delete("delete from block where target = '%s'" % li['target']) except Exception, e: save_log('ERROR',"'CC_unblock' Exception: %s" %(e))
def _block(self, ttls): print ttls if self.avr['montInterface']: ttls.insert(2, self.avr['montInterface']) else: ttls.insert(2, "") json_body = [{ "measurement": "block_ttl", "tags": { "ttl": ttls[0], "interface": ttls[2] }, "fields": { "counts": float(ttls[1]) } }] if str(self.avr['monlisten']) == "false": try: if not list( DB_Conn('ddos').select( "select * from block_ttl where ttl = '%s'" % ttls[0])): DB_Conn('ddos').insert(json_body) self._block_act(ttls) if self.avr['adminEmail']: self._sendmail(ttls) except Exception, e: save_log('ERROR', "'Sniff_block' Exception: %s" % (e))
def _reblock_act(self): try: d = commands.getoutput("/sbin/iptables -nL INPUT|grep ^DROP|awk '{print $4}'") for li in DB_Conn("ddos").select("select target,connections from block"): if not li['target'] in d.split('\n'): os.system('/sbin/iptables -I INPUT -s %s -j DROP' % li['target']) save_log('REBL','%s reload in iptables Success.' % li['target']) except Exception,e: save_log('ERROR',"'CC_reblock_act' Exception: %s" %(e))
def _unblock(self): for li in DB_Conn("ddos").select( "select * from block_ttl where time <= now() - %s" % (self.avr['blockTimeTTL'])): self._unblock_act([li['ttl'], li['counts'], li['interface']]) try: DB_Conn("ddos").delete( "delete from block_ttl where ttl = '%s'" % li['ttl']) except Exception, e: save_log('ERROR', "'Sniff_unblock' Exception: %s" % (e))
def _unblock_act(self, ttls): try: if not self.avr['montInterface']: os.system( '/sbin/iptables -D INPUT -p tcp -m tcp --tcp-flags SYN,RST,ACK SYN -m ttl --ttl-eq %s -j DROP' % ttls[0]) else: os.system( '/sbin/iptables -D INPUT -i %s -p tcp -m tcp --tcp-flags SYN,RST,ACK SYN -m ttl --ttl-eq %s -j DROP' % (ttls[2], ttls[0])) except Exception, e: save_log('ERROR', "'Sniff_unblock_act' Exception: %s" % (e))
def _dstat(self): net = Dstat().net() load = Dstat().loadavg() json_body = [{ "measurement": "dstat", "tags": {"1m":load['1m'],"recv":net['recv']}, "fields":{"1m":load['1m'], "5m":load['5m'], "15m":load['15m'], "recv":net['recv'], "send":net['send']} }] try: if not list(DB_Conn("system").select("select * from dstat where time >= now() - 1m")): DB_Conn("system").insert(json_body) except Exception, e: save_log('ERROR',"'CC_dstat' Exception: %s" %(e))
def _block(self, ips): json_body = [{ "measurement": "block", "tags": {"target":ips[1], "locaddr":ips[2], "port":ips[3]}, "fields":{"connections":float(ips[0])} }] if str(self.avr['monlisten']) == "false": try: if not list(DB_Conn('ddos').select("select * from block where target = '%s'" % ips[1])): DB_Conn('ddos').insert(json_body) self._block_act(ips) if self.avr['adminEmail']: self._sendmail(ips) except Exception, e: save_log('ERROR',"'CC_block' Exception: %s" %(e))
def _collect_current(self, data): if len(data)>0: for line in data.strip().split("\n"): line = line.strip().split(' ') if int(line[0]) < 1: continue json_body = [{ "measurement":"current", "tags":{"foreaddr":line[3], "locaddr":line[1], "port":line[2], "state":line[4]}, "fields":{"connections":int(line[0])} }] try: if not list(DB_Conn("connect").select("select * from current where foreaddr = '%s' and time >= now() - 1m" % line[3])): DB_Conn("connect").insert(json_body) except Exception, e: save_log('ERROR',"'CC_collect_current' Exception: %s" %(e))
def _reblock_act(self): try: d = commands.getoutput( "/sbin/iptables -nL INPUT|grep ^DROP|awk '{print $NF}'") for li in DB_Conn("ddos").select("select * from block_ttl"): if not li['ttl'] in d.split('\n'): if not li['interface']: os.system( '/sbin/iptables -I INPUT -p tcp -m tcp --tcp-flags SYN,RST,ACK SYN -m ttl --ttl-eq %s -j DROP' % li['ttl']) else: os.system( '/sbin/iptables -I INPUT -i %s -p tcp -m tcp --tcp-flags SYN,RST,ACK SYN -m ttl --ttl-eq %s -j DROP' % (li['interface'], li['ttl'])) save_log('REBL', 'TTL:%s reload in iptables Success.' % li['ttl']) except Exception, e: save_log('ERROR', "'Sniff_reblock_act' Exception: %s" % (e))
def _tcpdump(self): s = {} s['wip'] = "" s['port'] = "" for port in self.avr['montport'].split(","): if port: s['port'] = s['port'] + 'dst port {0} or '.format(port) for wip in self.avr['whitelistIPs'].split(","): if wip: if wip.find("~") > 0: lstart = int(wip.split("~")[0].split(".")[-1]) lend = int(wip.split("~")[1].split(".")[-1]) + 1 ldun = ".".join(wip.split("~")[1].split(".")[0:3]) for wli in xrange(lstart, lend): s['wip'] = s['wip'] + '! dst net {0} and '.format( "%s.%d" % (ldun, wli)) elif wip.find("-") > 0: lstart = int(wip.split("-")[0].split(".")[-1]) lend = int(wip.split("-")[1].split(".")[-1]) + 1 ldun = ".".join(wip.split("-")[1].split(".")[0:3]) for wli in xrange(lstart, lend): s['wip'] = s['wip'] + '! dst net {0} and '.format( "%s.%d" % (ldun, wli)) else: s['wip'] = s['wip'] + '! dst net {0} and '.format(wip) s['port'] = s['port'].strip("or ") s['wip'] = s['wip'].strip("and ") command = ['tcpdump', '-nvtqO', s['port'], 'and', s['wip']] if not self.avr['montInterface'] is None: command.insert(1, "-i%s" % self.avr['montInterface']) if not self.avr['montProtocol'] is None: command.insert(1, self.avr['montProtocol']) try: p1 = subprocess.Popen(command, bufsize=20000, stdout=subprocess.PIPE, close_fds=True) except Exception, e: save_log('ERROR', "'Sniff_tcpdump' Exception: %s" % (e))
def _collect(self, process, timeout): coll_cnt = [] clone_coll = [] dnct_ttls = {} count = None while process.poll() is None: time.sleep(0.1) for line in iter(process.stdout.readline, ""): if count is None: timeout = int(time.time()) + timeout line = line.split(' ') strl = str(line) if strl.find("'ttl'") >= 0: if line[4].strip(',') not in self.whileTTL: coll_cnt.append(line[4].strip(',')) if int(time.time()) > timeout: try: process.terminate() break except Exception, e: save_log('ERROR', "'Sniff_collect' Exception: %s" % (e)) count = True clone_coll = set(coll_cnt) for item in clone_coll: dnct_ttls[item] = coll_cnt.count(item) process.communicate() if process.stdin: process.stdin.close() if process.stdout: process.stdout.close() if process.stderr: process.stderr.close() try: process.kill() except Exception, e: pass
self.__init__() msg = MIMEText(msg, 'plain', 'utf-8') #中文需参数‘utf-8’,单字节字符不需要 msg['Subject'] = Header(subject, 'utf-8') smtp = smtplib.SMTP() smtp.connect(self.avr['smtpserver']) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.set_debuglevel(1) smtp.login(self.avr['username'], self.avr['password']) smtp.sendmail(self.sender, self.avr['receiver'], msg.as_string()) smtp.quit() """ @name: 发送邮件 """ def sendto(self, subject, msg): if str(self.avr['type']) == 'ssl': try: self.sslsend(subject, msg) save_log('MAIL', 'Send mail Success.') except Exception, e: save_log('MAIL', 'Send mail failed to: %s' % e) else: try: self.nonsend(subject, msg) save_log('MAIL', 'Send mail Success.') except Exception, e: save_log('MAIL', 'Send mail failed to: %s' % e)
def _unblock_act(self, ip): try: os.system('/sbin/iptables -D INPUT -s %s -j DROP' % ip) except Exception, e: save_log('ERROR',"'CC_unblock_act' Exception: %s" %(e))
json_body = [{ "measurement": "block", "tags": {"target":ips[1], "locaddr":ips[2], "port":ips[3]}, "fields":{"connections":float(ips[0])} }] if str(self.avr['monlisten']) == "false": try: if not list(DB_Conn('ddos').select("select * from block where target = '%s'" % ips[1])): DB_Conn('ddos').insert(json_body) self._block_act(ips) if self.avr['adminEmail']: self._sendmail(ips) except Exception, e: save_log('ERROR',"'CC_block' Exception: %s" %(e)) else: save_log('RECORD', "IP addresses:%s has %s connections to server ip %s:%s." % (ips[1], ips[0], ips[2], ips[3])) @async def _block_act(self,ips): try: os.system('/sbin/iptables -I INPUT -s %s -j DROP' % ips[1]) except Exception, e: save_log('ERROR',"'CC_block_act' Exception: %s" %(e)) save_log('LOCK',"%s has been blocked, It has %s connections to server ip %s:%s." % (ips[1], ips[0], ips[2], ips[3])) @async def _unblock(self): for li in DB_Conn("ddos").select("select target,connections from block where time <= now() - %s" % (self.avr['blockTimeIP'])): self._unblock_act(li['target']) try: DB_Conn("ddos").delete("delete from block where target = '%s'" % li['target'])
}] if str(self.avr['monlisten']) == "false": try: if not list( DB_Conn('ddos').select( "select * from block_ttl where ttl = '%s'" % ttls[0])): DB_Conn('ddos').insert(json_body) self._block_act(ttls) if self.avr['adminEmail']: self._sendmail(ttls) except Exception, e: save_log('ERROR', "'Sniff_block' Exception: %s" % (e)) else: save_log( 'RECORD', "The TTL:%s has %s packets transmitted. Attention please!" % (ttls[0], ttls[1])) @async def _block_act(self, ttls): try: if not self.avr['montInterface']: os.system( '/sbin/iptables -I INPUT -p tcp -m tcp --tcp-flags SYN,RST,ACK SYN -m ttl --ttl-eq %s -j DROP' % ttls[0]) else: os.system( '/sbin/iptables -I INPUT -i %s -p tcp -m tcp --tcp-flags SYN,RST,ACK SYN -m ttl --ttl-eq %s -j DROP' % (ttls[2], ttls[0])) except Exception, e: save_log('ERROR', "'Sniff_block_act' Exception: %s" % (e))