Ejemplo n.º 1
0
	def rule_unblock(self, confname, parse={}):
		# 解析block,注意配置文件不能缺少关键字
		try:
			action = parse['block']['action']
			expire = parse['block']['expire']
			command = parse['block']['ubkcmd']
			iptables = parse['block']['iptables']
		except Exception as e:
			Loger().ERROR("block rule farmat error.")
			raise

		if action:
			#解封过时记录
			call_cmd=''
			kwargs={'exptime': {'$lt': int(time.time())}, 'confname': confname}
			for item in CacheServer().find_conditions(self.Bcol, **kwargs):
				if iptables:
					call_cmd=("/sbin/iptables -D INPUT -s %s -j DROP" % item['_id'])
				else:
					if command.find(' %s')>0:
						temp={}
						temp['_id']=item['_id']
						temp['total']=item['total']
						temp['unblock']=1
						call_cmd=(command % temp)

				subprocess.call(call_cmd, shell=True)
				Loger().WARNING(Notes['UNLOCK'] % item['_id'])

			CacheServer().delete_many(self.Bcol, kwargs)
Ejemplo n.º 2
0
    def __init__(self):
        Dshield.__init__(self)
        """Instant a CacheServer
		"""
        self.Cache = CacheServer().create_or_connect_cache()
        self.Dcol = self.Cache["DSTAT"]
        CacheServer().create_index(self.Dcol, "exptime",
                                   self.avr['expire_after_seconds'])
Ejemplo n.º 3
0
	def rule_filter(self, parse={}):

		if parse['bolt'] in ["TCP", "UDP"]:
			col = self.cache_connect(parse['bolt'])
		else:
			Loger().ERROR("Bolt value must be 'TCP', 'UDP' !")
			raise

		# 解析filter,注意配置文件不能缺少关键字
		try:
			timeDelta =       parse['filter']['timeDelta']  #时间区间, Seconds.
			trustIps =        parse['filter']['trustIps']   #排除src白名单
			motrPort =        parse['filter']['motrPort']   #过滤端口
			motrProto =       parse['filter']['motrProto']  #过滤协议
			flags =           parse['filter']['flags']      #连接状态
			noOfConnections = parse['filter']['noOfConnections'] #阀值
			noOfCondition =   parse['filter']['noOfCondition']   #阀值条件 如$ge\$gt\$gte\$lt\$lte
			returnFiled =     parse['filter']['returnFiled']     #过滤器返回的字段名, blot表里必须存在
		except Exception as e:
			Loger().ERROR("filter rule farmat error.")
			raise

		#构造查询
		aggs=[]
		lte_time = int(time.time())
		gte_time = (lte_time - timeDelta)
		if timeDelta: aggs.append({'$match': {'time' : {'$gte' : gte_time, '$lte' : lte_time}}})
		if flags:     aggs.append({'$match': {'flags': {'$in': flags}}})
		if motrPort:  aggs.append({'$match': {'dport': {'$in': motrPort}}})
		if trustIps:  aggs.append({'$match': {'src': {'$nin': trustIps}}})
		aggs.append({'$group': {'_id': '$%s' %returnFiled, 'total': {'$sum': 1}}})
		aggs.append({'$match': {'total': {noOfCondition: noOfConnections}}})

		#Loger().WARNING(aggs)
		return CacheServer().find_aggregate(col, aggs)
Ejemplo n.º 4
0
	def __init__(self, **kwargs):
		self.filepath = kwargs['filepath'] if kwargs['filepath'] else CONF_DIR+"/rules"
		self.filetype = kwargs['filetype'] if kwargs['filetype']=='yaml' else 'json'
		self.S = {}

		"""Instant a CacheServer
		"""
		self.Cache = CacheServer().create_or_connect_cache()
		self.Bcol = self.Cache["BLOCK"]
Ejemplo n.º 5
0
	def view(self):
		table = PrettyTable(['_ID','ConfName','Total','Command','Time'])
		kwargs={'exptime': {'$gte': int(time.time())}}
		for item in CacheServer().find_conditions(self.Bcol, **kwargs):
			table.add_row([item['_id'], item['confname'], item['total'], item['command'], time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(item['time']))])

		table.sort_key(item['time'])
		table.reversesort=False
		table.border = 1
		print(table)
Ejemplo n.º 6
0
    def __init__(self, **kwargs):
        self.interface = kwargs["interface"] if kwargs["interface"] else 'any'
        self.filters = kwargs["filters"]
        self.__max_bytes = kwargs["max_bytes"]
        self.__promiscuous = kwargs["promiscuous"]
        self.__buffer_timeout = kwargs["buffer_timeout"]
        self.__expire_after_seconds = kwargs["expire_after_seconds"]
        """Instant a CacheServer

            exptime:
                expireAfterSeconds: <int> Used to create an expiring (TTL) collection. 
                MongoDB will automatically delete documents from this collection after <int> seconds. 
                The indexed field must be a UTC datetime or the data will not expire.
        """
        self.Cache = CacheServer().create_or_connect_cache()
        self.TCPcol = self.Cache["TCP"]
        self.UDPcol = self.Cache["UDP"]
        CacheServer().create_index(self.TCPcol, "exptime",
                                   self.__expire_after_seconds)
        CacheServer().create_index(self.UDPcol, "exptime",
                                   self.__expire_after_seconds)
Ejemplo n.º 7
0
 def show(self):
     table = PrettyTable([
         'Time', '1min', '5min', '15min', '%CPU', 'MemFree(MiB)',
         'Recv(MiB)', 'Send(MiB)'
     ])
     kwargs = {'time': {'$gte': int(time.time() - 900)}}
     for item in CacheServer().find_conditions(self.Dcol, **kwargs):
         table.add_row([
             time.strftime("%Y-%m-%d %H:%M:%S",
                           time.localtime(item['time'])), item['1m'],
             item['5m'], item['15m'], item['cpu_percent'], item['mem_free'],
             item['recv'], item['send']
         ])
     table.sort_key(item['time'])
     table.reversesort = False
     table.border = 1
     print(table)
Ejemplo n.º 8
0
	def load_cache(self, collection, condition, stdout):
		return CacheServer().replace_id(collection, condition, stdout)
Ejemplo n.º 9
0
	def cache_connect(self, bolt):
		return self.Cache[CacheServer().get_collection(self.Cache, bolt)]
Ejemplo n.º 10
0
 def load_cache(self, collection_obj, stdout):
     CacheServer().insert_one(collection_obj, stdout)