-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgmailExtractor.py
More file actions
153 lines (121 loc) · 5.15 KB
/
gmailExtractor.py
File metadata and controls
153 lines (121 loc) · 5.15 KB
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
import hashlib
import requests
import base64
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from dotenv import load_dotenv
import os
load_dotenv()
apiKey = os.getenv('virusTotal_Key')
SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"]
class GMAIL_EXTRACTOR:
def sayHello(self):
print("\nWelcome to Gmail File Analyzer,\ndeveloped by SSHPECTATOR")
def initVars(self):
self.mail = object
self.mailbox = ""
self.resp = None
self.messages = []
self.res = None
self.msg_data = []
self.file = ""
self.hash = ""
def getLogin(self):
print("\nUse your GMAIL login details to login")
creds = None
if os.path.exists("token.json"):
creds = Credentials.from_authorized_user_file("token.json", SCOPES)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
creds = flow.run_local_server(port=0)
with open("token.json", "w") as token:
token.write(creds.to_json())
try:
service = build("gmail", "v1", credentials=creds)
return service
except HttpError as error:
print(f"An error occurred: {error}")
return None
# def attemptLogin(self):
# self.mail = imaplib.IMAP4_SSL("imap.gmail.com", 993)
# if self.mail.login(self.usr, self.pwd):
# print("\nLogin Successful")
# else:
# print("\nLogin Failed")
# return False
def getSHA256(self, file):
h = hashlib.sha256()
with open(file, 'rb') as f:
while True:
chunk = f.read(4096)
if not chunk:
break
h.update(chunk)
self.hash= h.hexdigest()
return h.hexdigest()
def getSHA256_from_bytes(self, data):
h = hashlib.sha256()
h.update(data)
self.hash = h.hexdigest()
return self.hash
def useVirusTotal(self, hash):
url = "https://www.virustotal.com/api/v3/files/{}".format(hash)
headers = {
"accept": "application/json",
"x-apikey": apiKey
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
try:
verdict = data['data']['attributes'].get('threat_verdict', "VERDICT_UNKOWN")
return verdict
except KeyError:
stats = data['data']['attributes']['last_analysis_stats']
if stats['malicious'] > 0:
return "MALICIOUS"
return "VERDICT_UNDECTED"
elif response.status_code == 404:
return "FILE_NOT_FOUND"
else:
return "ERROR"
def getPDF(self,service):
try:
results = service.users().messages().list(userId="me",
q="is:unread has:attachment filename:pdf",
labelIds=['INBOX']
).execute()
self.messages = results.get('messages', [])
if not self.messages:
print("\n[!] No messages with PDF attachements to analyze [!]")
return
for msg in self.messages:
self.msg_data = service.users().messages().get(userId="me", id=msg['id']).execute()
payload = self.msg_data.get('payload', {})
self._processParts(service, msg['id'], payload.get('parts', []))
except Exception as e:
print("ERROR: {}".format(e))
"""Support function to treat multipart emails"""
def _processParts(self, service, message_id, parts):
for part in parts:
filename = part.get('filename')
if filename and filename.lower().endswith('.pdf'):
att_id = part['body'].get('attachmentId')
attachment = service.users().messages().attachments().get(
userId='me', messageId=message_id, id=att_id
).execute()
file_data = base64.urlsafe_b64decode(attachment['data'].encode('UTF-8'))
print("\n[*] Analyzing file: {} [*]".format(filename))
sha = self.getSHA256_from_bytes(file_data)
print(f"[!] SHA256: {sha}")
verdict = self.useVirusTotal(sha)
print(f"[RESULTS] {verdict}")
if 'parts' in part:
self._processParts(service, message_id, part['parts'])