Compare commits

...
40 Commits
Author SHA1 Message Date
Dan Petro a390bf5644 Documentation for v3.0 training data 2021-04-22 14:01:04 -07:00
Dan Petro 92738b16a4 Add verify util script 2021-04-21 16:23:30 -07:00
Dan Petro 361b47bea8 Change resizer script to properly resize to 224x224, not 224x140 2021-04-21 08:22:57 -07:00
Dan Petro 616116d9a2 Documentation for parked domains 2021-04-20 15:28:52 -07:00
Dan Petro ecef89c4f9 Add extra field in prebuilt html template for parked domains 2021-04-20 14:46:29 -07:00
Dan Petro 818166f607 Support parked domains in the code 2021-04-02 13:56:46 -07:00
Dan Petro c50eae4dc4 Update readme with pretrained weights instructions 2021-03-01 16:49:40 -07:00
Dan Petro 3c8e161f82 Updated readme to say correct pretrained network name 2021-03-01 13:59:46 -07:00
Dan Petro 3b39a0c244 Merge branch 'application-label' 2021-03-01 13:57:53 -07:00
Dan Petro 42a4d6d037 Change readme dropbox link to v2 images/labels/pretrained model 2021-03-01 13:53:33 -07:00
Dan Petro c8eec3de4a Change name in HTML output file to "webapp" 2021-02-22 13:03:37 -07:00
Dan Petro 28234dac76 Trying logo again 2021-02-18 16:16:00 -07:00
Dan Petro bb46582e74 Minor logo readme fix 2021-02-18 16:15:07 -07:00
Dan Petro 33086f2f78 Add logo to readme 2021-02-18 16:13:46 -07:00
Dan Petro a3be157768 Change name from homepage to webapp 2021-02-18 14:51:16 -07:00
Dan Petro 8703982fe0 Readme clarification on label meanings 2021-02-12 11:51:34 -07:00
Dan Petro c90d90c07c Removed some commented code 2021-02-11 11:33:10 -07:00
Dan Petro 87e7ce3741 Fix bug where predict woulnd't load model from file
- Update some minor API things to not use deprecated features
2021-02-11 11:13:27 -07:00
Dan Petro ba6d6f0f49 Remove deprecated fit_generator() in tf2.0 2021-02-05 16:12:17 -07:00
Dan Petro 99fd136a0d Moved label init so that it's not necessary for prediction
- IE: So you don't need a labels.csv file if you just want to use a pretrained model
2021-02-04 15:50:20 -07:00
Dan Petro b7063bc517 De-lint, gitignore 2021-02-04 15:18:54 -07:00
Pi Esposito b031377f83 Added tensorboard callback for later visualization 2021-02-04 14:30:59 -07:00
Dan Petro b6e1f630f5 TF 2.0 is default now, so remove warning from readme 2021-02-04 14:27:27 -07:00
Dan Petro 08b452b798 Update requirements to mainline tensorflow
- 2.0 is live now! yay!
2019-10-22 15:13:44 -07:00
Dan Petro 667b44430d Removed debug print
- Accidentally left in
2019-08-15 11:42:45 -07:00
Dan Petro f0f7c81fe6 Added example images to the readme 2019-08-14 13:53:56 -07:00
Dan Petro e1bbcbd2a0 Removed some dangling keras references in the code
- Accidentally left some in I guess
2019-08-14 10:45:05 -07:00
Dan Petro 0879c1e1eb Updated readme to have pretrained network info 2019-08-06 16:02:58 -07:00
Dan Petro 496bd6fb86 Updated readme with more info 2019-08-06 14:44:04 -07:00
Dan Petro 66dbb9c1d7 Removed unused unit test files 2019-08-06 14:43:42 -07:00
Dan Petro 1eafce6f7c Fix for progress bar error
- Also added a quiet mode for the progress bar
2019-08-05 10:50:10 -07:00
Dan Petro 39ca494295 More prediction unit tests 2019-07-26 15:51:42 -07:00
Dan Petro 7db3c60ed8 Added some unit tests
- All prediction tests
2019-07-26 15:12:25 -07:00
Dan Petro 9023c0ee9f Minor readme changes 2019-07-17 10:37:31 -07:00
Dan Petro 03ebc806fd Added threshold option to heatmap generation 2019-07-17 10:36:29 -07:00
Dan Petro 9cff8c45a3 Changed images directory to "images/" from "images_224x224/"
- You can have whatever size you want
2019-07-02 14:12:16 -07:00
Dan Petro 3bdaf3cd1d Moved back to MobileNet v1
- v2 had bad performance. Don't know why yet.
2019-07-01 14:07:07 -07:00
Dan Petro 09ec368c1a Set pretrained layer back to trainable 2019-07-01 12:22:21 -07:00
Dan Petro 35e70e2fe6 Working build with tf.keras and tf2.0
- Was actually quite easy
2019-07-01 12:19:26 -07:00
Dan Petro 7bc9028a21 Removed Kera's predict generator, added a progress bar
- You don't need a folder within a folder anymore
 - predict_generator was just so terrible
 - Added a dependency, but it's not bad
2019-06-26 10:51:59 -07:00
31 changed files with 307 additions and 139 deletions

No files matched your search

+4
View File
@@ -116,3 +116,7 @@ venv.bak/
results.html
!requirements.txt
!requirements-gpu.txt
!tests/models/*
!tests/data/*
!docs/*
logs/*
+66 -4
View File
@@ -1,8 +1,44 @@
# Eyeballer
![Logo](/docs/eyeballer_logo.png)
Give those screenshots of yours a quick eyeballing.
Eyeballer is meant for large-scope network penetration tests where you need to find "interesting" targets from a huge set of web-based hosts. Go ahead and use your favorite screenshotting tool like normal (EyeWitness or GoWitness) and then run them through Eyeballer to tell you what's likely to contain vulnerabilities, and what isn't.
### Example Labels
| Old-Looking Sites | Login Pages |
| ------ |:-----:|
| ![Sample Old-looking Page](/docs/old-looking.png) | ![Sample Login Page](/docs/login.png) |
| Webapp | Custom 404's |
| ------ |:-----:|
| ![Sample Webapp](/docs/homepage.png) | ![Sample Custom 404](/docs/404.png) |
| Parked Domains |
| ------ |
| ![Sample Webapp](/docs/parked.png) |
## What the Labels Mean
**Old-Looking Sites**
Blocky frames, broken CSS, that certain "je ne sais quoi" of a website that looks like it was designed in the early 2000's. You know it when you see it. Old websites aren't just ugly, they're also typically super vulnerable. When you're looking to hack into something, these websites are a gold mine.
**Login Pages**
Login pages are valuable to pen testing, they indicate that there's additional functionality you don't currently have access to. It also means there's a simple follow-up process of credential enumeration attacks. You might think that you can set a simple heuristic to find login pages, but in practice it's really hard. Modern sites don't just use a simple input tag we can grep for.
**Webapp**
This tells you that there is a larger group of pages and functionality available here that can serve as surface area to attack. This is in contrast to a simple login page, with no other functionality. Or a default IIS landing page which has no other functionality. This label should indicate to you that there is a web application here to attack.
**Custom 404**
Modern sites love to have cutesy custom 404 pages with pictures of broken robots or sad looking dogs. Unfortunately, they also love to return HTTP 200 response codes while they do it. More often, the "404" page doesn't even contain the text "404" in it. These pages are typically uninteresting, despite having a lot going on visually, and Eyeballer can help you sift them out.
**Parked Domains**
Parked domains are websites that look real, but aren't valid attack surface. They're stand-in pages, usually devoid of any real functionality, consist almost entirely of ads, and are usually not run by our actual target. It's what you get when the domain specified is wrong or lapsed. Finding these pages and removing them from scope is really valuable over time.
## Setup
Download required packages on pip:
@@ -15,23 +51,47 @@ Or if you want GPU support:
sudo pip3 install -r requirements-gpu.txt
```
**NOTE**: Setting up a GPU for use with TensorFlow is way beyond the scope of this README. There's hardware compatibility to consider, drivers to install... There's a lot. So you're just going to have to figure this part out on your own if you want a GPU. But at least from a Python package perspective, the above requirements file has you covered.
**Pretrained Weights**
For the latest pretrained weights, check out the releases here on GitHub.
**Training Data** You can find our training data here:
https://www.dropbox.com/s/rpylhiv2g0kokts/eyeballer-3.0.zip?dl=1
There's two things you need from the training data:
1. `images/` folder, containing all the screenshots (resized down to 224x224)
2. `labels.csv` that has all the labels
3. `bishop-fox-pretrained-v2.h5` A pretrained weights file you can use right out of the box without training.
Copy all three into the root of the Eyeballer code tree.
## Predicting Labels
NOTE: For best results, make sure you screenshot your websites in a native 1.6x aspect ratio. IE: 1440x900. Eyeballer will scale the image down automatically to the right size for you, but if it's the wrong aspect ratio then it will squish in a way that will affect prediction performance.
To eyeball some screenshots, just run the "predict" mode:
```
eyeballer --weights YOUR_WEIGHTS.h5 predict YOUR_FILE.png
eyeballer.py --weights YOUR_WEIGHTS.h5 predict YOUR_FILE.png
```
Or for a whole directory of files:
```
eyeballer --weights YOUR_WEIGHTS.h5 predict PATH_TO/YOUR_FILES/
eyeballer.py --weights YOUR_WEIGHTS.h5 predict PATH_TO/YOUR_FILES/
```
Eyeballer will spit the results back to you in human readable format (a `results.html` file so you can browse it easily) and machine readable format (a `results.csv` file).
## Training
To train a new model, run:
```
eyeballer train
eyeballer.py train
```
You'll want a machine with a good GPU for this to run in a reasonable amount of time. Setting that up is outside the scope of this readme, however.
@@ -43,5 +103,7 @@ This will output a new model file (weights.h5 by default).
You just trained a new model, cool! Let's see how well it performs against some images it's never seen before, across a variety of metrics:
```
eyeballer --weights YOUR_WEIGHTS.h5 evaluate
eyeballer.py --weights YOUR_WEIGHTS.h5 evaluate
```
The output will describe the model's accuracy in both recall and precision for each of the program's labels. (Including "none of the above" as a pseudo-label)
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

+5 -6
View File
@@ -46,7 +46,7 @@ def predict(ctx, screenshot, heatmap, threshold):
if heatmap:
# Generate a heatmap
HeatMap(screenshot, model).generate()
HeatMap(screenshot, model, threshold).generate()
if not results:
print("Error: Input file does not exist")
@@ -54,17 +54,17 @@ def predict(ctx, screenshot, heatmap, threshold):
print(results)
else:
with open("results.csv", "w", newline="") as csvfile:
fieldnames = ["filename", "custom404", "login", "homepage", "oldlooking"]
fieldnames = ["filename", "custom404", "login", "webapp", "oldlooking", "parked"]
labelwriter = csv.DictWriter(csvfile, fieldnames=fieldnames)
labelwriter.writeheader()
labelwriter.writerows(results)
print("Output written to results.csv")
buildHTML(processResults(results))
buildHTML(processResults(results, threshold))
print("HTML written to results.html")
def processResults(results):
def processResults(results, threshold):
'''Filter the initial results dictionary and reformat it for use in JS.
Keyword arguments:
@@ -79,8 +79,7 @@ def processResults(results):
for label, label_info in result.items():
if (label == 'filename'):
pass
elif label_info:
elif label_info > threshold:
positiveTags.append(label)
jsResults[result['filename']] = positiveTags
+1 -1
View File
@@ -1,7 +1,7 @@
import numpy as np
from Augmentor.Operations import Operation
from keras.applications.mobilenet import preprocess_input
from tensorflow.keras.applications.mobilenet import preprocess_input
class EyeballerAugmentation(Operation):
+96 -83
View File
@@ -1,6 +1,7 @@
import os
import random
import sys
import progressbar
# Prevent Tkinter Dependency
import matplotlib
@@ -10,20 +11,13 @@ import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import Augmentor
import tensorflow as tf
from keras import regularizers
from keras.applications import MobileNet
from keras.applications.mobilenet import preprocess_input
from keras.callbacks import ModelCheckpoint
from keras.layers import Dropout, Dense
from keras.layers import GlobalAveragePooling2D
from keras.models import Model
from keras.optimizers import Adam
from keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications.mobilenet import preprocess_input
from sklearn.metrics import classification_report, accuracy_score, hamming_loss
from eyeballer.augmentation import EyeballerAugmentation
DATA_LABELS = ["custom404", "login", "homepage", "oldlooking"]
DATA_LABELS = ["custom404", "login", "webapp", "oldlooking", "parked"]
class EyeballModel:
@@ -33,11 +27,11 @@ class EyeballModel:
"""
graphs_directory = "graphs/"
checkpoint_file = "weights.h5"
image_dir = "images_224x224/"
image_dir = "images/"
image_width, image_height = 224, 224
input_shape = (image_width, image_height, 3)
def __init__(self, weights_file, print_summary=False, seed=None):
def __init__(self, weights_file, print_summary=False, seed=None, quiet=False):
"""Constructor for model class.
Keyword arguments:
@@ -45,41 +39,20 @@ class EyeballModel:
weights_file -- A filename for where to load the model's weights.
seed -- PRNG seed, useful for repeating a previous run and using the same data. Training/Validation split is determined randomly.
"""
# Build the model
base_model = MobileNet(weights='imagenet', include_top=False, input_shape=self.input_shape)
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(256, activation="relu", name="HiddenLayer1")(x)
x = Dropout(0.5)(x)
x = Dense(128, activation="relu", name="HiddenLayer2", kernel_regularizer=regularizers.l2(0.01))(x)
x = Dropout(0.2)(x)
output_layer = Dense(len(DATA_LABELS), activation="sigmoid", name="OutputLayer")(x)
self.model = Model(inputs=base_model.input, outputs=output_layer)
# # Build the model
self.model = tf.keras.Sequential()
pretrained_layer = tf.keras.applications.mobilenet.MobileNet(weights='imagenet', include_top=False, input_shape=self.input_shape)
self.model.add(pretrained_layer)
self.model.add(tf.keras.layers.GlobalAveragePooling2D())
self.model.add(tf.keras.layers.Dense(256, activation="relu"))
self.model.add(tf.keras.layers.Dropout(0.5))
self.model.add(tf.keras.layers.Dense(128, activation="relu"))
self.model.add(tf.keras.layers.Dropout(0.2))
self.model.add(tf.keras.layers.Dense(len(DATA_LABELS), activation="sigmoid"))
# for layer in base_model.layers:
# layer.trainable = False
adam = Adam(lr=0.0005)
self.model.compile(optimizer=adam, loss="binary_crossentropy", metrics=["accuracy"])
if print_summary:
print(self.model.summary())
# Pull out our labels for use in generators later
data = pd.read_csv("labels.csv")
self.training_labels = data.loc[data['evaluation'] == False] # noqa: E712
self.evaluation_labels = data.loc[data['evaluation'] == True] # noqa: E712
# Shuffle the training labels
self.random_seed = False
self.seed = seed
if self.seed is None:
self.random_seed = True
self.seed = random.randint(0, 999999)
print("No seed set, ", end='')
print("using seed: {}".format(self.seed))
random.seed(self.seed)
self.training_labels = self.training_labels.sample(frac=1)
self.model.compile(optimizer=tf.keras.optimizers.Adam(0.0005),
loss="binary_crossentropy",
metrics=["accuracy"])
if weights_file is not None and os.path.isfile(weights_file):
try:
@@ -93,6 +66,28 @@ class EyeballModel:
raise FileNotFoundError
print("WARN: No model loaded from file. Generating random model")
if print_summary:
print(self.model.summary())
self.quiet = quiet
self.seed = seed
def _init_labels(self):
# Pull out our labels for use in generators later
data = pd.read_csv("labels.csv")
self.training_labels = data.loc[data['evaluation'] == False] # noqa: E712
self.evaluation_labels = data.loc[data['evaluation'] == True] # noqa: E712
# Shuffle the training labels
self.random_seed = False
if self.seed is None:
self.random_seed = True
self.seed = random.randint(0, 999999)
print("No seed set, ", end='')
print("using seed: {}".format(self.seed))
random.seed(self.seed)
self.training_labels = self.training_labels.sample(frac=1)
# Data augmentation
augmentor = Augmentor.Pipeline()
augmentor.set_seed(self.seed)
@@ -117,7 +112,8 @@ class EyeballModel:
"""
print("Training with seed: " + str(self.seed))
data_generator = ImageDataGenerator(
self._init_labels()
data_generator = tf.keras.preprocessing.image.ImageDataGenerator(
preprocessing_function=self.preprocess_training_function,
validation_split=0.2,
samplewise_center=True)
@@ -132,7 +128,7 @@ class EyeballModel:
subset='training',
shuffle=True,
seed=self.seed,
class_mode="other")
class_mode="raw")
validation_generator = data_generator.flow_from_dataframe(
self.training_labels,
directory=self.image_dir,
@@ -143,13 +139,26 @@ class EyeballModel:
subset='validation',
shuffle=False,
seed=self.seed,
class_mode="other")
class_mode="raw")
# Model checkpoint - Saves model weights when validation accuracy improves
callbacks = [ModelCheckpoint(self.checkpoint_file, monitor='val_loss', verbose=1, save_best_only=True,
save_weights_only=True, mode='min')]
callbacks = [tf.keras.callbacks.ModelCheckpoint(self.checkpoint_file,
monitor='val_loss',
verbose=1,
save_best_only=True,
save_weights_only=True,
mode='min'),
tf.keras.callbacks.TensorBoard(log_dir='logs',
histogram_freq=2,
write_graph=True,
write_images=False,
update_freq='epoch',
profile_batch=2,
embeddings_freq=0,
embeddings_metadata=None),
]
history = self.model.fit_generator(
history = self.model.fit(
training_generator,
steps_per_epoch=len(training_generator.filenames) // batch_size,
epochs=epochs,
@@ -196,16 +205,16 @@ class EyeballModel:
result["filename"] = "custom-image"
result["custom404"] = prediction[0][0]
result["login"] = prediction[0][1]
result["homepage"] = prediction[0][2]
result["webapp"] = prediction[0][2]
result["oldlooking"] = prediction[0][3]
result["parked"] = prediction[0][4]
return result
def predict(self, path, threshold=0.5):
"""Predict the labels for a single file
"""Predict the labels for a single file or directory of files
Keyword arguments:
path -- The path to the file that we'll be evaluating.
NOTE: This actually has to be a directory containing a directory with our files. Because Keras is dumb. Don't ask.
path -- The path to the file(s) that we'll be evaluating.
"""
# Is this a single file, or a directory?
screenshots = []
@@ -217,29 +226,33 @@ class EyeballModel:
else:
raise FileNotFoundError
# Prepare the data
data_generator = ImageDataGenerator(
preprocessing_function=preprocess_input)
prediction_generator = data_generator.flow_from_directory(
directory=path,
target_size=(self.image_width, self.image_height),
shuffle=False,
class_mode=None)
predictions = self.model.predict_generator(
prediction_generator,
verbose=1,
steps=len(prediction_generator))
predictions = predictions > threshold
results = []
for filename, prediction in zip(prediction_generator.filenames, predictions):
bar = progressbar.ProgressBar()
if self.quiet:
bar = progressbar.NullBar()
for screenshot in bar(screenshots):
# Load the image into memory
img = None
try:
img = tf.keras.preprocessing.image.load_img(screenshot, target_size=(self.image_width, self.image_height))
img = tf.keras.preprocessing.image.img_to_array(img)
img = np.expand_dims(img, axis=0)
img = preprocess_input(img)
except IsADirectoryError:
print("\nWARN: Skipping directory: ", screenshot)
continue
except OSError:
print("\nWARN: Skipping empty or corrupt file: ", screenshot)
continue
prediction = self.model.predict(img, batch_size=1)
result = dict()
result["filename"] = path + filename
result["custom404"] = prediction[0]
result["login"] = prediction[1]
result["homepage"] = prediction[2]
result["oldlooking"] = prediction[3]
result["filename"] = screenshot
result["custom404"] = prediction[0][0]
result["login"] = prediction[0][1]
result["webapp"] = prediction[0][2]
result["oldlooking"] = prediction[0][3]
result["parked"] = prediction[0][4]
results.append(result)
return results
@@ -250,7 +263,8 @@ class EyeballModel:
threshold -- Value between 0->1. The cutoff where the numerical prediction becomes boolean. Default: 0.5
"""
# Prepare the data
data_generator = ImageDataGenerator(
self._init_labels()
data_generator = tf.keras.preprocessing.image.ImageDataGenerator(
preprocessing_function=preprocess_input)
evaluation_generator = data_generator.flow_from_dataframe(
self.evaluation_labels,
@@ -260,12 +274,12 @@ class EyeballModel:
target_size=(self.image_width, self.image_height),
shuffle=False,
batch_size=1,
class_mode="other")
class_mode="raw")
# If a seed was selected, then also evaluate on the validation set for that seed
if not self.random_seed:
print("Using validation set...")
# Data augmentation
data_generator = ImageDataGenerator(
data_generator = tf.keras.preprocessing.image.ImageDataGenerator(
preprocessing_function=self.preprocess_training_function,
samplewise_center=True,
validation_split=0.2)
@@ -279,17 +293,16 @@ class EyeballModel:
subset='validation',
shuffle=False,
seed=self.seed,
class_mode="other")
class_mode="raw")
else:
print("Using evaluation set...")
predictions = self.model.predict_generator(
predictions = self.model.predict(
evaluation_generator,
verbose=1,
steps=len(evaluation_generator))
self._save_prediction_histograms(predictions)
print("predictions: ", type(predictions))
predictions = predictions > threshold
ground_truth = self.evaluation_labels[DATA_LABELS].to_numpy()
filenames = self.evaluation_labels[["filename"]].to_numpy()
+10 -8
View File
@@ -1,17 +1,18 @@
import numpy as np
import math
from keras.preprocessing import image
import tensorflow as tf
from copy import deepcopy
from matplotlib import pyplot as plt
from eyeballer.model import DATA_LABELS
class HeatMap():
def __init__(self, screenshot_path, model, boxsize=28, step=7):
def __init__(self, screenshot_path, model, threshold=0.5, boxsize=28, step=7):
self.model = model
img = image.load_img(screenshot_path, target_size=(self.model.image_width, self.model.image_height))
img = image.img_to_array(img)
img = tf.keras.preprocessing.image.load_img(screenshot_path, target_size=(self.model.image_width, self.model.image_height))
img = tf.keras.preprocessing.image.img_to_array(img)
self.screenshot = img
self.boxsize = boxsize
@@ -20,6 +21,7 @@ class HeatMap():
self.y = 0
self.screenshot_path = screenshot_path
self.gamma = 3
self.threshold = threshold
def generate(self, output_file="heatmap.png"):
""" Make a single heatmap image and return it """
@@ -30,11 +32,11 @@ class HeatMap():
for label in DATA_LABELS:
boxsize = self.boxsize
# Ignore this label if it didn't predict positively (true label)
if results[label] > 0.5:
if results[label] > self.threshold:
worst_score = 1
while worst_score > 0.5:
while worst_score > self.threshold:
heatmap, worst_score = self._get_heatmap(label, boxsize)
if worst_score > 0.5:
if worst_score > self.threshold:
boxsize += 28
print("Didn't get a good image for {}. Trying again with a bigger boxsize: {}".format(label, boxsize))
else:
@@ -42,7 +44,7 @@ class HeatMap():
labels.append(label)
plt.figure()
screenshot_image = image.load_img(self.screenshot_path, target_size=(self.model.image_width, self.model.image_width))
screenshot_image = tf.keras.preprocessing.image.load_img(self.screenshot_path, target_size=(self.model.image_width, self.model.image_width))
_, subplots = plt.subplots(1, len(heatmaps))
# This is a little janky, but matplotlib returns a list above if there's multiple subplots, and just a single subplot if there's only one
# it would have been easier if it was always a list. But alas
+2 -1
View File
@@ -7,8 +7,9 @@
<button class="btn all" onclick="filterSelection('all')"> Show all</button>
<button class="btn" onclick="filterSelection('custom404')"> 404</button>
<button class="btn" onclick="filterSelection('login')"> Login</button>
<button class="btn" onclick="filterSelection('homepage')"> Home Page</button>
<button class="btn" onclick="filterSelection('webapp')"> Web Application</button>
<button class="btn" onclick="filterSelection('oldlooking')"> Old Looking</button>
<button class="btn" onclick="filterSelection('parked')"> Parked Domain</button>
<select onchange="numOnPage=this.value; filterSelection([]);" style="float:right; margin:5px; margin-right:30px; height:30px; width:auto;">
<option value="25">25</option>
<option value="50">50</option>
+2 -1
View File
@@ -6,4 +6,5 @@ pandas
pillow
sklearn
tensorflow-gpu
keras
jinja2
progressbar2
+1 -1
View File
@@ -6,5 +6,5 @@ pandas
pillow
sklearn
tensorflow
keras
jinja2
progressbar2
-1
View File
@@ -1 +0,0 @@
#TODO
+87 -29
View File
@@ -1,15 +1,23 @@
import errno
import os
import unittest
import sys
from eyeballer.model import EyeballModel
from eyeballer.visualization import HeatMap
class PredictTest(unittest.TestCase):
def setUp(self):
weights_file = "latest_weights.h5"
class DummyFile(object):
def write(self, x): pass
def flush(self): pass
sys.stdout = DummyFile()
weights_file = "tests/models/test_weights.h5"
if not os.path.isfile(weights_file):
print("Error: Symlink the latest weights file to 'latest_weights.h5'")
print("Error: Symlink the latest weights file to " + weights_file)
raise FileNotFoundError(
errno.ENOENT,
os.strerror(errno.ENOENT),
@@ -18,7 +26,8 @@ class PredictTest(unittest.TestCase):
model_kwargs = {
"weights_file": weights_file,
"print_summary": False,
"seed": None
"seed": None,
"quiet": True
}
self.model = EyeballModel(**model_kwargs)
@@ -26,11 +35,12 @@ class PredictTest(unittest.TestCase):
model_kwargs = {
"weights_file": None,
"print_summary": False,
"seed": 12345678
"seed": 12345678,
"quiet": True
}
same_seed_model = EyeballModel(**model_kwargs)
screenshot = "tests/data/test.png"
screenshot = "tests/data/404.png"
results_one = self.model.predict(screenshot)
results_two = same_seed_model.predict(screenshot)
@@ -41,44 +51,92 @@ class PredictTest(unittest.TestCase):
model_kwargs = {
"weights_file": None,
"print_summary": False,
"seed": 12345678
"seed": 12345678,
"quiet": True
}
same_seed_model = EyeballModel(**model_kwargs)
screenshot = "tests/data/test.png"
screenshot = "tests/data/404.png"
results_one = same_seed_model.predict(screenshot)
results_two = same_seed_model.predict(screenshot)
self.assertEquals(results_one, results_two)
def get_prediction_by_name(self, results):
prediction = None
max_val = 0.0
print(results)
for k, v in results[0].items():
if not isinstance(v, str) and v > max_val:
prediction = k
max_val = v
return prediction
self.assertEqual(results_one, results_two)
def test_predict_custom404(self):
screenshot = "tests/data/custom404.png"
results = self.model.predict(screenshot)
self.assertEqual(self.get_prediction_by_name(results), "custom404")
screenshot = "tests/data/404.png"
results = self.model.predict(screenshot)[0]
self.assertGreater(results["custom404"], 0.5)
def test_predict_not_custom404(self):
screenshot = "tests/data/nothing.png"
results = self.model.predict(screenshot)[0]
self.assertLess(results["custom404"], 0.5)
def test_predict_login(self):
screenshot = "tests/data/login.png"
results = self.model.predict(screenshot)
self.assertEqual(self.get_prediction_by_name(results), "login")
results = self.model.predict(screenshot)[0]
self.assertGreater(results["login"], 0.5)
def test_predict_not_login(self):
screenshot = "tests/data/nothing.png"
results = self.model.predict(screenshot)[0]
print(screenshot, results)
self.assertLess(results["login"], 0.5)
def test_predict_homepage(self):
screenshot = "tests/data/homepage.png"
results = self.model.predict(screenshot)
self.assertEqual(self.get_prediction_by_name(results), "homepage")
results = self.model.predict(screenshot)[0]
self.assertGreater(results["homepage"], 0.5)
def test_predict_not_homepage(self):
screenshot = "tests/data/nothing.png"
results = self.model.predict(screenshot)[0]
self.assertLess(results["homepage"], 0.5)
def test_predict_oldlooking(self):
screenshot = "tests/data/oldlooking.png"
results = self.model.predict(screenshot)
self.assertEqual(self.get_prediction_by_name(results), "oldlooking")
screenshot = "tests/data/old-looking.png"
results = self.model.predict(screenshot)[0]
self.assertGreater(results["oldlooking"], 0.5)
def test_predict_not_oldlooking(self):
screenshot = "tests/data/nothing.png"
results = self.model.predict(screenshot)[0]
self.assertLess(results["oldlooking"], 0.5)
def test_file_doesnt_exist(self):
screenshot = "tests/data/doesnotexist.png"
try:
self.model.predict(screenshot)[0]
self.fail("FileNotFoundError was expected but not found")
except FileNotFoundError:
pass
def test_folder(self):
screenshots = "tests/data/"
results = self.model.predict(screenshots)
self.assertEqual(len(results), 7)
def test_file_is_empty(self):
"""
We're just testing that it doesn't crash, basically
"""
screenshot = "tests/data/empty.png"
self.model.predict(screenshot)
def test_file_is_invalid(self):
"""
We're just testing that it doesn't crash, basically
"""
screenshot = "tests/data/invalid.png"
self.model.predict(screenshot)
def test_heatmap(self):
screenshot = "tests/data/login.png"
HeatMap(screenshot, self.model, 0.5)
screenshot = "tests/data/404.png"
HeatMap(screenshot, self.model, 0.5)
screenshot = "tests/data/empty.png"
HeatMap(screenshot, self.model, 0.5)
-1
View File
@@ -1 +0,0 @@
#TODO
+1 -1
View File
@@ -1 +1 @@
from tests.PredictTest import *
from tests.PredictTest import * # noqa
Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

View File
Whitespace-only changes.
Binary file not shown.

After

Width:  |  Height:  |  Size: 479 KiB

+1
View File
@@ -0,0 +1 @@
THIS TEXT IS NOT A VALID PNG
Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 347 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 277 B

Binary file not shown.
+3 -2
View File
@@ -1,7 +1,8 @@
#!/bin/bash
# Converts full-size images to a given size (replacing the originals)
for f in images_full_size/*
for f in images/*
do
convert -resize 224x224 $f $f
echo $f
convert -resize 224x224\! $f $f
done
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env python3
import csv
import random
from os import listdir
from os.path import isfile, join
with open("labels.csv", newline="") as csvfile:
# Get the header labels
csvreader = csv.DictReader(csvfile)
# fieldnames = next(csvreader)
file_list = [f for f in listdir("images") if isfile(join("images", f))]
label_list = []
for row in csvreader:
label_list.append(row["filename"])
# Loop through the file
print("Rows in labels.csv, but no image exists:")
for label in label_list:
if label not in file_list:
print(row["filename"])
print("Images that exist, but don't have labels:")
i = 0
for image in file_list:
if image not in label_list:
print(image)