-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathsfp_github.py
282 lines (224 loc) · 9.65 KB
/
sfp_github.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
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name: sfp_github
# Purpose: Identifies public code repositories in Github associated with
# your target.
#
# Author: Steve Micallef <[email protected]>
#
# Created: 21/07/2015
# Copyright: (c) Steve Micallef 2015
# Licence: MIT
# -------------------------------------------------------------------------------
import json
from spiderfoot import SpiderFootEvent, SpiderFootPlugin
class sfp_github(SpiderFootPlugin):
meta = {
'name': "Github",
'summary': "Identify associated public code repositories on Github.",
'flags': [],
'useCases': ["Footprint", "Passive"],
'categories': ["Social Media"],
'dataSource': {
'website': "https://github.com/",
'model': "FREE_NOAUTH_UNLIMITED",
'references': [
"https://developer.github.com/"
],
'favIcon': "https://github.githubassets.com/favicons/favicon.png",
'logo': "https://github.githubassets.com/favicons/favicon.png",
'description': "GitHub brings together the world's largest community of "
"developers to discover, share, and build better software.",
}
}
# Default options
opts = {
'namesonly': True
}
# Option descriptions
optdescs = {
'namesonly': "Match repositories by name only, not by their descriptions. Helps reduce false positives."
}
def setup(self, sfc, userOpts=dict()):
self.sf = sfc
self.results = self.tempStorage()
for opt in list(userOpts.keys()):
self.opts[opt] = userOpts[opt]
# What events is this module interested in for input
def watchedEvents(self):
return ["DOMAIN_NAME", "USERNAME", "SOCIAL_MEDIA"]
# What events this module produces
# This is to support the end user in selecting modules based on events
# produced.
def producedEvents(self):
return ["RAW_RIR_DATA", "GEOINFO", "PUBLIC_CODE_REPO"]
# Build up repo info for use as an event
def buildRepoInfo(self, item):
# Get repos matching the name
name = item.get('name')
if name is None:
self.debug("Incomplete Github information found (name).")
return None
html_url = item.get('html_url')
if html_url is None:
self.debug("Incomplete Github information found (url).")
return None
description = item.get('description')
if description is None:
self.debug("Incomplete Github information found (description).")
return None
return "\n".join([f"Name: {name}", f"URL: {html_url}", f"Description: {description}"])
def handleEvent(self, event):
eventName = event.eventType
eventData = event.data
srcModuleName = event.module
self.debug(f"Received event, {eventName}, from {srcModuleName}")
if eventData in self.results:
self.debug(f"Already did a search for {eventData}, skipping.")
return
self.results[eventData] = True
# Extract name and location from profile
if eventName == "SOCIAL_MEDIA":
try:
network = eventData.split(": ")[0]
url = eventData.split(": ")[1].replace("<SFURL>", "").replace("</SFURL>", "")
except Exception as e:
self.debug(f"Unable to parse SOCIAL_MEDIA: {eventData} ({e})")
return
if network != "Github":
self.debug(f"Skipping social network profile, {url}, as not a GitHub profile")
return
try:
urlParts = url.split("/")
username = urlParts[len(urlParts) - 1]
except Exception:
self.debug(f"Couldn't get a username out of {url}")
return
res = self.sf.fetchUrl(
f"https://api.github.com/users/{username}",
timeout=self.opts['_fetchtimeout'],
useragent=self.opts['_useragent']
)
if res['content'] is None:
return
try:
json_data = json.loads(res['content'])
except Exception as e:
self.debug(f"Error processing JSON response: {e}")
return
if not json_data.get('login'):
self.debug(f"{username} is not a valid GitHub profile")
return
full_name = json_data.get('name')
if not full_name:
self.debug(f"{username} is not a valid GitHub profile")
return
e = SpiderFootEvent("RAW_RIR_DATA", f"Possible full name: {full_name}", self.__name__, event)
self.notifyListeners(e)
location = json_data.get('location')
if location is None:
return
if len(location) < 3 or len(location) > 100:
self.debug(f"Skipping likely invalid location: {location}")
return
e = SpiderFootEvent("GEOINFO", location, self.__name__, event)
self.notifyListeners(e)
return
if eventName == "DOMAIN_NAME":
username = self.sf.domainKeyword(eventData, self.opts['_internettlds'])
if not username:
return
if eventName == "USERNAME":
username = eventData
self.debug(f"Looking at {username}")
failed = False
# Get all the repositories based on direct matches with the
# name identified
url = f"https://api.github.com/search/repositories?q={username}"
res = self.sf.fetchUrl(
url,
timeout=self.opts['_fetchtimeout'],
useragent=self.opts['_useragent']
)
if res['content'] is None:
self.error(f"Unable to fetch {url}")
failed = True
if not failed:
try:
ret = json.loads(res['content'])
except Exception as e:
self.debug(f"Error processing JSON response from GitHub: {e}")
ret = None
if ret is None:
self.error(f"Unable to process empty response from Github for: {username}")
failed = True
if not failed:
if ret.get('total_count', "0") == "0" or len(ret['items']) == 0:
self.debug(f"No Github information for {username}")
failed = True
if not failed:
for item in ret['items']:
repo_info = self.buildRepoInfo(item)
if repo_info is not None:
if self.opts['namesonly'] and username != item['name']:
continue
evt = SpiderFootEvent("PUBLIC_CODE_REPO", repo_info, self.__name__, event)
self.notifyListeners(evt)
# Now look for users matching the name found
failed = False
url = f"https://api.github.com/search/users?q={username}"
res = self.sf.fetchUrl(
url,
timeout=self.opts['_fetchtimeout'],
useragent=self.opts['_useragent']
)
if res['content'] is None:
self.error(f"Unable to fetch {url}")
failed = True
if not failed:
try:
ret = json.loads(res['content'])
if ret is None:
self.error(f"Unable to process empty response from Github for: {username}")
failed = True
except Exception:
self.error(f"Unable to process invalid response from Github for: {username}")
failed = True
if not failed:
if ret.get('total_count', "0") == "0" or len(ret['items']) == 0:
self.debug("No Github information for " + username)
failed = True
if not failed:
# For each user matching the username, get their repos
for item in ret['items']:
if item.get('repos_url') is None:
self.debug("Incomplete Github information found (repos_url).")
continue
url = item['repos_url']
res = self.sf.fetchUrl(url, timeout=self.opts['_fetchtimeout'],
useragent=self.opts['_useragent'])
if res['content'] is None:
self.error(f"Unable to fetch {url}")
continue
try:
repret = json.loads(res['content'])
except Exception as e:
self.error(f"Invalid JSON returned from Github: {e}")
continue
if repret is None:
self.error(f"Unable to process empty response from Github for: {username}")
continue
for item in repret:
if not isinstance(item, dict):
self.debug("Encountered an unexpected or empty response from Github.")
continue
repo_info = self.buildRepoInfo(item)
if repo_info is not None:
if self.opts['namesonly'] and item['name'] != username:
continue
if eventName == "USERNAME" and "/" + username + "/" not in item.get('html_url', ''):
continue
evt = SpiderFootEvent("PUBLIC_CODE_REPO", repo_info,
self.__name__, event)
self.notifyListeners(evt)
# End of sfp_github class