code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def unet_34(pretrained=False, bn=False, progress=True, **kwargs):
"""
Construct 34 layer Unet3D model as in
https://arxiv.org/abs/1711.11248
Args:
pretrained (bool): If True, returns a model pre-trained on Kinetics-400
progress (bool): If True, displays a progress bar of the download to stderr
Returns:
nn.Module: R3D-18 encoder
"""
global batchnorm
# bn = False
if bn:
batchnorm = nn.BatchNorm3d
else:
batchnorm = identity
return _video_resnet('r3d_34',
pretrained, progress,
block=BasicBlock,
conv_makers=[Conv3DSimple] * 4,
layers=[3, 4, 6, 3],
stem=BasicStem, **kwargs) | Construct 34 layer Unet3D model as in
https://arxiv.org/abs/1711.11248
Args:
pretrained (bool): If True, returns a model pre-trained on Kinetics-400
progress (bool): If True, displays a progress bar of the download to stderr
Returns:
nn.Module: R3D-18 encoder | unet_34 | python | tarun005/FLAVR | model/resnet_3D.py | https://github.com/tarun005/FLAVR/blob/master/model/resnet_3D.py | Apache-2.0 |
def __init__(self, data_root, is_training , input_frames="1357"):
"""
Creates a Vimeo Septuplet object.
Inputs.
data_root: Root path for the Vimeo dataset containing the sep tuples.
is_training: Train/Test.
input_frames: Which frames to input for frame interpolation network.
"""
self.data_root = data_root
self.image_root = os.path.join(self.data_root, 'sequences')
self.training = is_training
self.inputs = input_frames
test_fn = os.path.join(self.data_root, 'sep_testlist.txt')
with open(test_fn, 'r') as f:
self.testlist = f.read().splitlines()
if self.training:
train_fn = os.path.join(self.data_root, 'sep_trainlist.txt')
with open(train_fn, 'r') as f:
self.trainlist = f.read().splitlines()
self.transforms = transforms.Compose([
transforms.RandomCrop(256),
transforms.RandomHorizontalFlip(0.5),
transforms.RandomVerticalFlip(0.5),
transforms.ColorJitter(0.05, 0.05, 0.05, 0.05),
transforms.ToTensor()
])
else:
self.transforms = transforms.Compose([
transforms.ToTensor()
]) | Creates a Vimeo Septuplet object.
Inputs.
data_root: Root path for the Vimeo dataset containing the sep tuples.
is_training: Train/Test.
input_frames: Which frames to input for frame interpolation network. | __init__ | python | tarun005/FLAVR | dataset/vimeo90k_septuplet.py | https://github.com/tarun005/FLAVR/blob/master/dataset/vimeo90k_septuplet.py | Apache-2.0 |
def crop(clip, i, j, h, w):
"""
Args:
clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
"""
assert len(clip.size()) == 4, "clip should be a 4D tensor"
return clip[..., i : i + h, j : j + w] | Args:
clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W) | crop | python | tarun005/FLAVR | dataset/transforms.py | https://github.com/tarun005/FLAVR/blob/master/dataset/transforms.py | Apache-2.0 |
def temporal_center_crop(clip, clip_len):
"""
Args:
clip (torch.tensor): Video clip to be
cropped along the temporal axis. Size is (C, T, H, W)
"""
assert len(clip.size()) == 4, "clip should be a 4D tensor"
assert clip.size(1) >= clip_len, "clip is shorter than the proposed lenght"
middle = int(clip.size(1) // 2)
start = middle - clip_len // 2
return clip[:, start : start + clip_len, ...] | Args:
clip (torch.tensor): Video clip to be
cropped along the temporal axis. Size is (C, T, H, W) | temporal_center_crop | python | tarun005/FLAVR | dataset/transforms.py | https://github.com/tarun005/FLAVR/blob/master/dataset/transforms.py | Apache-2.0 |
def resized_crop(clip, i, j, h, w, size, interpolation_mode="bilinear"):
"""
Do spatial cropping and resizing to the video clip
Args:
clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
i (int): i in (i,j) i.e coordinates of the upper left corner.
j (int): j in (i,j) i.e coordinates of the upper left corner.
h (int): Height of the cropped region.
w (int): Width of the cropped region.
size (tuple(int, int)): height and width of resized clip
Returns:
clip (torch.tensor): Resized and cropped clip. Size is (C, T, H, W)
"""
assert _is_tensor_video_clip(clip), "clip should be a 4D torch.tensor"
clip = crop(clip, i, j, h, w)
clip = resize(clip, size, interpolation_mode)
return clip | Do spatial cropping and resizing to the video clip
Args:
clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
i (int): i in (i,j) i.e coordinates of the upper left corner.
j (int): j in (i,j) i.e coordinates of the upper left corner.
h (int): Height of the cropped region.
w (int): Width of the cropped region.
size (tuple(int, int)): height and width of resized clip
Returns:
clip (torch.tensor): Resized and cropped clip. Size is (C, T, H, W) | resized_crop | python | tarun005/FLAVR | dataset/transforms.py | https://github.com/tarun005/FLAVR/blob/master/dataset/transforms.py | Apache-2.0 |
def to_tensor(clip):
"""
Convert tensor data type from uint8 to float, divide value by 255.0 and
permute the dimenions of clip tensor
Args:
clip (torch.tensor, dtype=torch.uint8): Size is (T, H, W, C)
Return:
clip (torch.tensor, dtype=torch.float): Size is (C, T, H, W)
"""
_is_tensor_video_clip(clip)
if not clip.dtype == torch.uint8:
raise TypeError(
"clip tensor should have data type uint8. Got %s" % str(clip.dtype)
)
return clip.float().permute(3, 0, 1, 2) / 255.0 | Convert tensor data type from uint8 to float, divide value by 255.0 and
permute the dimenions of clip tensor
Args:
clip (torch.tensor, dtype=torch.uint8): Size is (T, H, W, C)
Return:
clip (torch.tensor, dtype=torch.float): Size is (C, T, H, W) | to_tensor | python | tarun005/FLAVR | dataset/transforms.py | https://github.com/tarun005/FLAVR/blob/master/dataset/transforms.py | Apache-2.0 |
def normalize(clip, mean, std, inplace=False):
"""
Args:
clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W)
mean (tuple): pixel RGB mean. Size is (3)
std (tuple): pixel standard deviation. Size is (3)
Returns:
normalized clip (torch.tensor): Size is (C, T, H, W)
"""
assert _is_tensor_video_clip(clip), "clip should be a 4D torch.tensor"
if not inplace:
clip = clip.clone()
mean = torch.as_tensor(mean, dtype=clip.dtype, device=clip.device)
std = torch.as_tensor(std, dtype=clip.dtype, device=clip.device)
clip.sub_(mean[:, None, None, None]).div_(std[:, None, None, None])
return clip | Args:
clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W)
mean (tuple): pixel RGB mean. Size is (3)
std (tuple): pixel standard deviation. Size is (3)
Returns:
normalized clip (torch.tensor): Size is (C, T, H, W) | normalize | python | tarun005/FLAVR | dataset/transforms.py | https://github.com/tarun005/FLAVR/blob/master/dataset/transforms.py | Apache-2.0 |
def hflip(clip):
"""
Args:
clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W)
Returns:
flipped clip (torch.tensor): Size is (C, T, H, W)
"""
assert _is_tensor_video_clip(clip), "clip should be a 4D torch.tensor"
return clip.flip((-1)) | Args:
clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W)
Returns:
flipped clip (torch.tensor): Size is (C, T, H, W) | hflip | python | tarun005/FLAVR | dataset/transforms.py | https://github.com/tarun005/FLAVR/blob/master/dataset/transforms.py | Apache-2.0 |
def vflip(clip):
"""
Args:
clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W)
Returns:
flipped clip (torch.tensor): Size is (C, T, H, W)
"""
assert _is_tensor_video_clip(clip), "clip should be a 4D torch.tensor"
return clip.flip((-2)) | Args:
clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W)
Returns:
flipped clip (torch.tensor): Size is (C, T, H, W) | vflip | python | tarun005/FLAVR | dataset/transforms.py | https://github.com/tarun005/FLAVR/blob/master/dataset/transforms.py | Apache-2.0 |
def tflip(clip):
"""
Args:
clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W)
Returns:
flipped clip (torch.tensor): Size is (C, T, H, W)
"""
assert _is_tensor_video_clip(clip), "clip should be a 4D torch.tensor"
return clip.flip((-3)) | Args:
clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W)
Returns:
flipped clip (torch.tensor): Size is (C, T, H, W) | tflip | python | tarun005/FLAVR | dataset/transforms.py | https://github.com/tarun005/FLAVR/blob/master/dataset/transforms.py | Apache-2.0 |
def __call__(self, clip):
"""
Args:
clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
Returns:
torch.tensor: randomly cropped/resized video clip.
size is (C, T, OH, OW)
"""
i, j, h, w = self.get_params(clip, self.size)
return crop(clip, i, j, h, w) | Args:
clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
Returns:
torch.tensor: randomly cropped/resized video clip.
size is (C, T, OH, OW) | __call__ | python | tarun005/FLAVR | dataset/transforms.py | https://github.com/tarun005/FLAVR/blob/master/dataset/transforms.py | Apache-2.0 |
def __call__(self, clip):
"""
Args:
clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
Returns:
torch.tensor: randomly cropped/resized video clip.
size is (C, T, H, W)
"""
i, j, h, w = self.get_params(clip, self.scale, self.ratio)
return resized_crop(clip, i, j, h, w, self.size, self.interpolation_mode) | Args:
clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
Returns:
torch.tensor: randomly cropped/resized video clip.
size is (C, T, H, W) | __call__ | python | tarun005/FLAVR | dataset/transforms.py | https://github.com/tarun005/FLAVR/blob/master/dataset/transforms.py | Apache-2.0 |
def __call__(self, clip):
"""
Args:
clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
Returns:
torch.tensor: central cropping of video clip. Size is
(C, T, crop_size, crop_size)
"""
return center_crop(clip, self.crop_size) | Args:
clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
Returns:
torch.tensor: central cropping of video clip. Size is
(C, T, crop_size, crop_size) | __call__ | python | tarun005/FLAVR | dataset/transforms.py | https://github.com/tarun005/FLAVR/blob/master/dataset/transforms.py | Apache-2.0 |
def __call__(self, clip):
"""
Args:
clip (torch.tensor): video clip to be
normalized. Size is (C, T, H, W)
"""
return normalize(clip, self.mean, self.std, self.inplace) | Args:
clip (torch.tensor): video clip to be
normalized. Size is (C, T, H, W) | __call__ | python | tarun005/FLAVR | dataset/transforms.py | https://github.com/tarun005/FLAVR/blob/master/dataset/transforms.py | Apache-2.0 |
def __call__(self, clip):
"""
Args:
clip (torch.tensor, dtype=torch.uint8): Size is (T, H, W, C)
Return:
clip (torch.tensor, dtype=torch.float): Size is (C, T, H, W)
"""
return to_tensor(clip) | Args:
clip (torch.tensor, dtype=torch.uint8): Size is (T, H, W, C)
Return:
clip (torch.tensor, dtype=torch.float): Size is (C, T, H, W) | __call__ | python | tarun005/FLAVR | dataset/transforms.py | https://github.com/tarun005/FLAVR/blob/master/dataset/transforms.py | Apache-2.0 |
def __call__(self, clip):
"""
Args:
clip (torch.tensor): Size is (C, T, H, W)
Return:
clip (torch.tensor): Size is (C, T, H, W)
"""
if random.random() < self.p:
clip = hflip(clip)
return clip | Args:
clip (torch.tensor): Size is (C, T, H, W)
Return:
clip (torch.tensor): Size is (C, T, H, W) | __call__ | python | tarun005/FLAVR | dataset/transforms.py | https://github.com/tarun005/FLAVR/blob/master/dataset/transforms.py | Apache-2.0 |
def __call__(self, clip):
"""
Args:
clip (torch.tensor): Size is (C, T, H, W)
Return:
clip (torch.tensor): Size is (C, T, H, W)
"""
if random.random() < self.p:
clip = vflip(clip)
return clip | Args:
clip (torch.tensor): Size is (C, T, H, W)
Return:
clip (torch.tensor): Size is (C, T, H, W) | __call__ | python | tarun005/FLAVR | dataset/transforms.py | https://github.com/tarun005/FLAVR/blob/master/dataset/transforms.py | Apache-2.0 |
def __call__(self, clip):
"""
Args:
clip (torch.tensor): Size is (C, T, H, W)
Return:
clip (torch.tensor): Size is (C, T, H, W)
"""
if random.random() < self.p:
clip = tflip(clip)
return clip | Args:
clip (torch.tensor): Size is (C, T, H, W)
Return:
clip (torch.tensor): Size is (C, T, H, W) | __call__ | python | tarun005/FLAVR | dataset/transforms.py | https://github.com/tarun005/FLAVR/blob/master/dataset/transforms.py | Apache-2.0 |
def ResetConfig(resetLevel = 0, customConfig=None):
"""resetLevel values:
0 = Everything
1 = Main settings only (Preferences, FileNames, Advanced)
2 = Crack selection settings only (Crack)
"""
if customConfig:
currentConfig = customConfig
else:
currentConfig = config
if resetLevel == 0 or resetLevel == 1:
currentConfig["Preferences"] = {}
currentConfig["Preferences"]["UpdateOption"] = "0"
currentConfig["Preferences"]["CrackOption"] = "0"
currentConfig["Preferences"]["Steamless"] = "1"
currentConfig["Preferences"]["last_selected_folder"] = ""
currentConfig["FileNames"] = {}
currentConfig["FileNames"]["GameEXE"] = ".bak"
currentConfig["FileNames"]["BakSuffix"] = ".bak"
currentConfig["FileNames"]["SteamAPI"] = "steam_api.dll.bak"
currentConfig["FileNames"]["SteamAPI64"] = "steam_api64.dll.bak"
currentConfig["Advanced"] = {}
currentConfig["Advanced"]["RetryDelay"] = str(RETRY_DELAY)
currentConfig["Advanced"]["RetryMax"] = str(RETRY_MAX)
currentConfig["Advanced"]["BypassGameVerification"] = "0"
if resetLevel == 0 or resetLevel == 2:
currentConfig["Crack"] = {}
currentConfig["Crack"]["SelectedCrack"] = "game_ali213"
if not customConfig:
UpdateConfig() | resetLevel values:
0 = Everything
1 = Main settings only (Preferences, FileNames, Advanced)
2 = Crack selection settings only (Crack) | ResetConfig | python | BigBoiCJ/SteamAutoCracker | steam_auto_cracker_gui.py | https://github.com/BigBoiCJ/SteamAutoCracker/blob/master/steam_auto_cracker_gui.py | BSD-3-Clause |
def load_data():
""" Load GANs data from the gans.csv file """
with open('gans.tsv') as fid:
reader = csv.DictReader(fid, delimiter='\t')
gans = [row for row in reader]
return gans | Load GANs data from the gans.csv file | load_data | python | hindupuravinash/the-gan-zoo | update.py | https://github.com/hindupuravinash/the-gan-zoo/blob/master/update.py | MIT |
def update_readme(gans):
""" Update the Readme.md text file from a Jinja2 template """
import jinja2 as j2
gans.sort(key=lambda v: v['Abbr.'].upper())
j2_env = j2.Environment(loader=j2.FileSystemLoader('.'),
trim_blocks=True, lstrip_blocks=True)
with open('README.md', 'w') as fid:
print(j2_env.get_template('README.j2.md').render(gans=gans), file=fid) | Update the Readme.md text file from a Jinja2 template | update_readme | python | hindupuravinash/the-gan-zoo | update.py | https://github.com/hindupuravinash/the-gan-zoo/blob/master/update.py | MIT |
def update_figure(gans):
""" Update the figure cumulative_gans.jpg """
data = np.array([int(gan['Year']) + int(gan['Month']) / 12
for gan in gans])
x_range = int(np.ceil(np.max(data) - np.min(data)) * 12) + 1
y_range = int(np.ceil(data.size / 10)) * 10 + 1
with plt.style.context("seaborn"):
plt.hist(data, x_range, cumulative="True")
plt.xticks(range(2014, 2019))
plt.yticks(np.arange(0, y_range, 15))
plt.title("Cumulative number of named GAN papers by month")
plt.xlabel("Year")
plt.ylabel("Total number of papers")
plt.savefig('cumulative_gans.jpg') | Update the figure cumulative_gans.jpg | update_figure | python | hindupuravinash/the-gan-zoo | update.py | https://github.com/hindupuravinash/the-gan-zoo/blob/master/update.py | MIT |
def update_github_stats(gans):
""" Update Github stats """
num_rows = len(gans)
print('Fetching Github stats...')
for i, gan in enumerate(gans):
url = gan['Official_Code']
if url != "-" and url != "":
print(str(i) + '/' + str(num_rows))
result = requests.get(url)
c = result.text
soup = BeautifulSoup(c, "html.parser")
samples = soup.select("a.social-count")
gan['Watches'] = samples[0].get_text().strip().replace(",", "")
gan['Stars'] = samples[1].get_text().strip().replace(",", "")
gan['Forks'] = samples[2].get_text().strip().replace(",", "")
print(str(i) + '/' + str(num_rows))
print('Complete.')
with open('gans.tsv', 'w') as outfile:
fp = csv.DictWriter(outfile, gans[0].keys(), delimiter='\t')
fp.writeheader()
fp.writerows(gans) | Update Github stats | update_github_stats | python | hindupuravinash/the-gan-zoo | update.py | https://github.com/hindupuravinash/the-gan-zoo/blob/master/update.py | MIT |
def __init__(self, options: dict) -> None:
"""Initialize SpiderFoot object.
Args:
options (dict): dictionary of configuration options.
Raises:
TypeError: options argument was invalid type
"""
if not isinstance(options, dict):
raise TypeError(f"options is {type(options)}; expected dict()")
self.opts = deepcopy(options)
self.log = logging.getLogger(f"spiderfoot.{__name__}")
# This is ugly but we don't want any fetches to fail - we expect
# to encounter unverified SSL certs!
ssl._create_default_https_context = ssl._create_unverified_context # noqa: DUO122
if self.opts.get('_dnsserver', "") != "":
res = dns.resolver.Resolver()
res.nameservers = [self.opts['_dnsserver']]
dns.resolver.override_system_resolver(res) | Initialize SpiderFoot object.
Args:
options (dict): dictionary of configuration options.
Raises:
TypeError: options argument was invalid type | __init__ | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def dbh(self):
"""Database handle
Returns:
SpiderFootDb: database handle
"""
return self._dbh | Database handle
Returns:
SpiderFootDb: database handle | dbh | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def scanId(self) -> str:
"""Scan instance ID
Returns:
str: scan instance ID
"""
return self._scanId | Scan instance ID
Returns:
str: scan instance ID | scanId | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def socksProxy(self) -> str:
"""SOCKS proxy
Returns:
str: socks proxy
"""
return self._socksProxy | SOCKS proxy
Returns:
str: socks proxy | socksProxy | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def dbh(self, dbh):
"""Called usually some time after instantiation
to set up a database handle and scan ID, used
for logging events to the database about a scan.
Args:
dbh (SpiderFootDb): database handle
"""
self._dbh = dbh | Called usually some time after instantiation
to set up a database handle and scan ID, used
for logging events to the database about a scan.
Args:
dbh (SpiderFootDb): database handle | dbh | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def scanId(self, scanId: str) -> str:
"""Set the scan ID this instance of SpiderFoot is being used in.
Args:
scanId (str): scan instance ID
"""
self._scanId = scanId | Set the scan ID this instance of SpiderFoot is being used in.
Args:
scanId (str): scan instance ID | scanId | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def socksProxy(self, socksProxy: str) -> str:
"""SOCKS proxy
Bit of a hack to support SOCKS because of the loading order of
modules. sfscan will call this to update the socket reference
to the SOCKS one.
Args:
socksProxy (str): SOCKS proxy
"""
self._socksProxy = socksProxy | SOCKS proxy
Bit of a hack to support SOCKS because of the loading order of
modules. sfscan will call this to update the socket reference
to the SOCKS one.
Args:
socksProxy (str): SOCKS proxy | socksProxy | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def optValueToData(self, val: str) -> str:
"""Supplied an option value, return the data based on what the
value is. If val is a URL, you'll get back the fetched content,
if val is a file path it will be loaded and get back the contents,
and if a string it will simply be returned back.
Args:
val (str): option name
Returns:
str: option data
"""
if not isinstance(val, str):
self.error(f"Invalid option value {val}")
return None
if val.startswith('@'):
fname = val.split('@')[1]
self.info(f"Loading configuration data from: {fname}")
try:
with open(fname, "r") as f:
return f.read()
except Exception as e:
self.error(f"Unable to open option file, {fname}: {e}")
return None
if val.lower().startswith('http://') or val.lower().startswith('https://'):
try:
self.info(f"Downloading configuration data from: {val}")
session = self.getSession()
res = session.get(val)
return res.content.decode('utf-8')
except BaseException as e:
self.error(f"Unable to open option URL, {val}: {e}")
return None
return val | Supplied an option value, return the data based on what the
value is. If val is a URL, you'll get back the fetched content,
if val is a file path it will be loaded and get back the contents,
and if a string it will simply be returned back.
Args:
val (str): option name
Returns:
str: option data | optValueToData | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def error(self, message: str) -> None:
"""Print and log an error message
Args:
message (str): error message
"""
if not self.opts['__logging']:
return
self.log.error(message, extra={'scanId': self._scanId}) | Print and log an error message
Args:
message (str): error message | error | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def fatal(self, error: str) -> None:
"""Print an error message and stacktrace then exit.
Args:
error (str): error message
"""
self.log.critical(error, extra={'scanId': self._scanId})
print(str(inspect.stack()))
sys.exit(-1) | Print an error message and stacktrace then exit.
Args:
error (str): error message | fatal | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def status(self, message: str) -> None:
"""Log and print a status message.
Args:
message (str): status message
"""
if not self.opts['__logging']:
return
self.log.info(message, extra={'scanId': self._scanId}) | Log and print a status message.
Args:
message (str): status message | status | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def info(self, message: str) -> None:
"""Log and print an info message.
Args:
message (str): info message
"""
if not self.opts['__logging']:
return
self.log.info(f"{message}", extra={'scanId': self._scanId}) | Log and print an info message.
Args:
message (str): info message | info | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def debug(self, message: str) -> None:
"""Log and print a debug message.
Args:
message (str): debug message
"""
if not self.opts['_debug']:
return
if not self.opts['__logging']:
return
self.log.debug(f"{message}", extra={'scanId': self._scanId}) | Log and print a debug message.
Args:
message (str): debug message | debug | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def hashstring(self, string: str) -> str:
"""Returns a SHA256 hash of the specified input.
Args:
string (str): data to be hashed
Returns:
str: SHA256 hash
"""
s = string
if type(string) in [list, dict]:
s = str(string)
return hashlib.sha256(s.encode('raw_unicode_escape')).hexdigest() | Returns a SHA256 hash of the specified input.
Args:
string (str): data to be hashed
Returns:
str: SHA256 hash | hashstring | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def cachePut(self, label: str, data: str) -> None:
"""Store data to the cache.
Args:
label (str): Name of the cached data to be used when retrieving the cached data.
data (str): Data to cache
"""
pathLabel = hashlib.sha224(label.encode('utf-8')).hexdigest()
cacheFile = SpiderFootHelpers.cachePath() + "/" + pathLabel
with io.open(cacheFile, "w", encoding="utf-8", errors="ignore") as fp:
if isinstance(data, list):
for line in data:
if isinstance(line, str):
fp.write(line)
fp.write("\n")
else:
fp.write(line.decode('utf-8') + '\n')
elif isinstance(data, bytes):
fp.write(data.decode('utf-8'))
else:
fp.write(data) | Store data to the cache.
Args:
label (str): Name of the cached data to be used when retrieving the cached data.
data (str): Data to cache | cachePut | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def cacheGet(self, label: str, timeoutHrs: int) -> str:
"""Retreive data from the cache.
Args:
label (str): Name of the cached data to retrieve
timeoutHrs (int): Age of the cached data (in hours)
for which the data is considered to be too old and ignored.
Returns:
str: cached data
"""
if not label:
return None
pathLabel = hashlib.sha224(label.encode('utf-8')).hexdigest()
cacheFile = SpiderFootHelpers.cachePath() + "/" + pathLabel
try:
cache_stat = os.stat(cacheFile)
except OSError:
return None
if cache_stat.st_size == 0:
return None
if cache_stat.st_mtime > time.time() - timeoutHrs * 3600 or timeoutHrs == 0:
with open(cacheFile, "r", encoding='utf-8') as fp:
return fp.read()
return None | Retreive data from the cache.
Args:
label (str): Name of the cached data to retrieve
timeoutHrs (int): Age of the cached data (in hours)
for which the data is considered to be too old and ignored.
Returns:
str: cached data | cacheGet | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def configSerialize(self, opts: dict, filterSystem: bool = True):
"""Convert a Python dictionary to something storable in the database.
Args:
opts (dict): Dictionary of SpiderFoot configuration options
filterSystem (bool): TBD
Returns:
dict: config options
Raises:
TypeError: arg type was invalid
"""
if not isinstance(opts, dict):
raise TypeError(f"opts is {type(opts)}; expected dict()")
storeopts = dict()
if not opts:
return storeopts
for opt in list(opts.keys()):
# Filter out system temporary variables like GUID and others
if opt.startswith('__') and filterSystem:
continue
if isinstance(opts[opt], (int, str)):
storeopts[opt] = opts[opt]
if isinstance(opts[opt], bool):
if opts[opt]:
storeopts[opt] = 1
else:
storeopts[opt] = 0
if isinstance(opts[opt], list):
storeopts[opt] = ','.join(opts[opt])
if '__modules__' not in opts:
return storeopts
if not isinstance(opts['__modules__'], dict):
raise TypeError(f"opts['__modules__'] is {type(opts['__modules__'])}; expected dict()")
for mod in opts['__modules__']:
for opt in opts['__modules__'][mod]['opts']:
if opt.startswith('_') and filterSystem:
continue
mod_opt = f"{mod}:{opt}"
mod_opt_val = opts['__modules__'][mod]['opts'][opt]
if isinstance(mod_opt_val, (int, str)):
storeopts[mod_opt] = mod_opt_val
if isinstance(mod_opt_val, bool):
if mod_opt_val:
storeopts[mod_opt] = 1
else:
storeopts[mod_opt] = 0
if isinstance(mod_opt_val, list):
storeopts[mod_opt] = ','.join(str(x) for x in mod_opt_val)
return storeopts | Convert a Python dictionary to something storable in the database.
Args:
opts (dict): Dictionary of SpiderFoot configuration options
filterSystem (bool): TBD
Returns:
dict: config options
Raises:
TypeError: arg type was invalid | configSerialize | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def configUnserialize(self, opts: dict, referencePoint: dict, filterSystem: bool = True):
"""Take strings, etc. from the database or UI and convert them
to a dictionary for Python to process.
Args:
opts (dict): SpiderFoot configuration options
referencePoint (dict): needed to know the actual types the options are supposed to be.
filterSystem (bool): Ignore global "system" configuration options
Returns:
dict: TBD
Raises:
TypeError: arg type was invalid
"""
if not isinstance(opts, dict):
raise TypeError(f"opts is {type(opts)}; expected dict()")
if not isinstance(referencePoint, dict):
raise TypeError(f"referencePoint is {type(referencePoint)}; expected dict()")
returnOpts = referencePoint
# Global options
for opt in list(referencePoint.keys()):
if opt.startswith('__') and filterSystem:
# Leave out system variables
continue
if opt not in opts:
continue
if isinstance(referencePoint[opt], bool):
if opts[opt] == "1":
returnOpts[opt] = True
else:
returnOpts[opt] = False
continue
if isinstance(referencePoint[opt], str):
returnOpts[opt] = str(opts[opt])
continue
if isinstance(referencePoint[opt], int):
returnOpts[opt] = int(opts[opt])
continue
if isinstance(referencePoint[opt], list):
if isinstance(referencePoint[opt][0], int):
returnOpts[opt] = list()
for x in str(opts[opt]).split(","):
returnOpts[opt].append(int(x))
else:
returnOpts[opt] = str(opts[opt]).split(",")
if '__modules__' not in referencePoint:
return returnOpts
if not isinstance(referencePoint['__modules__'], dict):
raise TypeError(f"referencePoint['__modules__'] is {type(referencePoint['__modules__'])}; expected dict()")
# Module options
# A lot of mess to handle typing..
for modName in referencePoint['__modules__']:
for opt in referencePoint['__modules__'][modName]['opts']:
if opt.startswith('_') and filterSystem:
continue
if modName + ":" + opt in opts:
ref_mod = referencePoint['__modules__'][modName]['opts'][opt]
if isinstance(ref_mod, bool):
if opts[modName + ":" + opt] == "1":
returnOpts['__modules__'][modName]['opts'][opt] = True
else:
returnOpts['__modules__'][modName]['opts'][opt] = False
continue
if isinstance(ref_mod, str):
returnOpts['__modules__'][modName]['opts'][opt] = str(opts[modName + ":" + opt])
continue
if isinstance(ref_mod, int):
returnOpts['__modules__'][modName]['opts'][opt] = int(opts[modName + ":" + opt])
continue
if isinstance(ref_mod, list):
if isinstance(ref_mod[0], int):
returnOpts['__modules__'][modName]['opts'][opt] = list()
for x in str(opts[modName + ":" + opt]).split(","):
returnOpts['__modules__'][modName]['opts'][opt].append(int(x))
else:
returnOpts['__modules__'][modName]['opts'][opt] = str(opts[modName + ":" + opt]).split(",")
return returnOpts | Take strings, etc. from the database or UI and convert them
to a dictionary for Python to process.
Args:
opts (dict): SpiderFoot configuration options
referencePoint (dict): needed to know the actual types the options are supposed to be.
filterSystem (bool): Ignore global "system" configuration options
Returns:
dict: TBD
Raises:
TypeError: arg type was invalid | configUnserialize | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def modulesProducing(self, events: list) -> list:
"""Return an array of modules that produce the list of types supplied.
Args:
events (list): list of event types
Returns:
list: list of modules
"""
modlist = list()
if not events:
return modlist
loaded_modules = self.opts.get('__modules__')
if not loaded_modules:
return modlist
for mod in list(loaded_modules.keys()):
provides = loaded_modules[mod].get('provides')
if not provides:
continue
if "*" in events:
modlist.append(mod)
for evtype in provides:
if evtype in events:
modlist.append(mod)
return list(set(modlist)) | Return an array of modules that produce the list of types supplied.
Args:
events (list): list of event types
Returns:
list: list of modules | modulesProducing | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def modulesConsuming(self, events: list) -> list:
"""Return an array of modules that consume the list of types supplied.
Args:
events (list): list of event types
Returns:
list: list of modules
"""
modlist = list()
if not events:
return modlist
loaded_modules = self.opts.get('__modules__')
if not loaded_modules:
return modlist
for mod in list(loaded_modules.keys()):
consumes = loaded_modules[mod].get('consumes')
if not consumes:
continue
if "*" in consumes:
modlist.append(mod)
continue
for evtype in consumes:
if evtype in events:
modlist.append(mod)
return list(set(modlist)) | Return an array of modules that consume the list of types supplied.
Args:
events (list): list of event types
Returns:
list: list of modules | modulesConsuming | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def eventsFromModules(self, modules: list) -> list:
"""Return an array of types that are produced by the list of modules supplied.
Args:
modules (list): list of modules
Returns:
list: list of types
"""
evtlist = list()
if not modules:
return evtlist
loaded_modules = self.opts.get('__modules__')
if not loaded_modules:
return evtlist
for mod in modules:
if mod in list(loaded_modules.keys()):
provides = loaded_modules[mod].get('provides')
if provides:
for evt in provides:
evtlist.append(evt)
return evtlist | Return an array of types that are produced by the list of modules supplied.
Args:
modules (list): list of modules
Returns:
list: list of types | eventsFromModules | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def eventsToModules(self, modules: list) -> list:
"""Return an array of types that are consumed by the list of modules supplied.
Args:
modules (list): list of modules
Returns:
list: list of types
"""
evtlist = list()
if not modules:
return evtlist
loaded_modules = self.opts.get('__modules__')
if not loaded_modules:
return evtlist
for mod in modules:
if mod in list(loaded_modules.keys()):
consumes = loaded_modules[mod].get('consumes')
if consumes:
for evt in consumes:
evtlist.append(evt)
return evtlist | Return an array of types that are consumed by the list of modules supplied.
Args:
modules (list): list of modules
Returns:
list: list of types | eventsToModules | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def urlFQDN(self, url: str) -> str:
"""Extract the FQDN from a URL.
Args:
url (str): URL
Returns:
str: FQDN
"""
if not url:
self.error(f"Invalid URL: {url}")
return None
baseurl = SpiderFootHelpers.urlBaseUrl(url)
if '://' in baseurl:
count = 2
else:
count = 0
# http://abc.com will split to ['http:', '', 'abc.com']
return baseurl.split('/')[count].lower() | Extract the FQDN from a URL.
Args:
url (str): URL
Returns:
str: FQDN | urlFQDN | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def domainKeyword(self, domain: str, tldList: list) -> str:
"""Extract the keyword (the domain without the TLD or any subdomains) from a domain.
Args:
domain (str): The domain to check.
tldList (list): The list of TLDs based on the Mozilla public list.
Returns:
str: The keyword
"""
if not domain:
self.error(f"Invalid domain: {domain}")
return None
# Strip off the TLD
dom = self.hostDomain(domain.lower(), tldList)
if not dom:
return None
tld = '.'.join(dom.split('.')[1:])
ret = domain.lower().replace('.' + tld, '')
# If the user supplied a domain with a sub-domain, return the second part
if '.' in ret:
return ret.split('.')[-1]
return ret | Extract the keyword (the domain without the TLD or any subdomains) from a domain.
Args:
domain (str): The domain to check.
tldList (list): The list of TLDs based on the Mozilla public list.
Returns:
str: The keyword | domainKeyword | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def domainKeywords(self, domainList: list, tldList: list) -> set:
"""Extract the keywords (the domains without the TLD or any subdomains) from a list of domains.
Args:
domainList (list): The list of domains to check.
tldList (list): The list of TLDs based on the Mozilla public list.
Returns:
set: List of keywords
"""
if not domainList:
self.error(f"Invalid domain list: {domainList}")
return set()
keywords = list()
for domain in domainList:
keywords.append(self.domainKeyword(domain, tldList))
self.debug(f"Keywords: {keywords}")
return set([k for k in keywords if k]) | Extract the keywords (the domains without the TLD or any subdomains) from a list of domains.
Args:
domainList (list): The list of domains to check.
tldList (list): The list of TLDs based on the Mozilla public list.
Returns:
set: List of keywords | domainKeywords | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def hostDomain(self, hostname: str, tldList: list) -> str:
"""Obtain the domain name for a supplied hostname.
Args:
hostname (str): The hostname to check.
tldList (list): The list of TLDs based on the Mozilla public list.
Returns:
str: The domain name.
"""
if not tldList:
return None
if not hostname:
return None
ps = PublicSuffixList(tldList, only_icann=True)
return ps.privatesuffix(hostname) | Obtain the domain name for a supplied hostname.
Args:
hostname (str): The hostname to check.
tldList (list): The list of TLDs based on the Mozilla public list.
Returns:
str: The domain name. | hostDomain | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def validHost(self, hostname: str, tldList: str) -> bool:
"""Check if the provided string is a valid hostname with a valid public suffix TLD.
Args:
hostname (str): The hostname to check.
tldList (str): The list of TLDs based on the Mozilla public list.
Returns:
bool
"""
if not tldList:
return False
if not hostname:
return False
if "." not in hostname:
return False
if not re.match(r"^[a-z0-9-\.]*$", hostname, re.IGNORECASE):
return False
ps = PublicSuffixList(tldList, only_icann=True, accept_unknown=False)
sfx = ps.privatesuffix(hostname)
return sfx is not None | Check if the provided string is a valid hostname with a valid public suffix TLD.
Args:
hostname (str): The hostname to check.
tldList (str): The list of TLDs based on the Mozilla public list.
Returns:
bool | validHost | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def isDomain(self, hostname: str, tldList: list) -> bool:
"""Check if the provided hostname string is a valid domain name.
Given a possible hostname, check if it's a domain name
By checking whether it rests atop a valid TLD.
e.g. www.example.com = False because tld of hostname is com,
and www.example has a . in it.
Args:
hostname (str): The hostname to check.
tldList (list): The list of TLDs based on the Mozilla public list.
Returns:
bool
"""
if not tldList:
return False
if not hostname:
return False
ps = PublicSuffixList(tldList, only_icann=True, accept_unknown=False)
sfx = ps.privatesuffix(hostname)
return sfx == hostname | Check if the provided hostname string is a valid domain name.
Given a possible hostname, check if it's a domain name
By checking whether it rests atop a valid TLD.
e.g. www.example.com = False because tld of hostname is com,
and www.example has a . in it.
Args:
hostname (str): The hostname to check.
tldList (list): The list of TLDs based on the Mozilla public list.
Returns:
bool | isDomain | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def validIP(self, address: str) -> bool:
"""Check if the provided string is a valid IPv4 address.
Args:
address (str): The IPv4 address to check.
Returns:
bool
"""
if not address:
return False
return netaddr.valid_ipv4(address) | Check if the provided string is a valid IPv4 address.
Args:
address (str): The IPv4 address to check.
Returns:
bool | validIP | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def validIP6(self, address: str) -> bool:
"""Check if the provided string is a valid IPv6 address.
Args:
address (str): The IPv6 address to check.
Returns:
bool: string is a valid IPv6 address
"""
if not address:
return False
return netaddr.valid_ipv6(address) | Check if the provided string is a valid IPv6 address.
Args:
address (str): The IPv6 address to check.
Returns:
bool: string is a valid IPv6 address | validIP6 | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def validIpNetwork(self, cidr: str) -> bool:
"""Check if the provided string is a valid CIDR netblock.
Args:
cidr (str): The netblock to check.
Returns:
bool: string is a valid CIDR netblock
"""
if not isinstance(cidr, str):
return False
if '/' not in cidr:
return False
try:
return netaddr.IPNetwork(str(cidr)).size > 0
except BaseException:
return False | Check if the provided string is a valid CIDR netblock.
Args:
cidr (str): The netblock to check.
Returns:
bool: string is a valid CIDR netblock | validIpNetwork | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def isPublicIpAddress(self, ip: str) -> bool:
"""Check if an IP address is public.
Args:
ip (str): IP address
Returns:
bool: IP address is public
"""
if not isinstance(ip, (str, netaddr.IPAddress)):
return False
if not self.validIP(ip) and not self.validIP6(ip):
return False
if not netaddr.IPAddress(ip).is_unicast():
return False
if netaddr.IPAddress(ip).is_loopback():
return False
if netaddr.IPAddress(ip).is_reserved():
return False
if netaddr.IPAddress(ip).is_multicast():
return False
if netaddr.IPAddress(ip).is_private():
return False
return True | Check if an IP address is public.
Args:
ip (str): IP address
Returns:
bool: IP address is public | isPublicIpAddress | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def normalizeDNS(self, res: list) -> list:
"""Clean DNS results to be a simple list
Args:
res (list): List of DNS names
Returns:
list: list of domains
"""
ret = list()
if not res:
return ret
for addr in res:
if isinstance(addr, list):
for host in addr:
host = str(host).rstrip(".")
if host:
ret.append(host)
else:
host = str(addr).rstrip(".")
if host:
ret.append(host)
return ret | Clean DNS results to be a simple list
Args:
res (list): List of DNS names
Returns:
list: list of domains | normalizeDNS | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def resolveHost(self, host: str) -> list:
"""Return a normalised IPv4 resolution of a hostname.
Args:
host (str): host to resolve
Returns:
list: IP addresses
"""
if not host:
self.error(f"Unable to resolve host: {host} (Invalid host)")
return list()
addrs = list()
try:
addrs = self.normalizeDNS(socket.gethostbyname_ex(host))
except BaseException as e:
self.debug(f"Unable to resolve host: {host} ({e})")
return addrs
if not addrs:
self.debug(f"Unable to resolve host: {host}")
return addrs
self.debug(f"Resolved {host} to IPv4: {addrs}")
return list(set(addrs)) | Return a normalised IPv4 resolution of a hostname.
Args:
host (str): host to resolve
Returns:
list: IP addresses | resolveHost | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def resolveIP(self, ipaddr: str) -> list:
"""Return a normalised resolution of an IPv4 or IPv6 address.
Args:
ipaddr (str): IP address to reverse resolve
Returns:
list: list of domain names
"""
if not self.validIP(ipaddr) and not self.validIP6(ipaddr):
self.error(f"Unable to reverse resolve {ipaddr} (Invalid IP address)")
return list()
self.debug(f"Performing reverse resolve of {ipaddr}")
try:
addrs = self.normalizeDNS(socket.gethostbyaddr(ipaddr))
except BaseException as e:
self.debug(f"Unable to reverse resolve IP address: {ipaddr} ({e})")
return list()
if not addrs:
self.debug(f"Unable to reverse resolve IP address: {ipaddr}")
return list()
self.debug(f"Reverse resolved {ipaddr} to: {addrs}")
return list(set(addrs)) | Return a normalised resolution of an IPv4 or IPv6 address.
Args:
ipaddr (str): IP address to reverse resolve
Returns:
list: list of domain names | resolveIP | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def resolveHost6(self, hostname: str) -> list:
"""Return a normalised IPv6 resolution of a hostname.
Args:
hostname (str): hostname to resolve
Returns:
list
"""
if not hostname:
self.error(f"Unable to resolve host: {hostname} (Invalid host)")
return list()
addrs = list()
try:
res = socket.getaddrinfo(hostname, None, socket.AF_INET6)
for addr in res:
if addr[4][0] not in addrs:
addrs.append(addr[4][0])
except BaseException as e:
self.debug(f"Unable to resolve host: {hostname} ({e})")
return addrs
if not addrs:
self.debug(f"Unable to resolve host: {hostname}")
return addrs
self.debug(f"Resolved {hostname} to IPv6: {addrs}")
return list(set(addrs)) | Return a normalised IPv6 resolution of a hostname.
Args:
hostname (str): hostname to resolve
Returns:
list | resolveHost6 | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def validateIP(self, host: str, ip: str) -> bool:
"""Verify a host resolves to a given IP.
Args:
host (str): host
ip (str): IP address
Returns:
bool: host resolves to the given IP address
"""
if not host:
self.error(f"Unable to resolve host: {host} (Invalid host)")
return False
if self.validIP(ip):
addrs = self.resolveHost(host)
elif self.validIP6(ip):
addrs = self.resolveHost6(host)
else:
self.error(f"Unable to verify hostname {host} resolves to {ip} (Invalid IP address)")
return False
if not addrs:
return False
return any(str(addr) == ip for addr in addrs) | Verify a host resolves to a given IP.
Args:
host (str): host
ip (str): IP address
Returns:
bool: host resolves to the given IP address | validateIP | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def safeSocket(self, host: str, port: int, timeout: int) -> 'ssl.SSLSocket':
"""Create a safe socket that's using SOCKS/TOR if it was enabled.
Args:
host (str): host
port (int): port
timeout (int): timeout
Returns:
sock
"""
sock = socket.create_connection((host, int(port)), int(timeout))
sock.settimeout(int(timeout))
return sock | Create a safe socket that's using SOCKS/TOR if it was enabled.
Args:
host (str): host
port (int): port
timeout (int): timeout
Returns:
sock | safeSocket | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def safeSSLSocket(self, host: str, port: int, timeout: int) -> 'ssl.SSLSocket':
"""Create a safe SSL connection that's using SOCKs/TOR if it was enabled.
Args:
host (str): host
port (int): port
timeout (int): timeout
Returns:
sock
"""
s = socket.socket()
s.settimeout(int(timeout))
s.connect((host, int(port)))
sock = ssl.wrap_socket(s)
sock.do_handshake()
return sock | Create a safe SSL connection that's using SOCKs/TOR if it was enabled.
Args:
host (str): host
port (int): port
timeout (int): timeout
Returns:
sock | safeSSLSocket | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def parseCert(self, rawcert: str, fqdn: str = None, expiringdays: int = 30) -> dict:
"""Parse a PEM-format SSL certificate.
Args:
rawcert (str): PEM-format SSL certificate
fqdn (str): expected FQDN for certificate
expiringdays (int): The certificate will be considered as "expiring" if within this number of days of expiry.
Returns:
dict: certificate details
"""
if not rawcert:
self.error(f"Invalid certificate: {rawcert}")
return None
ret = dict()
if '\r' in rawcert:
rawcert = rawcert.replace('\r', '')
if isinstance(rawcert, str):
rawcert = rawcert.encode('utf-8')
from cryptography.hazmat.backends.openssl import backend
cert = cryptography.x509.load_pem_x509_certificate(rawcert, backend)
sslcert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, rawcert)
sslcert_dump = OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_TEXT, sslcert)
ret['text'] = sslcert_dump.decode('utf-8', errors='replace')
ret['issuer'] = str(cert.issuer)
ret['altnames'] = list()
ret['expired'] = False
ret['expiring'] = False
ret['mismatch'] = False
ret['certerror'] = False
ret['issued'] = str(cert.subject)
# Expiry info
try:
notafter = datetime.strptime(sslcert.get_notAfter().decode('utf-8'), "%Y%m%d%H%M%SZ")
ret['expiry'] = int(notafter.strftime("%s"))
ret['expirystr'] = notafter.strftime("%Y-%m-%d %H:%M:%S")
now = int(time.time())
warnexp = now + (expiringdays * 86400)
if ret['expiry'] <= warnexp:
ret['expiring'] = True
if ret['expiry'] <= now:
ret['expired'] = True
except BaseException as e:
self.error(f"Error processing date in certificate: {e}")
ret['certerror'] = True
return ret
# SANs
try:
ext = cert.extensions.get_extension_for_class(cryptography.x509.SubjectAlternativeName)
for x in ext.value:
if isinstance(x, cryptography.x509.DNSName):
ret['altnames'].append(x.value.lower().encode('raw_unicode_escape').decode("ascii", errors='replace'))
except BaseException as e:
self.debug(f"Problem processing certificate: {e}")
certhosts = list()
try:
attrs = cert.subject.get_attributes_for_oid(cryptography.x509.oid.NameOID.COMMON_NAME)
if len(attrs) == 1:
name = attrs[0].value.lower()
# CN often duplicates one of the SANs, don't add it then
if name not in ret['altnames']:
certhosts.append(name)
except BaseException as e:
self.debug(f"Problem processing certificate: {e}")
# Check for mismatch
if fqdn and ret['issued']:
fqdn = fqdn.lower()
try:
# Extract the CN from the issued section
if "cn=" + fqdn in ret['issued'].lower():
certhosts.append(fqdn)
# Extract subject alternative names
for host in ret['altnames']:
certhosts.append(host.replace("dns:", ""))
ret['hosts'] = certhosts
self.debug(f"Checking for {fqdn} in certificate subject")
fqdn_tld = ".".join(fqdn.split(".")[1:]).lower()
found = False
for chost in certhosts:
if chost == fqdn:
found = True
if chost == "*." + fqdn_tld:
found = True
if chost == fqdn_tld:
found = True
if not found:
ret['mismatch'] = True
except BaseException as e:
self.error(f"Error processing certificate: {e}")
ret['certerror'] = True
return ret | Parse a PEM-format SSL certificate.
Args:
rawcert (str): PEM-format SSL certificate
fqdn (str): expected FQDN for certificate
expiringdays (int): The certificate will be considered as "expiring" if within this number of days of expiry.
Returns:
dict: certificate details | parseCert | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def getSession(self) -> 'requests.sessions.Session':
"""Return requests session object.
Returns:
requests.sessions.Session: requests session
"""
session = requests.session()
if self.socksProxy:
session.proxies = {
'http': self.socksProxy,
'https': self.socksProxy,
}
return session | Return requests session object.
Returns:
requests.sessions.Session: requests session | getSession | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def removeUrlCreds(self, url: str) -> str:
"""Remove potentially sensitive strings (such as "key=..." and "password=...") from a string.
Used to remove potential credentials from URLs prior during logging.
Args:
url (str): URL
Returns:
str: Sanitized URL
"""
pats = {
r'key=\S+': "key=XXX",
r'pass=\S+': "pass=XXX",
r'user=\S+': "user=XXX",
r'password=\S+': "password=XXX"
}
ret = url
for pat in pats:
ret = re.sub(pat, pats[pat], ret, re.IGNORECASE)
return ret | Remove potentially sensitive strings (such as "key=..." and "password=...") from a string.
Used to remove potential credentials from URLs prior during logging.
Args:
url (str): URL
Returns:
str: Sanitized URL | removeUrlCreds | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def isValidLocalOrLoopbackIp(self, ip: str) -> bool:
"""Check if the specified IPv4 or IPv6 address is a loopback or local network IP address (IPv4 RFC1918 / IPv6 RFC4192 ULA).
Args:
ip (str): IPv4 or IPv6 address
Returns:
bool: IP address is local or loopback
"""
if not self.validIP(ip) and not self.validIP6(ip):
return False
if netaddr.IPAddress(ip).is_private():
return True
if netaddr.IPAddress(ip).is_loopback():
return True
return False | Check if the specified IPv4 or IPv6 address is a loopback or local network IP address (IPv4 RFC1918 / IPv6 RFC4192 ULA).
Args:
ip (str): IPv4 or IPv6 address
Returns:
bool: IP address is local or loopback | isValidLocalOrLoopbackIp | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def useProxyForUrl(self, url: str) -> bool:
"""Check if the configured proxy should be used to connect to a specified URL.
Args:
url (str): The URL to check
Returns:
bool: should the configured proxy be used?
Todo:
Allow using TOR only for .onion addresses
"""
host = self.urlFQDN(url).lower()
if not self.opts['_socks1type']:
return False
proxy_host = self.opts['_socks2addr']
if not proxy_host:
return False
proxy_port = self.opts['_socks3port']
if not proxy_port:
return False
# Never proxy requests to the proxy host
if host == proxy_host.lower():
return False
# Never proxy RFC1918 addresses on the LAN or the local network interface
if self.validIP(host):
if netaddr.IPAddress(host).is_private():
return False
if netaddr.IPAddress(host).is_loopback():
return False
# Never proxy local hostnames
else:
neverProxyNames = ['local', 'localhost']
if host in neverProxyNames:
return False
for s in neverProxyNames:
if host.endswith(s):
return False
return True | Check if the configured proxy should be used to connect to a specified URL.
Args:
url (str): The URL to check
Returns:
bool: should the configured proxy be used?
Todo:
Allow using TOR only for .onion addresses | useProxyForUrl | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def fetchUrl(
self,
url: str,
cookies: str = None,
timeout: int = 30,
useragent: str = "SpiderFoot",
headers: dict = None,
noLog: bool = False,
postData: str = None,
disableContentEncoding: bool = False,
sizeLimit: int = None,
headOnly: bool = False,
verify: bool = True
) -> dict:
"""Fetch a URL and return the HTTP response as a dictionary.
Args:
url (str): URL to fetch
cookies (str): cookies
timeout (int): timeout
useragent (str): user agent header
headers (dict): headers
noLog (bool): do not log request
postData (str): HTTP POST data
disableContentEncoding (bool): do not UTF-8 encode response body
sizeLimit (int): size threshold
headOnly (bool): use HTTP HEAD method
verify (bool): use HTTPS SSL/TLS verification
Returns:
dict: HTTP response
"""
if not url:
return None
result = {
'code': None,
'status': None,
'content': None,
'headers': None,
'realurl': url
}
url = url.strip()
try:
parsed_url = urllib.parse.urlparse(url)
except Exception:
self.debug(f"Could not parse URL: {url}")
return None
if parsed_url.scheme != 'http' and parsed_url.scheme != 'https':
self.debug(f"Invalid URL scheme for URL: {url}")
return None
request_log = []
proxies = dict()
if self.useProxyForUrl(url):
proxies = {
'http': self.socksProxy,
'https': self.socksProxy,
}
header = dict()
btime = time.time()
if isinstance(useragent, list):
header['User-Agent'] = random.SystemRandom().choice(useragent)
else:
header['User-Agent'] = useragent
# Add custom headers
if isinstance(headers, dict):
for k in list(headers.keys()):
header[k] = str(headers[k])
request_log.append(f"proxy={self.socksProxy}")
request_log.append(f"user-agent={header['User-Agent']}")
request_log.append(f"timeout={timeout}")
request_log.append(f"cookies={cookies}")
if sizeLimit or headOnly:
if noLog:
self.debug(f"Fetching (HEAD): {self.removeUrlCreds(url)} ({', '.join(request_log)})")
else:
self.info(f"Fetching (HEAD): {self.removeUrlCreds(url)} ({', '.join(request_log)})")
try:
hdr = self.getSession().head(
url,
headers=header,
proxies=proxies,
verify=verify,
timeout=timeout
)
except Exception as e:
if noLog:
self.debug(f"Unexpected exception ({e}) occurred fetching (HEAD only) URL: {url}", exc_info=True)
else:
self.error(f"Unexpected exception ({e}) occurred fetching (HEAD only) URL: {url}", exc_info=True)
return result
size = int(hdr.headers.get('content-length', 0))
newloc = hdr.headers.get('location', url).strip()
# Relative re-direct
if newloc.startswith("/") or newloc.startswith("../"):
newloc = SpiderFootHelpers.urlBaseUrl(url) + newloc
result['realurl'] = newloc
result['code'] = str(hdr.status_code)
if headOnly:
return result
if size > sizeLimit:
return result
if result['realurl'] != url:
if noLog:
self.debug(f"Fetching (HEAD): {self.removeUrlCreds(result['realurl'])} ({', '.join(request_log)})")
else:
self.info(f"Fetching (HEAD): {self.removeUrlCreds(result['realurl'])} ({', '.join(request_log)})")
try:
hdr = self.getSession().head(
result['realurl'],
headers=header,
proxies=proxies,
verify=verify,
timeout=timeout
)
size = int(hdr.headers.get('content-length', 0))
result['realurl'] = hdr.headers.get('location', result['realurl'])
result['code'] = str(hdr.status_code)
if size > sizeLimit:
return result
except Exception as e:
if noLog:
self.debug(f"Unexpected exception ({e}) occurred fetching (HEAD only) URL: {result['realurl']}", exc_info=True)
else:
self.error(f"Unexpected exception ({e}) occurred fetching (HEAD only) URL: {result['realurl']}", exc_info=True)
return result
try:
if postData:
if noLog:
self.debug(f"Fetching (POST): {self.removeUrlCreds(url)} ({', '.join(request_log)})")
else:
self.info(f"Fetching (POST): {self.removeUrlCreds(url)} ({', '.join(request_log)})")
res = self.getSession().post(
url,
data=postData,
headers=header,
proxies=proxies,
allow_redirects=True,
cookies=cookies,
timeout=timeout,
verify=verify
)
else:
if noLog:
self.debug(f"Fetching (GET): {self.removeUrlCreds(url)} ({', '.join(request_log)})")
else:
self.info(f"Fetching (GET): {self.removeUrlCreds(url)} ({', '.join(request_log)})")
res = self.getSession().get(
url,
headers=header,
proxies=proxies,
allow_redirects=True,
cookies=cookies,
timeout=timeout,
verify=verify
)
except requests.exceptions.RequestException as e:
self.error(f"Failed to connect to {url}: {e}")
return result
except Exception as e:
if noLog:
self.debug(f"Unexpected exception ({e}) occurred fetching URL: {url}", exc_info=True)
else:
self.error(f"Unexpected exception ({e}) occurred fetching URL: {url}", exc_info=True)
return result
try:
result['headers'] = dict()
result['realurl'] = res.url
result['code'] = str(res.status_code)
for header, value in res.headers.items():
result['headers'][str(header).lower()] = str(value)
# Sometimes content exceeds the size limit after decompression
if sizeLimit and len(res.content) > sizeLimit:
self.debug(f"Content exceeded size limit ({sizeLimit}), so returning no data just headers")
return result
refresh_header = result['headers'].get('refresh')
if refresh_header:
try:
newurl = refresh_header.split(";url=")[1]
except Exception as e:
self.debug(f"Refresh header '{refresh_header}' found, but not parsable: {e}")
return result
self.debug(f"Refresh header '{refresh_header}' found, re-directing to {self.removeUrlCreds(newurl)}")
return self.fetchUrl(
newurl,
cookies,
timeout,
useragent,
headers,
noLog,
postData,
disableContentEncoding,
sizeLimit,
headOnly
)
if disableContentEncoding:
result['content'] = res.content
else:
for encoding in ("utf-8", "ascii"):
try:
result["content"] = res.content.decode(encoding)
except UnicodeDecodeError:
pass
else:
break
else:
result["content"] = res.content
except Exception as e:
self.error(f"Unexpected exception ({e}) occurred parsing response for URL: {url}", exc_info=True)
result['content'] = None
result['status'] = str(e)
atime = time.time()
t = str(atime - btime)
self.info(f"Fetched {self.removeUrlCreds(url)} ({len(result['content'] or '')} bytes in {t}s)")
return result | Fetch a URL and return the HTTP response as a dictionary.
Args:
url (str): URL to fetch
cookies (str): cookies
timeout (int): timeout
useragent (str): user agent header
headers (dict): headers
noLog (bool): do not log request
postData (str): HTTP POST data
disableContentEncoding (bool): do not UTF-8 encode response body
sizeLimit (int): size threshold
headOnly (bool): use HTTP HEAD method
verify (bool): use HTTPS SSL/TLS verification
Returns:
dict: HTTP response | fetchUrl | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def checkDnsWildcard(self, target: str) -> bool:
"""Check if wildcard DNS is enabled for a domain by looking up a random subdomain.
Args:
target (str): domain
Returns:
bool: Domain returns DNS records for any subdomains
"""
if not target:
return False
randpool = 'bcdfghjklmnpqrstvwxyz3456789'
randhost = ''.join([random.SystemRandom().choice(randpool) for x in range(10)])
if not self.resolveHost(randhost + "." + target):
return False
return True | Check if wildcard DNS is enabled for a domain by looking up a random subdomain.
Args:
target (str): domain
Returns:
bool: Domain returns DNS records for any subdomains | checkDnsWildcard | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def cveInfo(self, cveId: str, sources: str = "circl,nist") -> (str, str):
"""Look up a CVE ID for more information in the first available source.
Args:
cveId (str): CVE ID, e.g. CVE-2018-15473
sources (str): Comma-separated list of sources to query. Options available are circl and nist
Returns:
(str, str): Appropriate event type and descriptive text
"""
sources = sources.split(",")
# VULNERABILITY_GENERAL is the generic type in case we don't have
# a real/mappable CVE.
eventType = "VULNERABILITY_GENERAL"
def cveRating(score: int) -> str:
if score == "Unknown":
return None
if score >= 0 and score <= 3.9:
return "LOW"
if score >= 4.0 and score <= 6.9:
return "MEDIUM"
if score >= 7.0 and score <= 8.9:
return "HIGH"
if score >= 9.0:
return "CRITICAL"
return None
for source in sources:
jsondata = self.cacheGet(f"{source}-{cveId}", 86400)
if not jsondata:
# Fetch data from source
if source == "nist":
ret = self.fetchUrl(f"https://services.nvd.nist.gov/rest/json/cve/1.0/{cveId}", timeout=5)
if source == "circl":
ret = self.fetchUrl(f"https://cve.circl.lu/api/cve/{cveId}", timeout=5)
if not ret:
continue
if not ret['content']:
continue
self.cachePut(f"{source}-{cveId}", ret['content'])
jsondata = ret['content']
try:
data = json.loads(jsondata)
if source == "circl":
score = data.get('cvss', 'Unknown')
rating = cveRating(score)
if rating:
eventType = f"VULNERABILITY_CVE_{rating}"
return (eventType, f"{cveId}\n<SFURL>https://nvd.nist.gov/vuln/detail/{cveId}</SFURL>\n"
f"Score: {score}\nDescription: {data.get('summary', 'Unknown')}")
if source == "nist":
try:
if data['result']['CVE_Items'][0]['impact'].get('baseMetricV3'):
score = data['result']['CVE_Items'][0]['impact']['baseMetricV3']['cvssV3']['baseScore']
else:
score = data['result']['CVE_Items'][0]['impact']['baseMetricV2']['cvssV2']['baseScore']
rating = cveRating(score)
if rating:
eventType = f"VULNERABILITY_CVE_{rating}"
except Exception:
score = "Unknown"
try:
descr = data['result']['CVE_Items'][0]['cve']['description']['description_data'][0]['value']
except Exception:
descr = "Unknown"
return (eventType, f"{cveId}\n<SFURL>https://nvd.nist.gov/vuln/detail/{cveId}</SFURL>\n"
f"Score: {score}\nDescription: {descr}")
except BaseException as e:
self.debug(f"Unable to parse CVE response from {source.upper()}: {e}")
continue
return (eventType, f"{cveId}\nScore: Unknown\nDescription: Unknown") | Look up a CVE ID for more information in the first available source.
Args:
cveId (str): CVE ID, e.g. CVE-2018-15473
sources (str): Comma-separated list of sources to query. Options available are circl and nist
Returns:
(str, str): Appropriate event type and descriptive text | cveInfo | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def googleIterate(self, searchString: str, opts: dict = None) -> dict:
"""Request search results from the Google API.
Will return a dict:
{
"urls": a list of urls that match the query string,
"webSearchUrl": url for Google results page,
}
Options accepted:
useragent: User-Agent string to use
timeout: API call timeout
Args:
searchString (str): Google search query
opts (dict): TBD
Returns:
dict: Search results as {"webSearchUrl": "URL", "urls": [results]}
"""
if not searchString:
return None
if opts is None:
opts = {}
search_string = searchString.replace(" ", "%20")
params = urllib.parse.urlencode({
"cx": opts["cse_id"],
"key": opts["api_key"],
})
response = self.fetchUrl(
f"https://www.googleapis.com/customsearch/v1?q={search_string}&{params}",
timeout=opts["timeout"],
)
if response['code'] != '200':
self.error("Failed to get a valid response from the Google API")
return None
try:
response_json = json.loads(response['content'])
except ValueError:
self.error("The key 'content' in the Google API response doesn't contain valid JSON.")
return None
if "items" not in response_json:
return None
# We attempt to make the URL params look as authentically human as possible
params = urllib.parse.urlencode({
"ie": "utf-8",
"oe": "utf-8",
"aq": "t",
"rls": "org.mozilla:en-US:official",
"client": "firefox-a",
})
return {
"urls": [str(k['link']) for k in response_json['items']],
"webSearchUrl": f"https://www.google.com/search?q={search_string}&{params}"
} | Request search results from the Google API.
Will return a dict:
{
"urls": a list of urls that match the query string,
"webSearchUrl": url for Google results page,
}
Options accepted:
useragent: User-Agent string to use
timeout: API call timeout
Args:
searchString (str): Google search query
opts (dict): TBD
Returns:
dict: Search results as {"webSearchUrl": "URL", "urls": [results]} | googleIterate | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def bingIterate(self, searchString: str, opts: dict = None) -> dict:
"""Request search results from the Bing API.
Will return a dict:
{
"urls": a list of urls that match the query string,
"webSearchUrl": url for bing results page,
}
Options accepted:
count: number of search results to request from the API
useragent: User-Agent string to use
timeout: API call timeout
Args:
searchString (str): Bing search query
opts (dict): TBD
Returns:
dict: Search results as {"webSearchUrl": "URL", "urls": [results]}
"""
if not searchString:
return None
if opts is None:
opts = {}
search_string = searchString.replace(" ", "%20")
params = urllib.parse.urlencode({
"responseFilter": "Webpages",
"count": opts["count"],
})
response = self.fetchUrl(
f"https://api.cognitive.microsoft.com/bing/v7.0/search?q={search_string}&{params}",
timeout=opts["timeout"],
useragent=opts["useragent"],
headers={"Ocp-Apim-Subscription-Key": opts["api_key"]},
)
if response['code'] != '200':
self.error("Failed to get a valid response from the Bing API")
return None
try:
response_json = json.loads(response['content'])
except ValueError:
self.error("The key 'content' in the bing API response doesn't contain valid JSON.")
return None
if ("webPages" in response_json and "value" in response_json["webPages"] and "webSearchUrl" in response_json["webPages"]):
return {
"urls": [result["url"] for result in response_json["webPages"]["value"]],
"webSearchUrl": response_json["webPages"]["webSearchUrl"],
}
return None | Request search results from the Bing API.
Will return a dict:
{
"urls": a list of urls that match the query string,
"webSearchUrl": url for bing results page,
}
Options accepted:
count: number of search results to request from the API
useragent: User-Agent string to use
timeout: API call timeout
Args:
searchString (str): Bing search query
opts (dict): TBD
Returns:
dict: Search results as {"webSearchUrl": "URL", "urls": [results]} | bingIterate | python | smicallef/spiderfoot | sflib.py | https://github.com/smicallef/spiderfoot/blob/master/sflib.py | MIT |
def do_debug(self, line):
"""debug
Short-cut command for set cli.debug = 1"""
if self.ownopts['cli.debug']:
val = "0"
else:
val = "1"
return self.do_set("cli.debug = " + val) | debug
Short-cut command for set cli.debug = 1 | do_debug | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_spool(self, line):
"""spool
Short-cut command for set cli.spool = 1/0"""
if self.ownopts['cli.spool']:
val = "0"
else:
val = "1"
if self.ownopts['cli.spool_file']:
return self.do_set("cli.spool = " + val)
self.edprint("You haven't set cli.spool_file. Set that before enabling spooling.")
return None | spool
Short-cut command for set cli.spool = 1/0 | do_spool | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_history(self, line):
"""history [-l]
Short-cut command for set cli.history = 1/0.
Add -l to just list the history."""
c = self.myparseline(line)
if '-l' in c[0]:
i = 0
while i < readline.get_current_history_length():
self.dprint(readline.get_history_item(i), plain=True)
i += 1
return None
if self.ownopts['cli.history']:
val = "0"
else:
val = "1"
return self.do_set("cli.history = " + val) | history [-l]
Short-cut command for set cli.history = 1/0.
Add -l to just list the history. | do_history | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_query(self, line):
"""query <SQL query>
Run an <SQL query> against the database."""
c = self.myparseline(line)
if len(c[0]) < 1:
self.edprint("Invalid syntax.")
return
query = ' '.join(c[0])
d = self.request(self.ownopts['cli.server_baseurl'] + "/query",
post={"query": query})
if not d:
return
j = json.loads(d)
if j[0] == "ERROR":
self.edprint(f"Error running your query: {j[1]}")
return
self.send_output(d, line) | query <SQL query>
Run an <SQL query> against the database. | do_query | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_ping(self, line):
"""ping
Ping the SpiderFoot server to ensure it's responding."""
d = self.request(self.ownopts['cli.server_baseurl'] + "/ping")
if not d:
return
s = json.loads(d)
if s[0] == "SUCCESS":
self.dprint(f"Server {self.ownopts['cli.server_baseurl']} responding.")
self.do_modules("", cacheonly=True)
self.do_types("", cacheonly=True)
else:
self.dprint(f"Something odd happened: {d}")
if s[1] != self.version:
self.edprint(f"Server and CLI version are not the same ({s[1]} / {self.version}). This could lead to unpredictable results!") | ping
Ping the SpiderFoot server to ensure it's responding. | do_ping | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_modules(self, line, cacheonly=False):
"""modules
List all available modules and their descriptions."""
d = self.request(self.ownopts['cli.server_baseurl'] + "/modules")
if not d:
return
if cacheonly:
j = json.loads(d)
for m in j:
self.modules.append(m['name'])
return
self.send_output(d, line, titles={"name": "Module name",
"descr": "Description"}) | modules
List all available modules and their descriptions. | do_modules | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_correlationrules(self, line, cacheonly=False):
"""correlations
List all available correlation rules and their descriptions."""
d = self.request(self.ownopts['cli.server_baseurl'] + "/correlationrules")
if not d:
return
if cacheonly:
j = json.loads(d)
for m in j:
self.correlationrules.append(m['name'])
return
self.send_output(d, line, titles={"id": "Correlation rule ID",
"name": "Name",
"risk": "Risk"}) | correlations
List all available correlation rules and their descriptions. | do_correlationrules | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_types(self, line, cacheonly=False):
"""types
List all available element types and their descriptions."""
d = self.request(self.ownopts['cli.server_baseurl'] + "/eventtypes")
if not d:
return
if cacheonly:
j = json.loads(d)
for t in j:
self.types.append(t[0])
return
self.send_output(
d,
line,
titles={
"1": "Element description",
"0": "Element name"
}
) | types
List all available element types and their descriptions. | do_types | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_load(self, line):
"""load <file>
Execute SpiderFoot CLI commands found in <file>."""
pass | load <file>
Execute SpiderFoot CLI commands found in <file>. | do_load | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_scaninfo(self, line):
"""scaninfo <sid> [-c]
Get status information for scan ID <sid>, optionally also its
configuration if -c is supplied."""
c = self.myparseline(line)
if len(c[0]) < 1:
self.edprint("Invalid syntax.")
return
sid = c[0][0]
d = self.request(self.ownopts['cli.server_baseurl'] + f"/scanopts?id={sid}")
if not d:
return
j = json.loads(d)
if len(j) == 0:
self.dprint("No such scan exists.")
return
out = list()
out.append(f"Name: {j['meta'][0]}")
out.append(f"ID: {sid}")
out.append(f"Target: {j['meta'][1]}")
out.append(f"Started: {j['meta'][3]}")
out.append(f"Completed: {j['meta'][4]}")
out.append(f"Status: {j['meta'][5]}")
if "-c" in c[0]:
out.append("Configuration:")
for k in sorted(j['config']):
out.append(f" {k} = {j['config'][k]}")
self.send_output("\n".join(out), line, total=False, raw=True) | scaninfo <sid> [-c]
Get status information for scan ID <sid>, optionally also its
configuration if -c is supplied. | do_scaninfo | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_scans(self, line):
"""scans [-x]
List all scans, past and present. -x for extended view."""
d = self.request(self.ownopts['cli.server_baseurl'] + "/scanlist")
if not d:
return
j = json.loads(d)
if len(j) == 0:
self.dprint("No scans exist.")
return
c = self.myparseline(line)
titles = dict()
if "-x" in c[0]:
titles = {
"0": "ID",
"1": "Name",
"2": "Target",
"4": "Started",
"5": "Finished",
"6": "Status",
"7": "Total Elements"
}
else:
titles = {
"0": "ID",
"2": "Target",
"6": "Status",
"7": "Total Elements"
}
self.send_output(d, line, titles=titles) | scans [-x]
List all scans, past and present. -x for extended view. | do_scans | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_correlations(self, line):
"""correlations <sid> [-c correlation_id]
Get the correlation results for scan ID <sid> and optionally the
events associated with a correlation result [correlation_id] to
get the results for a particular correlation."""
c = self.myparseline(line)
if len(c[0]) < 1:
self.edprint("Invalid syntax.")
return
post = {"id": c[0][0]}
if "-c" in c[0]:
post['correlationId'] = c[0][c[0].index("-c") + 1]
url = self.ownopts['cli.server_baseurl'] + "/scaneventresults"
titles = {
"10": "Type",
"1": "Data"
}
else:
url = self.ownopts['cli.server_baseurl'] + "/scancorrelations"
titles = {
"0": "ID",
"1": "Title",
"3": "Risk",
"7": "Data Elements"
}
d = self.request(url, post=post)
if not d:
return
j = json.loads(d)
if len(j) < 1:
self.dprint("No results.")
return
self.send_output(d, line, titles=titles) | correlations <sid> [-c correlation_id]
Get the correlation results for scan ID <sid> and optionally the
events associated with a correlation result [correlation_id] to
get the results for a particular correlation. | do_correlations | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_data(self, line):
"""data <sid> [-t type] [-x] [-u]
Get the scan data for scan ID <sid> and optionally the element
type [type] (e.g. EMAILADDR), [type]. Use -x for extended format.
Use -u for a unique set of results."""
c = self.myparseline(line)
if len(c[0]) < 1:
self.edprint("Invalid syntax.")
return
post = {"id": c[0][0]}
if "-t" in c[0]:
post["eventType"] = c[0][c[0].index("-t") + 1]
else:
post["eventType"] = "ALL"
if "-u" in c[0]:
url = self.ownopts['cli.server_baseurl'] + "/scaneventresultsunique"
titles = {
"0": "Data"
}
else:
url = self.ownopts['cli.server_baseurl'] + "/scaneventresults"
titles = {
"10": "Type",
"1": "Data"
}
d = self.request(url, post=post)
if not d:
return
j = json.loads(d)
if len(j) < 1:
self.dprint("No results.")
return
if "-x" in c[0]:
titles["0"] = "Last Seen"
titles["3"] = "Module"
titles["2"] = "Source Data"
d = d.replace("</SFURL>", "").replace("<SFURL>", "")
self.send_output(d, line, titles=titles) | data <sid> [-t type] [-x] [-u]
Get the scan data for scan ID <sid> and optionally the element
type [type] (e.g. EMAILADDR), [type]. Use -x for extended format.
Use -u for a unique set of results. | do_data | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_export(self, line):
"""export <sid> [-t type] [-f file]
Export the scan data for scan ID <sid> as type [type] to file [file].
Valid types: csv, json, gexf (default: json)."""
c = self.myparseline(line)
if len(c[0]) < 1:
self.edprint("Invalid syntax.")
return
export_format = 'json'
if '-t' in c[0]:
export_format = c[0][c[0].index("-t") + 1]
file = None
if '-f' in c[0]:
file = c[0][c[0].index("-f") + 1]
base_url = self.ownopts['cli.server_baseurl']
post = {"ids": c[0][0]}
if export_format not in ['json', 'csv', 'gexf']:
self.edprint(f"Invalid export format: {export_format}")
return
data = None
if export_format == 'json':
res = self.request(base_url + '/scanexportjsonmulti', post=post)
if not res:
self.dprint("No results.")
return
j = json.loads(res)
if len(j) < 1:
self.dprint("No results.")
return
data = json.dumps(j)
elif export_format == 'csv':
data = self.request(base_url + '/scaneventresultexportmulti', post=post)
elif export_format == 'gexf':
data = self.request(base_url + '/scanvizmulti', post=post)
if not data:
self.dprint("No results.")
return
self.send_output(data, line, titles=None, total=False, raw=True)
if file:
try:
with io.open(file, "w", encoding="utf-8", errors="ignore") as fp:
fp.write(data)
self.dprint(f"Wrote scan {c[0][0]} data to {file}")
except Exception as e:
self.edprint(f"Could not write scan {c[0][0]} data to file '{file}': {e}") | export <sid> [-t type] [-f file]
Export the scan data for scan ID <sid> as type [type] to file [file].
Valid types: csv, json, gexf (default: json). | do_export | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_logs(self, line):
"""logs <sid> [-l count] [-w]
Show the most recent [count] logs for a given scan ID, <sid>.
If no count is supplied, all logs are given.
If -w is supplied, logs will be streamed to the console until
Ctrl-C is entered."""
c = self.myparseline(line)
if len(c[0]) < 1:
self.edprint("Invalid syntax.")
return
sid = c[0][0]
limit = None
if "-l" in c[0]:
limit = c[0][c[0].index("-l") + 1]
if not limit.isdigit():
self.edprint(f"Invalid result count: {limit}")
return
limit = int(limit)
if "-w" not in c[0]:
d = self.request(
self.ownopts['cli.server_baseurl'] + "/scanlog",
post={'id': sid, 'limit': limit}
)
if not d:
return
j = json.loads(d)
if len(j) < 1:
self.dprint("No results.")
return
self.send_output(
d,
line,
titles={
"0": "Generated",
"1": "Type",
"2": "Source",
"3": "Message"
}
)
return
# Get the rowid of the latest log message
d = self.request(
self.ownopts['cli.server_baseurl'] + "/scanlog",
post={'id': sid, 'limit': '1'}
)
if not d:
return
j = json.loads(d)
if len(j) < 1:
self.dprint("No logs (yet?).")
return
rowid = j[0][4]
if not limit:
limit = 10
d = self.request(
self.ownopts['cli.server_baseurl'] + "/scanlog",
post={'id': sid, 'reverse': '1', 'rowId': rowid - limit}
)
if not d:
return
j = json.loads(d)
for r in j:
# self.send_output(str(r), line, total=False, raw=True)
if r[2] == "ERROR":
self.edprint(f"{r[1]}: {r[3]}")
else:
self.dprint(f"{r[1]}: {r[3]}")
try:
while True:
d = self.request(
self.ownopts['cli.server_baseurl'] + "/scanlog",
post={'id': sid, 'reverse': '1', 'rowId': rowid}
)
if not d:
return
j = json.loads(d)
for r in j:
if r[2] == "ERROR":
self.edprint(f"{r[1]}: {r[3]}")
else:
self.dprint(f"{r[1]}: {r[3]}")
rowid = str(r[4])
time.sleep(0.5)
except KeyboardInterrupt:
return | logs <sid> [-l count] [-w]
Show the most recent [count] logs for a given scan ID, <sid>.
If no count is supplied, all logs are given.
If -w is supplied, logs will be streamed to the console until
Ctrl-C is entered. | do_logs | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_start(self, line):
"""start <target> (-m m1,... | -t t1,... | -u case) [-n name] [-w]
Start a scan against <target> using modules m1,... OR looking
for types t1,...
OR by use case ("all", "investigate", "passive" and "footprint").
Scan be be optionally named [name], without a name the target
will be used.
Use -w to watch the logs from the scan. Ctrl-C to abort the
logging (but will not abort the scan).
"""
c = self.myparseline(line)
if len(c[0]) < 3:
self.edprint("Invalid syntax.")
return None
mods = ""
types = ""
usecase = ""
if "-m" in c[0]:
mods = c[0][c[0].index("-m") + 1]
if "-t" in c[0]:
# Scan by type
types = c[0][c[0].index("-t") + 1]
if "-u" in c[0]:
# Scan by use case
usecase = c[0][c[0].index("-u") + 1]
if not mods and not types and not usecase:
self.edprint("Invalid syntax.")
return None
target = c[0][0]
if "-n" in c[0]:
title = c[0][c[0].index("-n") + 1]
else:
title = target
post = {
"scanname": title,
"scantarget": target,
"modulelist": mods,
"typelist": types,
"usecase": usecase
}
d = self.request(
self.ownopts['cli.server_baseurl'] + "/startscan",
post=post
)
if not d:
return None
s = json.loads(d)
if s[0] == "SUCCESS":
self.dprint("Successfully initiated scan.")
self.dprint(f"Scan ID: {s[1]}")
else:
self.dprint(f"Unable to start scan: {s[1]}")
if "-w" in c[0]:
return self.do_logs(f"{s[1]} -w")
return None | start <target> (-m m1,... | -t t1,... | -u case) [-n name] [-w]
Start a scan against <target> using modules m1,... OR looking
for types t1,...
OR by use case ("all", "investigate", "passive" and "footprint").
Scan be be optionally named [name], without a name the target
will be used.
Use -w to watch the logs from the scan. Ctrl-C to abort the
logging (but will not abort the scan). | do_start | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_stop(self, line):
"""stop <sid>
Abort the running scan with scan ID, <sid>."""
c = self.myparseline(line)
try:
scan_id = c[0][0]
except BaseException:
self.edprint("Invalid syntax.")
return
self.request(self.ownopts['cli.server_baseurl'] + f"/stopscan?id={scan_id}")
self.dprint(f"Successfully requested scan {id} to stop. This could take some minutes to complete.") | stop <sid>
Abort the running scan with scan ID, <sid>. | do_stop | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_search(self, line):
"""search (look up 'find')
"""
return self.do_find(line) | search (look up 'find') | do_search | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_find(self, line):
"""find "<string|/regex/>" <[-s sid]|[-t type]> [-x]
Search for string/regex, limited to the scope of either a scan ID or
event type. -x for extended format."""
c = self.myparseline(line)
if len(c[0]) < 1:
self.edprint("Invalid syntax.")
return
val = c[0][0]
sid = None
etype = None
if "-t" in c[0]:
etype = c[0][c[0].index("-t") + 1]
if "-s" in c[0]:
sid = c[0][c[0].index("-s") + 1]
titles = {
"0": "Last Seen",
"1": "Data",
"3": "Module"
}
if "-x" in c[0]:
titles["2"] = "Source Data"
d = self.request(
self.ownopts['cli.server_baseurl'] + "/search",
post={'value': val, 'id': sid, 'eventType': etype}
)
if not d:
return
j = json.loads(d)
if not j:
self.dprint("No results found.")
return
if len(j) < 1:
self.dprint("No results found.")
return
self.send_output(d, line, titles) | find "<string|/regex/>" <[-s sid]|[-t type]> [-x]
Search for string/regex, limited to the scope of either a scan ID or
event type. -x for extended format. | do_find | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_summary(self, line):
"""summary <sid> [-t]
Summarise the results for a scan ID, <sid>. -t to only show
the element types."""
c = self.myparseline(line)
if len(c[0]) < 1:
self.edprint("Invalid syntax.")
return
sid = c[0][0]
if "-t" in c[0]:
titles = {"0": "Element Type"}
else:
titles = {
"0": "Element Type",
"1": "Element Description",
"3": "Total",
"4": "Unique"
}
d = self.request(self.ownopts['cli.server_baseurl'] + f"/scansummary?id={sid}&by=type")
if not d:
return
j = json.loads(d)
if not j:
self.dprint("No results found.")
return
if len(j) < 1:
self.dprint("No results found.")
return
self.send_output(d, line, titles, total=False) | summary <sid> [-t]
Summarise the results for a scan ID, <sid>. -t to only show
the element types. | do_summary | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_delete(self, line):
"""delete <sid>
Delete a scan with scan ID, <sid>."""
c = self.myparseline(line)
try:
scan_id = c[0][0]
except BaseException:
self.edprint("Invalid syntax.")
return
self.request(self.ownopts['cli.server_baseurl'] + f"/scandelete?id={scan_id}")
self.dprint(f"Successfully deleted scan {scan_id}.") | delete <sid>
Delete a scan with scan ID, <sid>. | do_delete | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_set(self, line):
"""set [opt [= <val>]]
Set a configuration variable in SpiderFoot."""
c = self.myparseline(line, replace=False)
cfg = None
val = None
if len(c[0]) > 0:
cfg = c[0][0]
if len(c[0]) > 2:
try:
val = c[0][2]
except BaseException:
self.edprint("Invalid syntax.")
return
# Local CLI config
if cfg and val:
if cfg.startswith('$'):
self.ownopts[cfg] = val
self.dprint(f"{cfg} set to {val}")
return
if cfg in self.ownopts:
if isinstance(self.ownopts[cfg], bool):
if val.lower() == "false" or val == "0":
val = False
else:
val = True
self.ownopts[cfg] = val
self.dprint(f"{cfg} set to {val}")
return
# Get the server-side config
d = self.request(self.ownopts['cli.server_baseurl'] + "/optsraw")
if not d:
self.edprint("Unable to obtain SpiderFoot server-side config.")
return
j = list()
serverconfig = dict()
token = "" # nosec
j = json.loads(d)
if j[0] == "ERROR":
self.edprint("Error fetching SpiderFoot server-side config.")
return
serverconfig = j[1]['data']
token = j[1]['token']
self.ddprint(str(serverconfig))
# Printing current config, not setting a value
if not cfg or not val:
ks = list(self.ownopts.keys())
ks.sort()
output = list()
for k in ks:
c = self.ownopts[k]
if isinstance(c, bool):
c = str(c)
if not cfg:
output.append({'opt': k, 'val': c})
continue
if cfg == k:
self.dprint(f"{k} = {c}", plain=True)
for k in sorted(serverconfig.keys()):
if type(serverconfig[k]) == list:
serverconfig[k] = ','.join(serverconfig[k])
if not cfg:
output.append({'opt': k, 'val': str(serverconfig[k])})
continue
if cfg == k:
self.dprint(f"{k} = {serverconfig[k]}", plain=True)
if len(output) > 0:
self.send_output(
json.dumps(output),
line,
{'opt': "Option", 'val': "Value"},
total=False
)
return
if val:
# submit all non-CLI vars to the SF server
confdata = dict()
found = False
for k in serverconfig:
if k == cfg:
serverconfig[k] = val
if type(val) == str:
if val.lower() == "true":
serverconfig[k] = "1"
if val.lower() == "false":
serverconfig[k] = "0"
found = True
if not found:
self.edprint("Variable not found, so not set.")
return
# Sanitize the data before sending it to the server
for k in serverconfig:
optstr = ":".join(k.split(".")[1:])
if type(serverconfig[k]) == bool:
if serverconfig[k]:
confdata[optstr] = "1"
else:
confdata[optstr] = "0"
if type(serverconfig[k]) == list:
# If set by the user, it must already be a
# string, not a list
confdata[optstr] = ','.join(serverconfig[k])
if type(serverconfig[k]) == int:
confdata[optstr] = str(serverconfig[k])
if type(serverconfig[k]) == str:
confdata[optstr] = serverconfig[k]
self.ddprint(str(confdata))
d = self.request(
self.ownopts['cli.server_baseurl'] + "/savesettingsraw",
post={'token': token, 'allopts': json.dumps(confdata)}
)
j = list()
if not d:
self.edprint("Unable to set SpiderFoot server-side config.")
return
j = json.loads(d)
if j[0] == "ERROR":
self.edprint(f"Error setting SpiderFoot server-side config: {j[1]}")
return
self.dprint(f"{cfg} set to {val}")
return
if cfg not in self.ownopts:
self.edprint("Variable not found, so not set. Did you mean to use a $ variable?")
return | set [opt [= <val>]]
Set a configuration variable in SpiderFoot. | do_set | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_shell(self, line):
"""shell
Run a shell command locally."""
self.dprint("Running shell command:" + str(line))
self.dprint(os.popen(line).read(), plain=True) # noqa: DUO106 | shell
Run a shell command locally. | do_shell | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_clear(self, line):
"""clear
Clear the screen."""
sys.stderr.write("\x1b[2J\x1b[H") | clear
Clear the screen. | do_clear | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_exit(self, line):
"""exit
Exit the SpiderFoot CLI."""
return True | exit
Exit the SpiderFoot CLI. | do_exit | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def do_EOF(self, line):
"""EOF (Ctrl-D)
Exit the SpiderFoot CLI."""
print("\n")
return True | EOF (Ctrl-D)
Exit the SpiderFoot CLI. | do_EOF | python | smicallef/spiderfoot | sfcli.py | https://github.com/smicallef/spiderfoot/blob/master/sfcli.py | MIT |
def start_scan(sfConfig: dict, sfModules: dict, args, loggingQueue) -> None:
"""Start scan
Args:
sfConfig (dict): SpiderFoot config options
sfModules (dict): modules
args (argparse.Namespace): command line args
loggingQueue (Queue): main SpiderFoot logging queue
"""
log = logging.getLogger(f"spiderfoot.{__name__}")
global dbh
global scanId
dbh = SpiderFootDb(sfConfig, init=True)
sf = SpiderFoot(sfConfig)
if not args.s:
log.error("You must specify a target when running in scan mode. Try --help for guidance.")
sys.exit(-1)
if args.x and not args.t:
log.error("-x can only be used with -t. Use --help for guidance.")
sys.exit(-1)
if args.x and args.m:
log.error("-x can only be used with -t and not with -m. Use --help for guidance.")
sys.exit(-1)
if args.r and (args.o and args.o not in ["tab", "csv"]):
log.error("-r can only be used when your output format is tab or csv.")
sys.exit(-1)
if args.H and (args.o and args.o not in ["tab", "csv"]):
log.error("-H can only be used when your output format is tab or csv.")
sys.exit(-1)
if args.D and args.o != "csv":
log.error("-D can only be used when using the csv output format.")
sys.exit(-1)
target = args.s
# Usernames and names - quoted on the commandline - won't have quotes,
# so add them.
if " " in target:
target = f"\"{target}\""
if "." not in target and not target.startswith("+") and '"' not in target:
target = f"\"{target}\""
targetType = SpiderFootHelpers.targetTypeFromString(target)
if not targetType:
log.error(f"Could not determine target type. Invalid target: {target}")
sys.exit(-1)
target = target.strip('"')
modlist = list()
if not args.t and not args.m and not args.u:
log.warning("You didn't specify any modules, types or use case, so all modules will be enabled.")
for m in list(sfModules.keys()):
if "__" in m:
continue
modlist.append(m)
signal.signal(signal.SIGINT, handle_abort)
# If the user is scanning by type..
# 1. Find modules producing that type
if args.t:
types = args.t
modlist = sf.modulesProducing(types)
newmods = deepcopy(modlist)
newmodcpy = deepcopy(newmods)
# 2. For each type those modules consume, get modules producing
while len(newmodcpy) > 0:
for etype in sf.eventsToModules(newmodcpy):
xmods = sf.modulesProducing([etype])
for mod in xmods:
if mod not in modlist:
modlist.append(mod)
newmods.append(mod)
newmodcpy = deepcopy(newmods)
newmods = list()
# Easier if scanning by module
if args.m:
modlist = list(filter(None, args.m.split(",")))
# Select modules if the user selected usercase
if args.u:
usecase = args.u[0].upper() + args.u[1:] # Make the first Letter Uppercase
for mod in sfConfig['__modules__']:
if usecase == 'All' or usecase in sfConfig['__modules__'][mod]['group']:
modlist.append(mod)
# Add sfp__stor_stdout to the module list
typedata = dbh.eventTypes()
types = dict()
for r in typedata:
types[r[1]] = r[0]
sfp__stor_stdout_opts = sfConfig['__modules__']['sfp__stor_stdout']['opts']
sfp__stor_stdout_opts['_eventtypes'] = types
if args.f:
if args.f and not args.t:
log.error("You can only use -f with -t. Use --help for guidance.")
sys.exit(-1)
sfp__stor_stdout_opts['_showonlyrequested'] = True
if args.F:
sfp__stor_stdout_opts['_requested'] = args.F.split(",")
sfp__stor_stdout_opts['_showonlyrequested'] = True
if args.o:
if args.o not in ["tab", "csv", "json"]:
log.error("Invalid output format selected. Must be 'tab', 'csv' or 'json'.")
sys.exit(-1)
sfp__stor_stdout_opts['_format'] = args.o
if args.t:
sfp__stor_stdout_opts['_requested'] = args.t.split(",")
if args.n:
sfp__stor_stdout_opts['_stripnewline'] = True
if args.r:
sfp__stor_stdout_opts['_showsource'] = True
if args.S:
sfp__stor_stdout_opts['_maxlength'] = args.S
if args.D:
sfp__stor_stdout_opts['_csvdelim'] = args.D
if args.x:
tmodlist = list()
modlist = list()
xmods = sf.modulesConsuming([targetType])
for mod in xmods:
if mod not in modlist:
tmodlist.append(mod)
# Remove any modules not producing the type requested
rtypes = args.t.split(",")
for mod in tmodlist:
for r in rtypes:
if not sfModules[mod]['provides']:
continue
if r in sfModules[mod].get('provides', []) and mod not in modlist:
modlist.append(mod)
if len(modlist) == 0:
log.error("Based on your criteria, no modules were enabled.")
sys.exit(-1)
modlist += ["sfp__stor_db", "sfp__stor_stdout"]
if sfConfig['__logging']:
log.info(f"Modules enabled ({len(modlist)}): {','.join(modlist)}")
cfg = sf.configUnserialize(dbh.configGet(), sfConfig)
# Debug mode is a variable that gets stored to the DB, so re-apply it
if args.debug:
cfg['_debug'] = True
else:
cfg['_debug'] = False
# If strict mode is enabled, filter the output from modules.
if args.x and args.t:
cfg['__outputfilter'] = args.t.split(",")
# Prepare scan output headers
if args.o == "json":
print("[", end='')
elif not args.H:
delim = "\t"
if args.o == "tab":
delim = "\t"
if args.o == "csv":
if args.D:
delim = args.D
else:
delim = ","
if args.r:
if delim == "\t":
headers = delim.join(["Source".ljust(30), "Type".ljust(45), "Source Data", "Data"])
else:
headers = delim.join(["Source", "Type", "Source Data", "Data"])
else:
if delim == "\t":
headers = delim.join(["Source".ljust(30), "Type".ljust(45), "Data"])
else:
headers = delim.join(["Source", "Type", "Data"])
print(headers)
# Start running a new scan
scanName = target
scanId = SpiderFootHelpers.genScanInstanceId()
try:
p = mp.Process(target=startSpiderFootScanner, args=(loggingQueue, scanName, scanId, target, targetType, modlist, cfg))
p.daemon = True
p.start()
except BaseException as e:
log.error(f"Scan [{scanId}] failed: {e}")
sys.exit(-1)
# Poll for scan status until completion
while True:
time.sleep(1)
info = dbh.scanInstanceGet(scanId)
if not info:
continue
if info[5] in ["ERROR-FAILED", "ABORT-REQUESTED", "ABORTED", "FINISHED"]:
# allow 60 seconds for post-scan correlations to complete
timeout = 60
p.join(timeout=timeout)
if (p.is_alive()):
log.error(f"Timeout reached ({timeout}s) waiting for scan {scanId} post-processing to complete.")
sys.exit(-1)
if sfConfig['__logging']:
log.info(f"Scan completed with status {info[5]}")
if args.o == "json":
print("]")
sys.exit(0)
return | Start scan
Args:
sfConfig (dict): SpiderFoot config options
sfModules (dict): modules
args (argparse.Namespace): command line args
loggingQueue (Queue): main SpiderFoot logging queue | start_scan | python | smicallef/spiderfoot | sf.py | https://github.com/smicallef/spiderfoot/blob/master/sf.py | MIT |
def start_web_server(sfWebUiConfig: dict, sfConfig: dict, loggingQueue=None) -> None:
"""Start the web server so you can start looking at results
Args:
sfWebUiConfig (dict): web server options
sfConfig (dict): SpiderFoot config options
loggingQueue (Queue): main SpiderFoot logging queue
"""
log = logging.getLogger(f"spiderfoot.{__name__}")
web_host = sfWebUiConfig.get('host', '127.0.0.1')
web_port = sfWebUiConfig.get('port', 5001)
web_root = sfWebUiConfig.get('root', '/')
cors_origins = sfWebUiConfig.get('cors_origins', [])
cherrypy.config.update({
'log.screen': False,
'server.socket_host': web_host,
'server.socket_port': int(web_port)
})
log.info(f"Starting web server at {web_host}:{web_port} ...")
# Enable access to static files via the web directory
conf = {
'/query': {
'tools.encode.text_only': False,
'tools.encode.add_charset': True,
},
'/static': {
'tools.staticdir.on': True,
'tools.staticdir.dir': 'static',
'tools.staticdir.root': f"{os.path.dirname(os.path.abspath(__file__))}/spiderfoot"
}
}
secrets = dict()
passwd_file = SpiderFootHelpers.dataPath() + '/passwd'
if os.path.isfile(passwd_file):
if not os.access(passwd_file, os.R_OK):
log.error("Could not read passwd file. Permission denied.")
sys.exit(-1)
with open(passwd_file, 'r') as f:
passwd_data = f.readlines()
for line in passwd_data:
if line.strip() == '':
continue
if ':' not in line:
log.error("Incorrect format of passwd file, must be username:password on each line.")
sys.exit(-1)
u = line.strip().split(":")[0]
p = ':'.join(line.strip().split(":")[1:])
if not u or not p:
log.error("Incorrect format of passwd file, must be username:password on each line.")
sys.exit(-1)
secrets[u] = p
if secrets:
log.info("Enabling authentication based on supplied passwd file.")
conf['/'] = {
'tools.auth_digest.on': True,
'tools.auth_digest.realm': web_host,
'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(secrets),
'tools.auth_digest.key': random.SystemRandom().randint(0, 99999999)
}
else:
warn_msg = "\n********************************************************************\n"
warn_msg += "Warning: passwd file contains no passwords. Authentication disabled.\n"
warn_msg += "Please consider adding authentication to protect this instance!\n"
warn_msg += "Refer to https://www.spiderfoot.net/documentation/#security.\n"
warn_msg += "********************************************************************\n"
log.warning(warn_msg)
using_ssl = False
key_path = SpiderFootHelpers.dataPath() + '/spiderfoot.key'
crt_path = SpiderFootHelpers.dataPath() + '/spiderfoot.crt'
if os.path.isfile(key_path) and os.path.isfile(crt_path):
if not os.access(crt_path, os.R_OK):
log.critical(f"Could not read {crt_path} file. Permission denied.")
sys.exit(-1)
if not os.access(key_path, os.R_OK):
log.critical(f"Could not read {key_path} file. Permission denied.")
sys.exit(-1)
log.info("Enabling SSL based on supplied key and certificate file.")
cherrypy.server.ssl_module = 'builtin'
cherrypy.server.ssl_certificate = crt_path
cherrypy.server.ssl_private_key = key_path
using_ssl = True
if using_ssl:
url = "https://"
else:
url = "http://"
if web_host == "0.0.0.0": # nosec
url = f"{url}127.0.0.1:{web_port}"
else:
url = f"{url}{web_host}:{web_port}{web_root}"
cors_origins.append(url)
cherrypy_cors.install()
cherrypy.config.update({
'cors.expose.on': True,
'cors.expose.origins': cors_origins,
'cors.preflight.origins': cors_origins
})
print("")
print("*************************************************************")
print(" Use SpiderFoot by starting your web browser of choice and ")
print(f" browse to {url}")
print("*************************************************************")
print("")
# Disable auto-reloading of content
cherrypy.engine.autoreload.unsubscribe()
cherrypy.quickstart(SpiderFootWebUi(sfWebUiConfig, sfConfig, loggingQueue), script_name=web_root, config=conf) | Start the web server so you can start looking at results
Args:
sfWebUiConfig (dict): web server options
sfConfig (dict): SpiderFoot config options
loggingQueue (Queue): main SpiderFoot logging queue | start_web_server | python | smicallef/spiderfoot | sf.py | https://github.com/smicallef/spiderfoot/blob/master/sf.py | MIT |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.