Example #1
0
 def post(self):
     user = {
         "id": request.json.get("id"),
         "password": request.json.get("password"),
     }
     doc = {
         "size": 10000,
         "query": {
             "bool": {
                 "must": [
                     {
                         "match": {
                             "id": user["id"]
                         }
                     },
                     {
                         "match": {
                             "password": user["password"]
                         }
                     }
                 ]
             }
         },
     }
     result = es.search(index="userdb", body=doc)["hits"]
     if result["total"]["value"] > 0:
         print(result)
         if result["hits"][0]["_source"]["valid"] == False:
             return {"state": "관리자 승인을 기다리세요!"}
     else:
         return {"state": "아이디와 비밀번호를 확인해주세요"}
     return {"state": "success", "user": result["hits"][0]["_source"]}
Example #2
0
 def get(self):
     doc = {
         "size": 10000,
         "query": {
             "match_all": {}
         },
     }
     users = []
     for r in es.search(index="userdb", body=doc)["hits"]["hits"]:
         users.append(r["_source"])
     return users
Example #3
0
 def post(self):
     """date와 agent image로 하루의 그 프로그램에 대한 networkconnection 내역들을 다 가져옵니다!"""
     d = request.json.get("date")
     a = request.json.get("agent")
     image = request.json.get("image")
     print(a, " ", d, " ", image)
     print("hi")
     result = []
     body = body = {
         "size": 10000,
         "query": {
             "bool": {
                 "must": [{
                     "match": {
                         "data.win.system.eventID": 3
                     }
                 }, {
                     "match_phrase": {
                         "data.win.eventdata.image": image
                     }
                 }, {
                     "match": {
                         "agent.name": a
                     }
                 }, {
                     "range": {
                         "@timestamp": {
                             "gte": "now-" + str(d + 1) + "d/d",
                             "lt": "now-" + str(d) + "d/d",
                         }
                     }
                 }]
             }
         }
     }
     for r in es.search(index="wazuh-alert*", body=body)["hits"]["hits"]:
         destIP = r["_source"]["data"]["win"]["eventdata"]["destinationIp"]
         destPort = r["_source"]["data"]["win"]["eventdata"][
             "destinationPort"]
         protocol = r["_source"]["data"]["win"]["eventdata"]["protocol"]
         ruleName = r["_source"]["data"]["win"]["eventdata"]["ruleName"]
         sourIP = r["_source"]["data"]["win"]["eventdata"]["sourceIp"]
         sourPort = r["_source"]["data"]["win"]["eventdata"]["sourcePort"]
         time = timefunc(r["_source"]["timestamp"])
         result.append({
             "destIP": destIP,
             "destPort": destPort,
             "protocol": protocol,
             "ruleName": ruleName,
             "sourIP": sourIP,
             "sourPort": sourPort,
             "time": time
         })
     return result
Example #4
0
    def get(self):
        """7045이벤트(서비스 설치관련 이벤트임) 불러오기"""
        body = {
            "size": 10000,
            "query": {
                "match_all": {

                }
            }
        }

        result = []
        return es.search(index=".opendistro-alerting-config", body="body")
Example #5
0
 def post(self):
     daysago = request.json.get("date")
     result = []
     body = {
         "size": 10000,
         "query": {
             "bool": {
                 "must": [{
                     "match": {
                         "data.win.system.eventID": 15
                     }
                 }, {
                     "regexp": {
                         "data.win.eventdata.targetFilename":
                         ".+Zone.Identifier"
                     }
                 }, {
                     "regexp": {
                         "data.win.eventdata.contents": ".+HostUrl.+"
                     }
                 }, {
                     "range": {
                         "@timestamp": {
                             "gte": "now-" + str(daysago) + "d/d",
                             "lt": "now"
                         }
                     }
                 }]
             }
         },
         "sort": [{
             "timestamp": "desc"
         }]
     }
     for r in es.search(index="wazuh-alert*", body=body)["hits"]["hits"]:
         time = timefunc(r["_source"]["@timestamp"])
         name = r["_source"]["agent"]["name"]
         prog = lastPath(r["_source"]["data"]["win"]["eventdata"]["image"])
         url = catchurl(
             r["_source"]["data"]["win"]["eventdata"]["contents"])
         file = lastPath(r["_source"]["data"]["win"]["eventdata"]
                         ["targetFilename"]).replace(
                             ":Zone.Identifier", "")
         result.append({
             "timestamp": time,
             "name": name,
             "image": prog,
             "file": file,
             "url": url
         })
     return result
Example #6
0
    def post(self):
        """근무 시간 외에 사용하고있는가? 를 감지."""
        # get wazuh agents!
        resultApi = []
        agodays = request.json.get('data')["date"]
        for i in range(0, int(agodays)):  # 일주일 로그를 수집하기위한 i
            endday = str(datetime.datetime.now() -
                         datetime.timedelta(days=(i + 1)))[0:10]
            startday = str(datetime.datetime.now() -
                           datetime.timedelta(days=(i)))[0:10]
            starttime = startday + " " + request.json.get('data')["start"]
            endtime = endday + " " + request.json.get('data')["end"]
            print(endtime, starttime)
            body = {
                "query": {
                    "bool": {
                        "must": [{
                            "match_phrase": {
                                "status": "active"
                            }
                        }, {
                            "range": {
                                "timestamp": {
                                    "time_zone": "+09:00",
                                    "gte": endtime,
                                    "lte": starttime,
                                    "format": "yyyy-MM-dd HH:mm"
                                }
                            }
                        }],
                    }
                },
                "aggs": {
                    "agent": {
                        "terms": {
                            "field": "name"
                        }
                    }
                }
            }
            result = es.search(index="wazuh-monitoring*",
                               body=body)["aggregations"]["agent"]["buckets"]
            if len(result) != 0:
                for r in result:
                    agent = r['key']
                    resultApi.append({"agent": agent, "date": startday})

            # 0시부터 근무 출근시간 까지 로그 수집햇음
            # 퇴근 시간 부터~ 0시까지 수집
        return resultApi
Example #7
0
    def post(self):
        """wi-fi(사실 랜연결도 잡음)연결 감지이벤트불러오기"""
        daysago = request.json.get("date")
        body = {
            "query": {
                "bool": {
                    "must": [{
                        "match": {
                            "data.win.system.channel":
                            "Microsoft-Windows-NetworkProfile/Operational"
                        }
                    }, {
                        "range": {
                            "@timestamp": {
                                "gte": "now-" + str(daysago) + "d/d",
                                "lt": "now"
                            }
                        }
                    }]
                }
            }
        }
        result = []
        for r in es.search(index="wazuh-alert*", body=body)["hits"]["hits"]:
            message = r["_source"]["data"]["win"]["system"]["message"]
            name = r["_source"]["data"]["win"]["eventdata"]["name"]
            time = timefunc(r["_source"]["timestamp"])
            agent = r["_source"]["agent"]["name"]
            connection = "판결되지 않음"
            con = False

            if message.find("식별 중...") != -1:
                continue
            if message.find("연결됨") != -1:
                con = True

            if con == True:
                connection = "연결됨"
            else:
                connection = "연결 해제"
            result.append({
                "agent": agent,
                "name": name,
                "connect": connection,
                "time": time
            })
        # status값을 연결됨, 연결되지 않음으로 구분하기 + 이름 가져오기 + host이름 가져오기!
        return result
Example #8
0
 def post(self):
     """필터링 되지 않은 driver event를 얻습니다."""
     daysago = request.json.get("date")
     body = {
         "size": 10000,
         "query": {
             "bool": {
                 "must": [{
                     "match": {
                         "data.win.system.eventID": 6
                     }
                 }, {
                     "range": {
                         "@timestamp": {
                             "gte": "now-" + str(daysago) + "d/d",
                             "lt": "now"
                         }
                     }
                 }]
             }
         },
         "sort": [{
             "timestamp": "desc"
         }]
     }
     result = []
     for s in es.search(index="wazuh-alerts*", body=body)["hits"]["hits"]:
         name = s["_source"]["agent"]["name"]
         sigstate = s["_source"]["data"]["win"]["eventdata"]["signed"]
         imageLoad = s["_source"]["data"]["win"]["eventdata"]["imageLoaded"]
         if sigstate == "true":
             signature = s["_source"]["data"]["win"]["eventdata"][
                 "signature"]
         else:
             signature = "None"
         date_t = timefunc(s["_source"]["@timestamp"])
         result.append({
             "agent": name,
             "driver": signature,
             "sigstate": sigstate,
             "imageLoad": imageLoad,
             "time": date_t
         })
     return result
Example #9
0
    def post(self):
        """7045이벤트(서비스 설치관련 이벤트임) 불러오기"""
        daysago = request.json.get("date")
        body = {
            "size": 10000,
            "query": {
                "bool": {
                    "must": [{
                        "match": {
                            "data.win.system.channel": "System"
                        }
                    }, {
                        "match": {
                            "data.win.system.eventID": "7045"
                        }
                    }, {
                        "range": {
                            "@timestamp": {
                                "gte": "now-" + str(daysago) + "d/d",
                                "lt": "now"
                            }
                        }
                    }]
                }
            }
        }
        print("hi")
        print(daysago)
        result = []
        for r in es.search(index="wazuh-alert*", body=body)["hits"]["hits"]:
            print(r)
            agent = r["_source"]["agent"]["name"]
            time = timefunc(r["_source"]["timestamp"])
            service = r["_source"]["data"]["win"]["eventdata"]["serviceName"]
            path = r["_source"]["data"]["win"]["eventdata"]["imagePath"]
            result.append({
                "agent": agent,
                "time": time,
                "service": service,
                "path": path
            })

        return result
Example #10
0
 def post(self):
     daysago = request.json.get("date")
     result = []
     body = {
         "size": 10000,
         "query": {
             "bool": {
                 "must": [{
                     "match": {
                         "data.win.system.eventID": 15
                     }
                 }, {
                     "regexp": {
                         "data.win.eventdata.targetFilename":
                         ".+Zone.Identifier"
                     }
                 }, {
                     "regexp": {
                         "data.win.eventdata.contents": ".+HostUrl.+"
                     }
                 }, {
                     "range": {
                         "@timestamp": {
                             "gte": "now-" + str(daysago) + "d/d",
                             "lt": "now"
                         }
                     }
                 }]
             }
         },
         "aggs": {
             "downcount": {
                 "terms": {
                     "field": "agent.name"
                 }
             }
         }
     }
     for r in es.search(index="wazuh-alert*",
                        body=body)["aggregations"]["downcount"]["buckets"]:
         result.append({"agent": r["key"], "count": r["doc_count"]})
     return result
Example #11
0
 def post(self):
     result = []
     daysago = request.json.get("date")
     body = {
         "size": 10000,
         "query": {
             "bool": {
                 "must": [{
                     "match": {
                         "data.win.system.eventID": 22
                     }
                 }, {
                     "range": {
                         "@timestamp": {
                             "gte": "now-" + str(daysago) + "d/d",
                             "lt": "now"
                         }
                     }
                 }]
             }
         },
         "sort": [{
             "timestamp": "desc"
         }]
     }
     for r in es.search(index="wazuh-alert*", body=body)["hits"]["hits"]:
         time = timefunc(r["_source"]["@timestamp"])
         name = r["_source"]["agent"]["name"]
         image = lastPath(r["_source"]["data"]["win"]["eventdata"]["image"])
         query = lastPath(
             r["_source"]["data"]["win"]["eventdata"]["queryName"])
         record = lastPath(
             r["_source"]["data"]["win"]["system"]["eventRecordID"])
         result.append({
             "timestamp": time,
             "name": name,
             "image": image,
             "query": query,
             "record": record
         })
     return result
Example #12
0
    def post(self):
        result = []
        daysago = request.json.get("date")
        body = {
            "size": 10000,
            "query": {
                "bool": {
                    "must": {
                        "range": {
                            "@timestamp": {
                                "gte": "now-" + str(daysago) + "d/d",
                                "lt": "now"
                            }
                        }
                    },
                    "must_not": {
                        "match": {
                            "agent.id": "000"
                        }
                    },
                }
            },
            "sort": [{
                "timestamp": "desc"
            }],
            "aggs": {
                "appusecount": {
                    "terms": {
                        "field": "agent.name",
                        "size": 20
                    }
                }
            }
        }
        for r in es.search(
                index="wazuh-alert*",
                body=body)["aggregations"]["appusecount"]["buckets"]:
            result.append({"label": r["key"], "data": r["doc_count"]})

        return result
Example #13
0
    def post(self):
        """모든 agent에 대해 agodate만큼의 Active에 대한내용을 전부 불러옴."""
        agents = getAgentData()
        daysago = request.json.get("date")
        result = []
        for agent in agents:
            body = {
                "size": 10000,
                "query": {
                    "bool": {
                        "must": [{
                            "match": {
                                "name": agent
                            }
                        }, {
                            "range": {
                                "timestamp": {
                                    "gte": "now-" + str(daysago) + "d/d",
                                    "lt": "now"
                                }
                            }
                        }]
                    }
                },
                "sort": [{
                    "timestamp": "desc"
                }]
            }
            data = []
            for r in es.search(index="wazuh-monitoring-*",
                               body=body)["hits"]["hits"]:
                time = r["_source"]["timestamp"]
                status = 0
                if r["_source"]["status"] == "active":
                    status = 1
                data.append({"time": time, "status": status})
            result.append({"agent": agent, "data": data})

        return result
Example #14
0
 def post(self):
     user = {
         "name": request.json.get("name"),
         "password": request.json.get("password"),
         "id": request.json.get("id"),
         "companyid": request.json.get("companyid"),
         "valid": request.json.get("valid"),
         "admin": request.json.get("admin"),
         "phone": request.json.get("phone"),
         "addr": request.json.get("addr")
     }
     doc = {
         "size": 10000,
         "query": {
             "match": {
                 "id": user["id"]
             }
         },
     }
     if es.search(index="userdb", body=doc)["hits"]["total"]["value"] > 0:
         return {"message": "이미 존재하는 아이디입니다."}
     else:
         print(es.index(index="userdb", doc_type="_doc", body=user))
     return {"message": "아이디 등록 완료"}
Example #15
0
 def post(self):
     """Network connection 정보 하루날짜-agent이름- image로 얻어옵니다."""
     daysago = request.json.get("date")
     result = []
     agents = []
     cnt = 0
     for a in userlist.get(self):
         agents.append(a["name"])
     print(daysago)
     print(agents)
     for d in range(0, int(daysago)):
         for a in agents:
             body = {
                 "size": 0,
                 "query": {
                     "bool": {
                         "must": [{
                             "match": {
                                 "data.win.system.eventID": 3
                             }
                         }, {
                             "match": {
                                 "agent.name": a
                             }
                         }, {
                             "range": {
                                 "@timestamp": {
                                     "gte": "now-" + str(d + 1) + "d/d",
                                     "lt": "now-" + str(d) + "d/d",
                                 }
                             }
                         }]
                     }
                 },
                 "aggs": {
                     "stations": {
                         "terms": {
                             "field": "data.win.eventdata.image"
                         }
                     }
                 }
             }
             for r in es.search(
                     index="wazuh-alert*",
                     body=body)["aggregations"]["stations"]["buckets"]:
                 cnt += 1
                 result.append({
                     "id":
                     cnt,
                     "time":
                     str(datetime.datetime.now() -
                         datetime.timedelta(days=(d)))[0:10],
                     "agent":
                     a,
                     "image":
                     r["key"],
                     "count":
                     r["doc_count"],
                     "date":
                     d
                 })
             # "query": "select DISTINCT data.win.eventdata.image,agent.name from wazuh-alert* where data.win.system.eventID='3'"
     return result
    def post(self):
        """ProcessCreate이벤트 정보를 다 받아옵니다!"""
        daysago = request.json.get("date")
        result = []
        body = {
            "size": 10000,
            "query": {
                "bool": {
                    "must": [
                        {
                            "match": {
                                "data.win.system.eventID": 1
                            }
                        },
                        {
                            "range": {
                                "@timestamp": {
                                    "gte": "now-"+str(daysago)+"d/d",
                                    "lt": "now"
                                }
                            }
                        }
                    ]
                }
            }
        }
        for cnt, r in enumerate(es.search(index="wazuh-alert*", body=body)["hits"]["hits"]):
            dic = {}
            eventdata = r["_source"]["data"]["win"]["eventdata"]
            dic["time"] = timefunc(r["_source"]["timestamp"])
            dic["agent"] = r["_source"]["agent"]["name"]

            if "originalFileName" in eventdata:
                dic["originalFileName"] = eventdata["originalFileName"]
            else:
                dic["originalFileName"] = "..."

            if "image" in eventdata:
                dic["image"] = eventdata["image"]
            else:
                dic["image"] = "..."

            if "hashes" in eventdata:
                dic["hashes"] = eventdata["hashes"]
            else:
                dic["hashes"] = "..."

            if "company" in eventdata:
                dic["company"] = eventdata["company"]
            else:
                dic["company"] = "..."

            if "description" in eventdata:
                dic["description"] = eventdata["description"]
            else:
                dic["description"] = "..."

            if "fileVersion" in eventdata:
                dic["fileVersion"] = eventdata["fileVersion"]
            else:
                dic["fileVersion"] = "..."

            if "integrityLevel" in eventdata:
                dic["integrityLevel"] = eventdata["integrityLevel"]
            else:
                dic["integrityLevel"] = "..."

            if "parentCommandLine" in eventdata:
                dic["parentCommandLine"] = eventdata["parentCommandLine"]
            else:
                dic["parentCommandLine"] = "..."

            if "parentImage" in eventdata:
                dic["parentImage"] = eventdata["parentImage"]
            else:
                dic["parentImage"] = "..."

            if "product" in eventdata:
                dic["product"] = eventdata["product"]
            else:
                dic["product"] = "..."

            if "processId" in eventdata:
                dic["processId"] = eventdata["processId"]
            else:
                dic["processId"] = "..."

            if "parentProcessId" in eventdata:
                dic["parentProcessId"] = eventdata["parentProcessId"]
            else:
                dic["parentProcessId"] = "..."
            dic["id"] = cnt
            result.append(dic)

        return result
Example #17
0
    def post(self):
        """agent-날짜 로 count해서 chart에 뿌릴 데이터를 로드합니다"""
        agents = []
        daysago = request.json.get("date")
        # get agentlist from wazuh
        wazuhlogin()
        for r in callWazuhApi("/agents")["data"]["affected_items"]:
            agents.append(r["name"])
        print(agents)
        result = []  # query result
        chartdata = []
        for a in agents:
            body = {
                "size": 10000,
                "query": {
                    "bool": {
                        "must": [{
                            "match": {
                                "data.win.system.eventID": 6
                            }
                        }, {
                            "match": {
                                "agent.name": a
                            }
                        }, {
                            "range": {
                                "@timestamp": {
                                    "gte": "now-" + str(daysago) + "d/d",
                                    "lt": "now"
                                }
                            }
                        }]
                    }
                },
                "aggs": {
                    "date_his": {
                        "date_histogram": {
                            "field": "timestamp",
                            "interval": "day"
                        }
                    }
                }
            }

            for r in es.search(
                    index="wazuh-alerts*",
                    body=body)["aggregations"]["date_his"]["buckets"]:
                time = r["key_as_string"][0:10]
                count = r["doc_count"]
                result.append({"agent": a, "time": time, "count": count})

        # panda로LineChart형태로 array를 바꿔줌
        dates = pd.date_range(datetime.date.today() -
                              datetime.timedelta(days=daysago),
                              periods=daysago + 1)
        # pandas로 만들어진 df에 정보입력
        df = pd.DataFrame(np.zeros((daysago + 1, len(agents)), int),
                          index=dates,
                          columns=agents)
        for r in result:
            df.at[r["time"], r["agent"]] += r["count"]

        # 반환해줄 chartdata array에 column값 넣기
        column = ["Date"]
        for a in df.columns:
            column.append(a)
        chartdata.append(column)

        # 반환해줄 chartdata에 날짜랑 해서 데이터 넣기
        for i, r in enumerate(np.array(df).tolist()):
            r.insert(0, df.index[i].strftime("%Y-%m-%d"))
            chartdata.append(r)
        return chartdata
Example #18
0
    def post(self):
        result = []
        daysago = request.json.get("date")
        body = {
            "size": 10000,
            "query": {
                "bool": {
                    "must": [{
                        "range": {
                            "@timestamp": {
                                "gte": "now-" + str(daysago) + "d/d",
                                "lt": "now"
                            }
                        }
                    }],
                    "should": [{
                        "regexp": {
                            "data.win.eventdata.image": {
                                "value": ".+chrome[.]exe",
                                "boost": 1
                            }
                        }
                    }, {
                        "regexp": {
                            "data.win.eventdata.image": {
                                "value": ".+edge[.]exe",
                                "boost": 1
                            }
                        }
                    }, {
                        "regexp": {
                            "data.win.eventdata.image": {
                                "value": ".+whale[.]exe",
                                "boost": 1
                            }
                        }
                    }],
                    "minimum_should_match":
                    1,
                    "boost":
                    1
                }
            },
            "sort": [{
                "timestamp": "desc"
            }],
            "aggs": {
                "appusecount": {
                    "terms": {
                        "field": "data.win.eventdata.queryName",
                        "size": 80
                    }
                }
            }
        }
        for r in es.search(
                index="wazuh-alert*",
                body=body)["aggregations"]["appusecount"]["buckets"]:
            result.append({"label": r["key"], "data": r["doc_count"]})

        return result