-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathGithub-CVE-Listener.py
215 lines (204 loc) · 8.76 KB
/
Github-CVE-Listener.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#coding = utf-8
import urllib
import requests,re,time
import html
import json
import os
from base64 import b64encode
from nacl import encoding, public
from lxml import etree
import telegram
import asyncio
import time
gh_token=os.getenv('GH_TOKEN')
gh_repo=os.getenv('GH_REPO')
#The option of send method
# 1 --> Wechat
# 2 --> TGBot
option=os.getenv('option')
Auth=r'token '+gh_token
geturl=r'https://api.github.com/repos/'+gh_repo+r'/actions/secrets/public-key'
#有道翻译API
def translate(text):
url = 'https://aidemo.youdao.com/trans'
try:
data = {"q": text, "from": "auto", "to": "zh-CHS"}
resp = requests.post(url, data)
if resp is not None and resp.status_code == 200:
respJson = json.loads(resp.text)
if "translation" in respJson:
text ="\n".join('' + str(i) for i in respJson["translation"])
except:
print("[WARN] Error translating message!")
return text
def getpublickey(Auth,geturl):
headers={'Accept': 'application/vnd.github.v3+json','Authorization': Auth}
html = requests.get(geturl,headers=headers)
jsontxt = json.loads(html.text)
if 'key' in jsontxt:
print("[INFO] Get public key suceeded")
else:
print("[ERROR] Get public key failed :( Is secret GH_TOKEN set correctly? ")
public_key = jsontxt['key']
global key_id
key_id = jsontxt['key_id']
return public_key
#encrypt secret
def createsecret(public_key,secret_value):
public_key = public.PublicKey(public_key.encode("utf-8"), encoding.Base64Encoder())
sealed_box = public.SealedBox(public_key)
encrypted = sealed_box.encrypt(str(secret_value).encode("utf-8"))
return b64encode(encrypted).decode("utf-8")
#upload total_count as secret
def setsecret(encrypted_value,key_id,puturl):
headers={'Accept': 'application/vnd.github.v3+json','Authorization': Auth}
data_str=r'{"encrypted_value":"'+encrypted_value+r'",'+r'"key_id":"'+key_id+r'"}'
putstatus=requests.put(puturl,headers=headers,data=data_str)
if putstatus.status_code >= 300:
print("[ERROR] total_count upload failed!")
else:
print("[INFO] total_count upload suceeded!")
return putstatus
#get cve related repos
def getNews():
try:
api = "https://api.github.com/search/repositories?q=CVE-2023&sort=updated"
headers = {
"Authorization": "Bearer "+gh_token
}
req = requests.get(api, headers=headers).text
respJson = json.loads(req)
#print(respJson)
#cve_total_count=re.findall ('"total_count":*.{1,10}"incomplete_results"',req)[0][14:17]
cve_total_count=respJson["total_count"]
#cve_description=re.findall ('"description":*.{1,200}"fork"',req)[0].replace("\",\"fork\"",'').replace("\"description\":\"",'')
if respJson["items"][0]["description"]:
cve_description = respJson["items"][0]["description"]
else:
cve_description = "NULL!"
#cve_url=re.findall ('"svn_url":*.{1,200}"homepage"',req)[0].replace("\",\"homepage\"",'').replace("\"svn_url\":\"",'')
cve_url = respJson["items"][0]["svn_url"]
return cve_total_count,cve_description,cve_url
except Exception as e:
print ("[ERROR] ",e,"Can not connect to github :( ")
#check CVE_ID
def exist_cve(cve):
query_cve_url = "https://cve.mitre.org/cgi-bin/cvename.cgi?name=" + cve
github_headers = {'Authorization': Auth }
response = requests.get(query_cve_url, headers=github_headers, timeout=10)
html = etree.HTML(response.text)
#des = html.xpath('//*[@id="GeneratedTable"]/table//tr[4]/td/text()')[0].strip()
if re.findall('but the record does not exist', str(html), flags=re.IGNORECASE):
print("[WARN] CVE_ID doesn't exist, skipping...")
return 0
else:
return 1
#get vuln description from CVE
def get_cve_des(cve):
try:
time.sleep(3)
query_cve_url = "https://www.cve.org/api/?action=getCveById&cveId=" + cve
print(query_cve_url)
github_headers = {
'Authorization': Auth }
#response = requests.get(query_cve_url, headers=github_headers, timeout=10)
#html = etree.HTML(response.text)
#des = html.xpath('//*[@id="GeneratedTable"]/table//tr[4]/td/text()')[0].strip()
resp = requests.get(query_cve_url,headers=github_headers, timeout=10)
respJson = json.loads(resp.text)
des = respJson["containers"]["cna"]["descriptions"][0]["value"]
return des
except Exception as e:
err = "* **RESERVED** *"
print("[WARN] Get CVE description Failed, cause CVE refused")
return err
#get cve id
def getid(respJson):
cve_name = respJson["items"][0]["name"]
cve_id = re.findall('(CVE\-\d+\-\d+)', cve_name, flags=re.IGNORECASE)
des = respJson["items"][0]["description"]
if des:
cve_des = re.findall('(CVE\-\d+\-\d+)', des, flags=re.IGNORECASE)
# if empty or have README only
if(int(respJson["items"][0]["size"]) == 0):
print("[WARN] Repo is empty or only contains readme...Skipping...")
exit(0)
readme = "https://raw.githubusercontent.com/" + str(respJson["items"][0]["full_name"]) + "/main/README.md"
readme_content = requests.get(readme).text
if str(cve_id) == "[]":
cve_id = cve_id + re.findall('(CVE\-\d+\-\d+)', readme_content, flags=re.IGNORECASE)
if str(cve_id) != "[]":
if("cve" in str(cve_id[0])):
return re.sub("cve", "CVE", str(cve_id[0]))
return cve_id[0]
else:
print("[WARN] Get CVE ID Failed, Does the repo contain the correct info?")
exit(0)
#Send TG
async def TG(cve_des):
text = r'喵~~ Senpai! 有新的CVE更新送达!'
msg ="CVE相关项目总数: " + str(getNews()[0]) + "\r\n" +"GitHub项目介绍: " + getNews()[1]+ "\r\n" +"("+translate(getNews()[1])+")"+"\r\n"+ "链接: " + getNews()[2] + "\r\n" + "该CVE编号的详情: " + cve_des +"\r\n"+"("+translate(cve_des)+")"+"\r\n" + "(⁄ ⁄•⁄ω⁄•⁄ ⁄)"
#msg ="repo number: " + str(getNews()[0]) + "\r\n" +"GitHub description: " + getNews()[1]+ "\r\n" + "Link: " + getNews()[2] + "\r\n" + "CVE Vulnerability Description: " + cve_des + "\r\n" + "(⁄ ⁄•⁄ω⁄•⁄ ⁄)"
#msg = translate(msg)
tg_token = os.getenv('TG_TOKEN')
tg_chat_id = os.getenv('TG_CHAT_ID')
bot = telegram.Bot(token=tg_token)
await bot.send_message(chat_id=tg_chat_id, text=text + "\r\n" + msg)
#Send Wechat
def Wechat(cve_des):
#The title of the message
text = r'喵~~ Senpai! 有新的CVE更新送达!'
#Process SCKEYs
sckey = os.getenv('SCKEY')
sckeys = sckey.split(",")
#The contents of the message
msg ="\n"+"* CVE相关项目总数: " + str(getNews()[0]) + "\n" +"* GitHub项目介绍: " + getNews()[1]+"\n"+"> ("+translate(getNews()[1])+")"+"\n"+ "* 链接: " + getNews()[2] + "\n" + "* 该CVE编号的详情: " + cve_des +"\n"+"> ("+translate(cve_des)+")"+"\n"+"\n"+ "(⁄ ⁄•⁄ω⁄•⁄ ⁄)"
#msg = translate(msg)
for key in sckeys:
uri = 'https://sc.ftqq.com/'+ key +'.send?text={}&desp={}'.format(text, msg)
send = requests.get(uri)
#Send Message
def sendNews(total_count):
try:
api = "https://api.github.com/search/repositories?q=CVE-2023&sort=updated"
req = requests.get(api).text
respJson = json.loads(req)
repo_name = respJson["items"][0]["name"]
if int(total_count) < getNews()[0]:
cve_id = getid(respJson)
print("[INFO] CVE ID: ", cve_id)
#Description from CVE
if exist_cve(cve_id):
cve_des = get_cve_des(cve_id)
else:
exit(0)
if int(option) == 1:
print("[INFO] CVE updates found! Sending Wechat!")
Wechat(cve_des)
elif int(option) == 2:
print("[INFO] CVE updates found! Sending TG!")
asyncio.run(TG(cve_des))
elif int(option) == 3:
print("[INFO] CVE updates found! Sending TG and Wechat!")
asyncio.run(TG(cve_des))
Wechat(cve_des)
print(getNews())
time.sleep(5)
total_count = getNews()[0]
return total_count
elif int(total_count) > getNews()[0]:
print("[WARN] Some repos are deleted!")
total_count = getNews()[0]
return total_count
else:
print("[INFO] No CVE updates found! Bye!")
exit()
except Exception as e:
raise e
if __name__ == '__main__':
total_count = os.getenv('total_count')
puturl=r'https://api.github.com/repos/'+gh_repo+r'/actions/secrets/TOTAL_COUNT'
key_id='qwq'
encrypted_value=createsecret(getpublickey(Auth,geturl),sendNews(total_count))
setsecret(encrypted_value,key_id,puturl)
#sendNews()