forked from Summer-Geeks/code_vul_check
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chk.py
1628 lines (1399 loc) · 62.9 KB
/
chk.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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
from streamlit.components.v1 import html
import base64
import requests
import re
from pytube import YouTube
import os
import stat
import subprocess
import random
import urllib.request
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import spacy
import requests
import numpy as np
import pandas as pd
import shutil
from pyppeteer import launch
from generate_mermaid_svg import generate_mermaid_svg
from langchain.document_loaders import WebBaseLoader, GitLoader
from langchain.text_splitter import CharacterTextSplitter
from langchain.tools import BaseTool
from langchain.chat_models import ChatOpenAI
from langchain.llms import OpenAI
from langchain.agents import initialize_agent, AgentType
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores.chroma import Chroma
from langchain.chains import ConversationalRetrievalChain
from langchain.agents import AgentOutputParser
from langchain import PromptTemplate
from langchain.output_parsers import PydanticOutputParser, OutputFixingParser
from langchain.schema import AgentAction, AgentFinish, OutputParserException
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score
from sklearn.preprocessing import LabelEncoder
from sklearn.svm import SVC
from typing import List, Union, Optional, Type
from pydantic import root_validator, BaseModel, Field, ValidationError, validator
import openai
from langchain.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field, validator
from typing import List
import base64
import tempfile
import re
import time
import os
import subprocess
import json
OPENAI_API_KEY = ["LIST_OF_YOUR_OPENAI_API_KEYS"]
GOOGLE_API_KEY = "YOUR_GOOGLE_API_KEY"
GOOGLE_CX = "YOUR_SEARCH_ENGINE_CX"
os.environ["SERPER_API_KEY"] = "YOUR_SERPER_API_KEY"
os.environ["HUGGINGFACEHUB_API_TOKEN"] = "YOUR_HUGGINGFACE_KEY"
import nltk
nltk.download('stopwords')
nltk.download('wordnet')
nltk.download("punkt")
from sumy.parsers.html import HtmlParser
from sumy.nlp.tokenizers import Tokenizer
from sumy.summarizers.luhn import LuhnSummarizer
from langchain.embeddings import HuggingFaceEmbeddings
from sentence_transformers import SentenceTransformer
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from langchain import HuggingFaceHub
llm = OpenAI(openai_api_key=OPENAI_API_KEY[random.randint(0, len(OPENAI_API_KEY)-1)])
nlp = spacy.load("en_core_web_md")
# Set custom Streamlit theme
st.set_page_config(
page_title="Chat with AI Bot",
page_icon="🤖",
layout="wide",
initial_sidebar_state="expanded",
)
def onerror(func, path, exc_info):
if isinstance(exc_info[1], FileNotFoundError):
return
if not os.access(path, os.W_OK):
os.chmod(path, stat.S_IWUSR)
func(path)
else:
raise
class CodeStore:
def __init__(
_self,
openai_api_key: str,
github_url: str,
local_path: str,
branch: str
):
_self.github_url = github_url
_self.local_path = local_path
_self.branch = branch
_self.OPENAI_API_KEY = openai_api_key
_self.documents = None
last_slash_index = github_url.rfind("/")
last_suffix_index = github_url.rfind(".git")
if last_suffix_index < 0:
last_suffix_index = len(github_url)
_self.persist_directory = github_url[last_slash_index+1 : last_suffix_index]
_self.embedding_function = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
_self.code_store = None
_self.question_answer = None
_self.chat_history = []
# @st.cache_data
def generate_documents(_self):
_self.clear_files()
loader = GitLoader(
clone_url = _self.github_url,
repo_path = _self.local_path,
branch = _self.branch
)
docs = loader.load()
text_splitter = CharacterTextSplitter(
chunk_size = 1500,
chunk_overlap = 0
)
_self.documents = text_splitter.split_documents(docs)
print(_self.documents)
# documents are generated
# @st.cache_data
def create_vector_store(_self):
_self.code_store = Chroma.from_documents(
documents=_self.documents,
embedding=_self.embedding_function,
persist_directory=_self.persist_directory,
)
prompt = PromptTemplate.from_template(
"""
Question: {question}
Instructions: \n
Respond to the human as helpfully and accurately as possible in 100 words or less. You can look into the github code repository, YOU HAVE BEEN GIVEN ACCESS TO ALL FILES.
Output Format must be:
Brief Explanation : <Give Brief Explanation here> \n
Code: <give the relevant code here>\n
Example:
OUTPUT:
BRIEF EXPLANATION: This folder contains ...
Code:
def function_Get():
pass
OUTPUT:
BRIEF EXPLANATION: The function present in the code ...
Code:
def myfunction():
pass
OUTPUT:
BRIEF EXPLANATION: This Algorithm is used to ...
Code:
def algorithm():
pass
"""
)
# prompt = PromptTemplate.from_template(
# "Question: {question}"
# "Instructions: \n"
# "Output Format must be:"
# "Explanation : <Give Explanation here> \n"
# "Code: <give the relevant code here>\n"
# "Summary: <give summary here>"
# )
if _self.code_store:
print("Code Store exists")
_self.code_store.persist()
_self.question_answer = ConversationalRetrievalChain.from_llm(
ChatOpenAI(
openai_api_key = _self.OPENAI_API_KEY,
temperature = 0
),
_self.code_store.as_retriever(),
return_source_documents = True,
condense_question_prompt=prompt
# get_chat_history = _self.get_chat_history
)
@st.cache_data
def search_code(_self, query: str):
# Preprocess and summarize the input query
stop_words = set(stopwords.words('english'))
word_tokens = word_tokenize(query)
filtered_query = [w for w in word_tokens if not w in stop_words]
summarized_query = ' '.join(filtered_query)
# Pass the summarized query to the question_answer method
_self.chat_history = []
result = _self.question_answer({
"question": summarized_query,
"chat_history": _self.chat_history
})
_self.chat_history.append((summarized_query, result["answer"]))
return result
def clear_files(_self):
try:
# subprocess.run(["cmd", "/c", "rmdir", "/s", "/q", _self.local_path], check=True)
# subprocess.run(["cmd", "/c", "rmdir", "/s", "/q", _self.persist_directory], check=True)
shutil.rmtree(_self.local_path, onerror=onerror)
shutil.rmtree(_self.persist_directory, onerror=onerror)
return True
except OSError as e:
print(f"Error: {e.filename} - {e.strerror}.")
# except subprocess.CalledProcessError as e:
# print(f"Failed to remove Code Store or Cloned Repository: {e}")
# return False
def clear_history(_self):
_self.chat_history = []
def reinitialize(_self, openai_api_key: str, github_url: str, local_path: str, branch: str):
_self.github_url = github_url
_self.local_path = local_path
_self.branch = branch
_self.OPENAI_API_KEY = openai_api_key
_self.documents = None
last_slash_index = github_url.rfind("/")
last_suffix_index = github_url.rfind(".git")
if last_suffix_index < 0:
last_suffix_index = len(github_url)
_self.persist_directory = github_url[last_slash_index+1 : last_suffix_index]
_self.embedding_function = OpenAIEmbeddings(openai_api_key = openai_api_key)
_self.code_store = None
_self.question_answer = None
_self.chat_history = []
@st.cache_data
def _cr(github_url, git_branch):
cr = CodeStore(
openai_api_key=OPENAI_API_KEY[random.randint(0, len(OPENAI_API_KEY)-1)],
github_url=github_url,
local_path="./repo",
branch=git_branch)
return cr
class UseCaseGenerator:
def __init__(_self, api_key, description, diagram):
openai.api_key = api_key
_self.description = description
_self.diagram = diagram
# @st.cache_data
def generate_use_cases(_self, _description, diagram):
prompt = f"""Generate structured and well-defined use cases for the given system description, and then generate mermaid code for the given diagram type.
System Description: {_description}
Use Case 1:
Use Case 2:
Use Case 3:
Use Case n:
Diagram Type: {diagram}
Mermaid Code:
"""
completions = openai.Completion.create(
engine="text-davinci-002",
prompt=prompt,
max_tokens=1024,
n=1,
stop=None,
temperature=0.7,
)
message = completions.choices[0].text.strip()
return message
class VulnerabilityStore:
def __init__(_self, openai_api_key:list):
_self.OPENAI_API_KEY = openai_api_key
_self.documents = []
_self.summarizer_llm = HuggingFaceHub(
repo_id="sshleifer/distilbart-cnn-12-6", model_kwargs={"temperature": 0.2, "max_length": 10000}
)
_self.similarity_model = SentenceTransformer('paraphrase-distilroberta-base-v2')
_self.embedding_function = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
_self.start_urls = [
"https://owasp.org/Top10/A01_2021-Broken_Access_Control",
"https://owasp.org/Top10/A02_2021-Cryptographic_Failures",
"https://owasp.org/Top10/A03_2021-Injection",
"https://owasp.org/Top10/A04_2021-Insecure_Design",
"https://owasp.org/Top10/A05_2021-Security_Misconfiguration",
"https://owasp.org/Top10/A06_2021-Vulnerable_and_Outdated_Components",
"https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures",
"https://owasp.org/Top10/A08_2021-Software_and_Data_Integrity_Failures",
"https://owasp.org/Top10/A09_2021-Security_Logging_and_Monitoring_Failures",
"https://owasp.org/Top10/A10_2021-Server-Side_Request_Forgery_%28SSRF%29"
]
_self.labels = []
_self.persist_directories = []
_self.metadata = []
_self.stores: list[Chroma] = []
_self.user_agents = [
"Mozilla/5.0 (Windows NT 10.4; Win64; x64) Gecko/20130401 Firefox/60.7",
"Mozilla/5.0 (Linux; Linux i676 ; en-US) AppleWebKit/602.37 (KHTML, like Gecko) Chrome/53.0.3188.182 Safari/533",
"Mozilla/5.0 (Android; Android 6.0.1; SM-G928S Build/MDB08I) AppleWebKit/536.43 (KHTML, like Gecko) Chrome/53.0.1961.231 Mobile Safari/602.4",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_1_7) Gecko/20100101 Firefox/48.4",
"Mozilla/5.0 (Windows NT 10.1; Win64; x64) AppleWebKit/602.6 (KHTML, like Gecko) Chrome/49.0.2764.174 Safari/603",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 9_8_7) Gecko/20130401 Firefox/59.7",
"Mozilla/5.0 (Linux; U; Android 5.0; LG-D332 Build/LRX22G) AppleWebKit/602.2 (KHTML, like Gecko) Chrome/54.0.2014.306 Mobile Safari/600.5",
"Mozilla/5.0 (Android; Android 5.0.2; HTC 80:number1-2w Build/LRX22G) AppleWebKit/600.31 (KHTML, like Gecko) Chrome/54.0.3164.157 Mobile Safari/603.5",
"Mozilla/5.0 (Linux; Android 7.1; Nexus 8P Build/NPD90G) AppleWebKit/601.15 (KHTML, like Gecko) Chrome/47.0.3854.218 Mobile Safari/600.6",
"Mozilla/5.0 (Android; Android 5.1; SM-G928L Build/LRX22G) AppleWebKit/602.47 (KHTML, like Gecko) Chrome/48.0.1094.253 Mobile Safari/537.6",
]
_self.question_answer = []
def get_links_from_url(_self, url: str):
req = urllib.request.Request(url, headers={
"User-Agent": _self.user_agents[random.randint(0, 9)]
})
html_page = urllib.request.urlopen(req)
soup = BeautifulSoup(html_page, 'html.parser')
links = []
for link in soup.findAll('a'):
links.append(urljoin(url, link.get('href')))
return links
@st.cache_data
def expand_start_urls(_self):
to = len(_self.start_urls)
for l in range(to):
try:
if len(_self.start_urls) > 0:
break
newlinks = _self.get_links_from_url(url = _self.start_urls[l])
checked_links = []
for url in newlinks:
if len(url) < 10:
continue
if url[-1] == "/":
url = url[:-1]
checked_links.append(url)
checked_links = list(set(checked_links))
# for i in range(len(checked_links)):
# _self.labels.append("vulnerability_related")
_self.start_urls.extend(checked_links)
# if len(_self.labels) != len(_self.start_urls):
# print("Gadbad :)")
except Exception:
# print("URL : ", _self.start_urls[l], "Error: ", e)
continue
@st.cache_data
def get_documents(_self):
for url in _self.start_urls:
try:
loader = WebBaseLoader(web_path=url)
loader.default_parser = "html.parser"
doc = loader.load()
parser = HtmlParser.from_url(url, Tokenizer("english"))
summarizer = LuhnSummarizer()
summary = str(summarizer(parser.document, sentences_count=4))
summary = summary.replace("<", "").replace(">", "").replace("Sentence:", "")
for d in doc:
if d.metadata is None:
d.metadata = {}
d.metadata["summary"] = summary.replace("<", "").replace(">", "").replace("Sentence:", "")
_self.documents.append(doc)
_self.metadata.append(summary)
except Exception as e:
print("URL : ", url, "Error : ", e)
continue
@staticmethod
def clear_vector_stores():
try:
subprocess.run(["cmd", "/c", "rmdir", "/s", "/q", "vectorstores"])
print("Removed vectorstores")
except subprocess.CalledProcessError:
print("Failure")
@st.cache_data
def create_vector_stores(_self):
# _self.clear_vector_stores()
l = len(_self.documents)
p = 0
for i in range(l):
try:
_self.stores.append(
Chroma.from_documents(
documents=_self.documents[i],
embedding=_self.embedding_function,
persist_directory=_self.persist_directories[i]
)
)
except Exception as e:
print(e, _self.documents[i])
p = p+1
continue
_self.stores[i-p].persist()
prompt = PromptTemplate.from_template(
"Question: {question}"
"Instructions: \n"
"Output Format must be:"
"Explanation : <Give Explanation here> \n"
"Code: <give the relevant code here>\n"
"Summary: <give summary here>"
)
# make qa
_self.question_answer.append(ConversationalRetrievalChain.from_llm(
ChatOpenAI(
openai_api_key = _self.OPENAI_API_KEY[random.randint(0,len(_self.OPENAI_API_KEY)-1)],
temperature = 0
),
retriever=(_self.stores[i-p]).as_retriever(search_kwargs={"k": 1}), condense_question_prompt = prompt
))
@st.cache_data
def add_url(_self, url: str, label: str):
loader = WebBaseLoader(web_path=url)
loader.default_parser = "html.parser"
doc = loader.load()
if len(doc) == 0:
return
parser = HtmlParser.from_url(url, Tokenizer("english"))
## LUHN method
summarizer = LuhnSummarizer()
summary = str(summarizer(parser.document, sentences_count=4))
summary = summary.replace("<", "").replace(">", "").replace("Sentence:", "")
for d in doc:
try:
if d.metadata is None or d.metadata == {}:
d.metadata = {"error": "metadata was null"}
d.metadata["summary"] = summary.replace("<", "").replace(">", "").replace("Sentence:", "")
d.metadata["url"] = url
except Exception:
pass
# print(e)
# print(d)
topic_exists = False
for i in range(len(_self.metadata)):
qe = _self.similarity_model.encode(doc[0].metadata["summary"])
me = _self.similarity_model.encode(_self.metadata[i])
score = qe.dot(me) / (np.linalg.norm(qe) * np.linalg.norm(me))
if score > 0.6:
topic_exists = True
print("merged")
try:
for d in doc:
_self.stores[i].add_documents(d)
_self.metadata[i] += " " + summary
except Exception:
pass
# print(score, i, _self.persist_directories[i])
break
if not topic_exists:
per = ""
if url[-1] == "/":
url = url[:-1]
slash = url.rfind("/")
if slash < 0:
ext = url.rfind(".")
per = "./vectorstores/" + url[ext+1:]
if slash > 0:
per = "./vectorstores/" + url[slash+1:]
_self.stores.append(
Chroma.from_documents(
documents=doc,
embedding=_self.embedding_function,
persist_directory=per
)
)
_self.labels.append(label)
_self.stores[-1].persist()
_self.documents.append(doc)
_self.metadata.append(summary)
_self.persist_directories.append(per)
prompt = PromptTemplate.from_template(
"Question: {question}"
"Instructions: \n"
"Output Format must be:"
"Explanation : <Give Explanation here> \n"
"Code: <give the relevant code here>\n"
"Summary: <give summary here>"
)
# make qa
_self.question_answer.append(ConversationalRetrievalChain.from_llm(
llm = ChatOpenAI(temperature = 0.2, openai_api_key = _self.OPENAI_API_KEY[random.randint(0,len(_self.OPENAI_API_KEY)-1)]),
retriever=_self.stores[-1].as_retriever(search_kwargs={"k": 1}),
max_tokens_limit=4000, condense_question_prompt = prompt
))
@st.cache_data
def run_vul(_self):
for url in _self.start_urls:
try:
_self.add_url(url = url, label="vulnerability_related")
except Exception:
# print("Error in URL : ", url)
# print("Skip due to error : ", e)
continue
# print(len(_self.metadata), len(_self.documents), len(_self.stores), len(_self.persist_directories), len(_self.question_answer))
print("URL : ", url)
print("Store : ", _self.persist_directories[-1])
# print("Metadata : ", _self.metadata[-1])
@st.cache_data
def search(_self, query:str, label:str):
similarity_scores = []
l = len(_self.metadata)
for i in range(l):
# if store or metadata is not labelled related to the label mentioned then skip
if _self.labels[i] != label:
similarity_scores.append(0)
continue
qe = _self.similarity_model.encode(_self.metadata[i])
me = _self.similarity_model.encode(query)
score = qe.dot(me) / (np.linalg.norm(qe) * np.linalg.norm(me))
similarity_scores.append(score)
solutions = []
for i in range(l):
if similarity_scores[i] > 0.5:
solutions.append(i)
outputs = []
chat_history = []
if len(solutions) == 0:
url = "https://www.googleapis.com/customsearch/v1"
params = {
"key": "YOUR_GOOGLE_API_KEY",
"cx": "YOUR_SEARCH_ENGINE_CX_KEY",
"q": query,
"num": 10,
"fields": "items(link)"
}
response = requests.get(url, params=params)
if response.status_code == 200:
results = response.json()["items"]
urls = [result["link"] for result in results]
text_urls = []
for url in urls:
try:
response = requests.get(url)
if response.status_code == 200 and 'text' in response.headers['Content-Type']:
text_urls.append(url)
elif response.status_code == 200 and 'text' in response.content.decode('utf-8'):
text_urls.append(url)
except:
pass
stprev = len(_self.stores)
print(text_urls)
for i in text_urls:
try:
_self.add_url(i, label)
_self.start_urls.append(i)
except Exception as e:
print("URL", i, e)
stnext = len(_self.stores)
# label new stores generated with the label provided
# for i in range(stnext - stprev):
# _self.labels.append(label)
try:
l = len(_self.question_answer)
for i in range(l- (stnext - stprev), l):
qa = _self.question_answer[i]
result = qa({"question": query, "chat_history": []})
outputs.append(result)
except Exception:
pass
# print("Gadbad", e, "\n", "LEngth : ", len(_self.start_urls), "QA len : ", len(_self.question_answer), " sol len ", len(solutions))
else:
outputs.append("No search results found.")
else:
try:
for i in solutions:
qa = _self.question_answer[i]
result = qa({"question": query, "chat_history": []})
outputs.append(result)
chat_history.append(result)
except Exception:
pass
# print(e)
return outputs
vul = VulnerabilityStore(openai_api_key=OPENAI_API_KEY)
# vul.clear_vector_stores()
vul.expand_start_urls()
# print(len(vul.start_urls))
vul.run_vul()
class GeneralStore:
def __init__(self, openai_api_key:list):
self.OPENAI_API_KEY = openai_api_key
self.documents = []
self.summarizer_llm = HuggingFaceHub(
repo_id="sshleifer/distilbart-cnn-12-6", model_kwargs={"temperature": 0, "max_length": 10000}
)
self.similarity_model = SentenceTransformer('paraphrase-distilroberta-base-v2')
self.embedding_function = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
self.start_urls = [
# "https://owasp.org/Top10/A01_2021-Broken_Access_Control",
# "https://owasp.org/Top10/A02_2021-Cryptographic_Failures",
# "https://owasp.org/Top10/A03_2021-Injection",
# "https://owasp.org/Top10/A04_2021-Insecure_Design",
# "https://owasp.org/Top10/A05_2021-Security_Misconfiguration",
# "https://owasp.org/Top10/A06_2021-Vulnerable_and_Outdated_Components",
# "https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures",
# "https://owasp.org/Top10/A08_2021-Software_and_Data_Integrity_Failures",
# "https://owasp.org/Top10/A09_2021-Security_Logging_and_Monitoring_Failures",
# "https://owasp.org/Top10/A10_2021-Server-Side_Request_Forgery_%28SSRF%29"
]
self.labels = []
self.persist_directories = []
self.metadata = []
self.stores: list[Chroma] = []
self.user_agents = [
"Mozilla/5.0 (Windows NT 10.4; Win64; x64) Gecko/20130401 Firefox/60.7",
"Mozilla/5.0 (Linux; Linux i676 ; en-US) AppleWebKit/602.37 (KHTML, like Gecko) Chrome/53.0.3188.182 Safari/533",
"Mozilla/5.0 (Android; Android 6.0.1; SM-G928S Build/MDB08I) AppleWebKit/536.43 (KHTML, like Gecko) Chrome/53.0.1961.231 Mobile Safari/602.4",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_1_7) Gecko/20100101 Firefox/48.4",
"Mozilla/5.0 (Windows NT 10.1; Win64; x64) AppleWebKit/602.6 (KHTML, like Gecko) Chrome/49.0.2764.174 Safari/603",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 9_8_7) Gecko/20130401 Firefox/59.7",
"Mozilla/5.0 (Linux; U; Android 5.0; LG-D332 Build/LRX22G) AppleWebKit/602.2 (KHTML, like Gecko) Chrome/54.0.2014.306 Mobile Safari/600.5",
"Mozilla/5.0 (Android; Android 5.0.2; HTC 80:number1-2w Build/LRX22G) AppleWebKit/600.31 (KHTML, like Gecko) Chrome/54.0.3164.157 Mobile Safari/603.5",
"Mozilla/5.0 (Linux; Android 7.1; Nexus 8P Build/NPD90G) AppleWebKit/601.15 (KHTML, like Gecko) Chrome/47.0.3854.218 Mobile Safari/600.6",
"Mozilla/5.0 (Android; Android 5.1; SM-G928L Build/LRX22G) AppleWebKit/602.47 (KHTML, like Gecko) Chrome/48.0.1094.253 Mobile Safari/537.6",
]
self.question_answer = []
def get_links_from_url(self, url: str):
req = urllib.request.Request(url, headers={
"User-Agent": self.user_agents[random.randint(0, 9)]
})
html_page = urllib.request.urlopen(req)
soup = BeautifulSoup(html_page, 'html.parser')
links = []
for link in soup.findAll('a'):
links.append(urljoin(url, link.get('href')))
return links
def expand_start_urls(self):
to = len(self.start_urls)
for l in range(to):
try:
if len(self.start_urls) > 0:
break
newlinks = self.get_links_from_url(url = self.start_urls[l])
checked_links = []
for url in newlinks:
if len(url) < 10:
continue
if url[-1] == "/":
url = url[:-1]
checked_links.append(url)
checked_links = list(set(checked_links))
# for i in range(len(checked_links)):
# self.labels.append("vulnerability_related")
self.start_urls.extend(checked_links)
# if len(self.labels) != len(self.start_urls):
# print("Gadbad :)")
except Exception:
# print("URL : ", self.start_urls[l], "Error: ", e)
continue
@st.cache_data
def get_documents(self):
for url in self.start_urls:
try:
loader = WebBaseLoader(web_path=url)
loader.default_parser = "html.parser"
doc = loader.load()
parser = HtmlParser.from_url(url, Tokenizer("english"))
summarizer = LuhnSummarizer()
summary = str(summarizer(parser.document, sentences_count=4))
summary = summary.replace("<", "").replace(">", "").replace("Sentence:", "")
for d in doc:
if d.metadata is None:
d.metadata = {}
d.metadata["summary"] = summary.replace("<", "").replace(">", "").replace("Sentence:", "")
self.documents.append(doc)
self.metadata.append(summary)
except Exception as e:
print("URL : ", url, "Error : ", e)
continue
@staticmethod
def clear_vector_stores():
try:
subprocess.run(["rm", "-r", "./generalstore"])
print("Removed generalstore")
except subprocess.CalledProcessError:
print("Failure")
@st.cache_data
def create_vector_stores(self):
# self.clear_vector_stores()
l = len(self.documents)
p = 0
for i in range(l):
try:
self.stores.append(
Chroma.from_documents(
documents=self.documents[i],
embedding=self.embedding_function,
persist_directory=self.persist_directories[i]
)
)
except Exception as e:
print(e, self.documents[i])
p = p+1
continue
self.stores[i-p].persist()
prompt = PromptTemplate.from_template(
"Question: {question}"
"Instructions: \n"
"Output Format must be:"
"Explanation : <Give Explanation here> \n"
"Code: <give the relevant code here>\n"
"Summary: <give summary here>"
)
# make qa
self.question_answer.append(ConversationalRetrievalChain.from_llm(
ChatOpenAI(
openai_api_key = self.OPENAI_API_KEY[random.randint(0,len(self.OPENAI_API_KEY)-1)],
temperature = 0
),
retriever=(self.stores[i-p]).as_retriever(search_kwargs={"k": 1}), condense_question_prompt = prompt
))
@st.cache_data
def add_url(self, url: str, label: str):
loader = WebBaseLoader(web_path=url)
loader.default_parser = "html.parser"
doc = loader.load()
if len(doc) == 0:
return
parser = HtmlParser.from_url(url, Tokenizer("english"))
## LUHN method
summarizer = LuhnSummarizer()
summary = str(summarizer(parser.document, sentences_count=4))
summary = summary.replace("<", "").replace(">", "").replace("Sentence:", "")
for d in doc:
try:
if d.metadata is None or d.metadata == {}:
d.metadata = {"error": "metadata was null"}
d.metadata["summary"] = summary.replace("<", "").replace(">", "").replace("Sentence:", "")
d.metadata["url"] = url
except Exception:
pass
# print(e)
# print(d)
topic_exists = False
for i in range(len(self.metadata)):
qe = self.similarity_model.encode(doc[0].metadata["summary"])
me = self.similarity_model.encode(self.metadata[i])
score = qe.dot(me) / (np.linalg.norm(qe) * np.linalg.norm(me))
if score > 0.6:
topic_exists = True
print("merged")
try:
for d in doc:
self.stores[i].add_documents(d)
self.metadata[i] += " " + summary
except Exception:
pass
# print(score, i, self.persist_directories[i])
break
if not topic_exists:
per = ""
if url[-1] == "/":
url = url[:-1]
slash = url.rfind("/")
if slash < 0:
ext = url.rfind(".")
per = "./generalstore/" + url[ext+1:]
if slash > 0:
per = "./generalstore/" + url[slash+1:]
self.stores.append(
Chroma.from_documents(
documents=doc,
embedding=self.embedding_function,
persist_directory=per
)
)
self.labels.append(label)
self.stores[-1].persist()
self.documents.append(doc)
self.metadata.append(summary)
self.persist_directories.append(per)
prompt = PromptTemplate.from_template(
"Question: {question}"
"Instructions: \n"
"Output Format must be:\n"
"Explanation : <Give Explanation here> \n"
"Code: <give the relevant code here>\n"
"Summary: <give summary here>\n"
""
)
# make qa
self.question_answer.append(ConversationalRetrievalChain.from_llm(
llm = ChatOpenAI(temperature = 0, openai_api_key = self.OPENAI_API_KEY[random.randint(0,len(self.OPENAI_API_KEY)-1)]),
retriever=self.stores[-1].as_retriever(search_kwargs={"k": 1}),
max_tokens_limit=4000, condense_question_prompt = prompt
))
def run_vul(self):
for url in self.start_urls:
try:
self.add_url(url = url, label="vulnerability_related")
except Exception:
# print("Error in URL : ", url)
# print("Skip due to error : ", e)
continue
# print(len(self.metadata), len(self.documents), len(self.stores), len(self.persist_directories), len(self.question_answer))
print("URL : ", url)
print("Store : ", self.persist_directories[-1])
# print("Metadata : ", self.metadata[-1])
def search(self, query:str, label:str):
similarity_scores = []
l = len(self.metadata)
for i in range(l):
# if store or metadata is not labelled related to the label mentioned then skip
if self.labels[i] != label:
similarity_scores.append(0)
continue
qe = self.similarity_model.encode(self.metadata[i])
me = self.similarity_model.encode(query)
score = qe.dot(me) / (np.linalg.norm(qe) * np.linalg.norm(me))
similarity_scores.append(score)
solutions = []
for i in range(l):
if similarity_scores[i] > 0.5:
solutions.append(i)
outputs = []
chat_history = []
if len(solutions) == 0:
url = "https://www.googleapis.com/customsearch/v1"
params = {
"key": "YOUR_GOOGLE_API_KEY",
"cx": "YOUR_SEARCH_ENGINE_CX_KEY",
"q": query,
"num": 10,
"fields": "items(link)"
}
response = requests.get(url, params=params)
if response.status_code == 200:
results = response.json()["items"]
urls = [result["link"] for result in results]
text_urls = []
for url in urls:
try:
response = requests.get(url)
if response.status_code == 200 and 'text' in response.headers['Content-Type']:
text_urls.append(url)
elif response.status_code == 200 and 'text' in response.content.decode('utf-8'):
text_urls.append(url)
except:
pass
stprev = len(self.stores)
print(text_urls)
for i in text_urls:
try:
self.add_url(i, label)
self.start_urls.append(i)
except Exception as e:
print("URL", i, e)
stnext = len(self.stores)
# label new stores generated with the label provided
# for i in range(stnext - stprev):
# self.labels.append(label)
try:
l = len(self.question_answer)
for i in range(l- (stnext - stprev), l):
qa = self.question_answer[i]
result = qa({"question": query, "chat_history": []})
outputs.append(result)
except Exception:
pass
else:
outputs.append("No search results found.")
else:
try:
for i in solutions:
qa = self.question_answer[i]
result = qa({"question": query, "chat_history": []})
outputs.append(result)
chat_history.append(result)
except Exception:
pass
return outputs
gs = GeneralStore(openai_api_key=OPENAI_API_KEY)
"""# Classifier"""
dataset = None
if dataset not in st.session_state:
dataset = pd.read_csv("code_chk_data.csv", names=["Query", "Type"])
print(dataset)
class ClassifierModel:
def __init__(_self, data, criteria, model_name="all-MiniLM-L6-v2"):
_self.scaler = None
_self.embeddings = None
_self.classifier = None
_self.Y_test = None
_self.Y_train = None
_self.X_test = None
_self.X_train = None
_self.Y = None
_self.X = None
_self.punctuations = None
_self.nlp = spacy.load("en_core_web_sm")
_self.stop_words = _self.nlp.Defaults.stop_words
# filtered_dataset = data.loc[(data["Type"] == criteria[0]) | (data["Type"] == criteria[1])]
# _self.dataset = filtered_dataset
_self.dataset = data
_self.criteria = criteria
_self.model = SentenceTransformer(model_name)
def split(_self):
if len(_self.X) != len(_self.Y):
print("Length of X not equal to Y", len(_self.X), len(_self.Y), len(dataset), len(_self.embeddings))
return
_self.X_train, _self.X_test, _self.Y_train, _self.Y_test = train_test_split(_self.X, _self.Y, test_size=0.20)
def tokenizer(_self, sentence):
words = _self.nlp(sentence)
_self.punctuations = "!#$%&'()*+,-./:;<=>?@[\]^_`{|}~"