forked from cve-search/cve-search
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search_xmpp.py
executable file
·227 lines (197 loc) · 7.24 KB
/
search_xmpp.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
216
217
218
219
220
221
222
223
224
225
226
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Simple XMPP bot to query for the last entries in the CVE database
#
# current command supported is:
#
# last <max>
#
# You need to add the XMPP bot in your roster if you want to communicate
# with it.
#
# Software is free software released under the "Modified BSD license"
#
# Copyright (c) 2012 Alexandre Dulaunoy - [email protected]
import sys
import logging
import getpass
from optparse import OptionParser
import sleekxmpp
import pymongo
import re
import datetime
import json
# BSON MongoDB include ugly stuff that needs to be processed for standard JSON
from bson import json_util
if sys.version_info < (3, 0):
from sleekxmpp.util.misc_ops import setdefaultencoding
setdefaultencoding('utf8')
else:
raw_input = input
rankinglookup = True
connect = pymongo.Connection()
db = connect.cvedb
collection = db.cves
helpmessage = "\nlast <n> cve entries (output: JSON) \n"
helpmessage = helpmessage + "cvetweet <n> cve entries (output: Text) \n"
helpmessage = helpmessage + "search <query> full-text search on the summary field (output JSON)\n\n"
helpmessage = helpmessage + "For more info about cve-search: http://adulau.github.com/cve-search/"
def lookupcpe(cpeid = None):
e = db.cpe.find_one({'id': cpeid})
if e is None:
return cpeid
if 'id' in e:
return e['title']
def findranking(cpe = None, loosy = True):
if cpe is None:
return False
r = db.ranking
result = False
if loosy:
for x in cpe.split(':'):
if x is not '':
i = r.find_one({'cpe': {'$regex':x}})
if i is None:
continue
if 'rank' in i:
result = i['rank']
else:
i = r.find_one({'cpe': {'$regex':cpe}})
print (cpe)
if i is None:
return result
if 'rank' in i:
result = i['rank']
return result
def lastentries(limit = 5, namelookup=False):
entries = []
for item in collection.find({}).sort("last-modified",-1).limit(limit):
if not namelookup and rankinglookup is not True:
entries.append(item)
else:
if "vulnerable_configuration" in item:
vulconf = []
ranking = []
for conf in item['vulnerable_configuration']:
if namelookup:
vulconf.append(lookupcpe(cpeid=conf))
else:
vulconf.append(conf)
if rankinglookup:
rank = findranking(cpe=conf)
if rank and rank not in ranking:
ranking.append(rank)
item['vulnerable_configuration'] = vulconf
if rankinglookup:
item['ranking'] = ranking
entries.append(item)
return entries
def searchentries(query = None, namelookup=True, rankinglookup=True):
entries = []
sorttype = -1
print (query)
for item in collection.find({'summary': {'$regex' : re.compile(query, re.IGNORECASE)}}).sort("last-modified",sorttype):
if not namelookup:
entries.append(item)
else:
if "vulnerable_configuration" in item:
vulconf = []
ranking = []
for conf in item['vulnerable_configuration']:
vulconf.append(lookupcpe(cpeid=conf))
if rankinglookup:
rank = findranking(cpe=conf)
if rank and rank not in ranking:
ranking.append(rank)
item['vulnerable_configuration'] = vulconf
if rankinglookup:
item['ranking'] = ranking
entries.append(item)
return entries
def cvesearch(query="last", option=None):
if query=="last":
if option is None:
limit = 10
else:
limit = int(option)
return json.dumps(lastentries(limit=limit), sort_keys=True, indent=4, default=json_util.default)
elif query=="search":
return json.dumps(searchentries(query=option), sort_keys=True, indent=4, default=json_util.default)
elif query=="cvetweet":
text = " "
if option is None:
limit =10
else:
limit = int(option)
for t in lastentries(limit=limit):
text = text+str(t['id'])+" , "+str(t['summary'])+" "+" , ".join(t['references'])+"\n"
return text
else:
return False
class CVEBot(sleekxmpp.ClientXMPP):
def __init__(self, jid, password):
sleekxmpp.ClientXMPP.__init__(self, jid, password)
self.add_event_handler("session_start", self.start)
self.add_event_handler("message", self.message)
def start(self, event):
self.send_presence()
self.get_roster()
def message(self, msg):
if msg['type'] in ('chat', 'normal'):
q = []
q = (msg['body']).split()
if q[0] == "last":
try:
option=q[1]
except IndexError:
option=None
msg.reply(cvesearch(query="last", option=option)).send()
elif q[0] == "search":
q.pop(0)
option=' '.join(q)
msg.reply(cvesearch(query="search", option=option)).send()
elif q[0] == "cvetweet":
try:
option=q[1]
except IndexError:
option=None
msg.reply(cvesearch(query="cvetweet", option=option)).send()
else:
msg.reply(helpmessage).send()
if __name__ == '__main__':
optp = OptionParser()
optp.add_option('-q', '--quiet', help='set logging to ERROR',
action='store_const', dest='loglevel',
const=logging.ERROR, default=logging.INFO)
optp.add_option('-d', '--debug', help='set logging to DEBUG',
action='store_const', dest='loglevel',
const=logging.DEBUG, default=logging.INFO)
optp.add_option('-v', '--verbose', help='set logging to COMM',
action='store_const', dest='loglevel',
const=5, default=logging.INFO)
optp.add_option('-n', '--cpenamelookup', help='CPE name lookup',
action='store_false', dest='cpelookup',default=True)
optp.add_option("-j", "--jid", dest="jid",
help="JID to use")
optp.add_option("-p", "--password", dest="password",
help="password to use")
opts, args = optp.parse_args()
# Setup logging.
logging.basicConfig(level=opts.loglevel,
format='%(levelname)-8s %(message)s')
if opts.jid is None:
opts.jid = raw_input("Username: ")
if opts.password is None:
opts.password = getpass.getpass("Password: ")
# Basic skeleton based on CVEBot from sleekxmpp library
xmpp = CVEBot(opts.jid, opts.password)
xmpp.register_plugin('xep_0030') # Service Discovery
xmpp.register_plugin('xep_0004') # Data Forms
xmpp.register_plugin('xep_0060') # PubSub
xmpp.register_plugin('xep_0199') # XMPP Ping
if xmpp.connect():
xmpp.process(block=True)
print("Done")
else:
print("Unable to connect.")