Skip to content

Commit 190ff69

Browse files
authored
Merge pull request #126 from rackerlabs/issue-126-small-updates
Issue 126 small updates
2 parents 5aa7b1e + d8bfde4 commit 190ff69

File tree

10 files changed

+97
-59
lines changed

10 files changed

+97
-59
lines changed

README.md

+7-5
Original file line numberDiff line numberDiff line change
@@ -368,10 +368,10 @@ the current datetime.
368368

369369
```bash
370370
# Not using SSH tunnels.
371-
curl -k -X GET -H 'Authorization: Token <VALID API TOKEN>' https://192.168.1.99:443/api/scheduled_scans?format=json
371+
curl -k -X GET -H 'Authorization: Token <VALID API TOKEN>' https://192.168.1.99:443/api/scheduled_scans
372372

373373
# Using SSH tunnels.
374-
curl -k -X GET -H 'Authorization: Token <VALID API TOKEN>' https://127.0.0.1:4430/api/scheduled_scans?format=json
374+
curl -k -X GET -H 'Authorization: Token <VALID API TOKEN>' https://127.0.0.1:4430/api/scheduled_scans
375375
```
376376

377377
You can also log into the webapp using the agent name and password and browse to `/api/?format=json` to view any scan
@@ -391,17 +391,19 @@ jobs. The username and agent name are the same from the webapp's point of view.
391391

392392
### Master Troubleshooting
393393

394-
Ensure SSH tunnels setup in `/etc/rc.local` are up.
394+
1). Ensure SSH tunnels setup in `/etc/rc.local` are up.
395395

396396
```bash
397397
netstat -nat | egrep "192.168.1.100|192.168.1.101"
398398
ps -ef | egrep autossh
399399
```
400400

401-
Check nginx logs for agent name in User-Agent field to determine which agents are calling home.
401+
2). Django logs can be found here: `/var/log/webapp/django_scantron.log`
402+
403+
3). Check nginx logs for agent name in User-Agent field to determine which agents are calling home.
402404
nginx logs: `tail -f /var/log/nginx/{access,error}.log`
403405

404-
uwsgi logs: `/home/scantron/master/logs`
406+
4). uwsgi logs: `/home/scantron/master/logs`
405407

406408
### Known issues with Master NFS share
407409

agent/modules/api.py

+27-29
Original file line numberDiff line numberDiff line change
@@ -20,16 +20,20 @@ def check_for_scan_jobs(config_data):
2020
"""Check for new scans through the API."""
2121

2222
# Build URL to pull new scan jobs. Server determines jobs based off agent (user) making request.
23-
url = "{}:{}/api/scheduled_scans?format=json".format(
24-
config_data["master_address"], config_data["master_port"]
25-
)
23+
master_address = config_data["master_address"]
24+
master_port = config_data["master_port"]
25+
api_token = config_data["api_token"]
26+
27+
url = f"{master_address}:{master_port}/api/scheduled_scans"
2628
logger.ROOT_LOGGER.info("check_for_scans URL: {}".format(url))
2729

2830
# Update User-Agent and add API token.
31+
# fmt:off
2932
headers = {
3033
"user-agent": config_data["scan_agent"],
31-
"Authorization": "Token {}".format(config_data["api_token"]),
34+
"Authorization": f"Token {api_token}",
3235
}
36+
# fmt:on
3337

3438
try:
3539
# Make the HTTP GET request.
@@ -40,53 +44,47 @@ def check_for_scan_jobs(config_data):
4044
return response.json()
4145

4246
else:
43-
logger.ROOT_LOGGER.error(
44-
"Could not access {}. HTTP status code: {}".format(
45-
url, response.status_code
46-
)
47-
)
47+
logger.ROOT_LOGGER.error(f"Could not access {url}. HTTP status code: {response.status_code}")
4848
return None
4949

5050
except Exception as e:
51-
logger.ROOT_LOGGER.error(
52-
"api.check_for_scans function exception: {}".format(e)
53-
)
51+
logger.ROOT_LOGGER.error(f"api.check_for_scan_jobs function exception: {e}")
5452

5553

5654
def update_scan_information(config_data, scan_job, update_info):
5755
"""Update scan information using a PATCH API request."""
5856

57+
master_address = config_data["master_address"]
58+
master_port = config_data["master_port"]
59+
api_token = config_data["api_token"]
60+
scan_agent = config_data["scan_agent"]
61+
scan_job_id = scan_job["id"]
62+
5963
# Build URL to update scan job.
60-
url = "{}:{}/api/scheduled_scans/{}".format(
61-
config_data["master_address"], config_data["master_port"], scan_job["id"]
62-
)
63-
logger.ROOT_LOGGER.info("update_scan_information URL: {}".format(url))
64+
url = f"{master_address}:{master_port}/api/scheduled_scans/{scan_job_id}"
65+
logger.ROOT_LOGGER.info(f"update_scan_information URL: {url}")
6466

65-
# Update the User-Agent, add API token, and add Content-Type.
67+
# Update the User-Agent, API token, and Content-Type.
68+
# fmt:off
6669
headers = {
67-
"user-agent": config_data["scan_agent"],
68-
"Authorization": "Token {}".format(config_data["api_token"]),
70+
"user-agent": scan_agent,
71+
"Authorization": f"Token {api_token}",
6972
"Content-Type": "application/json",
7073
}
74+
# fmt:on
7175

7276
# Make the HTTP PATCH request.
73-
response = requests.patch(
74-
url, headers=headers, verify=False, timeout=15, json=update_info
75-
)
77+
response = requests.patch(url, headers=headers, verify=False, timeout=15, json=update_info)
7678

7779
if response.status_code == 200:
7880
logger.ROOT_LOGGER.info(
79-
"Successfully updated scan information for scan ID {} with data {}".format(
80-
scan_job["id"], update_info
81-
)
81+
f"Successfully updated scan information for scan ID {scan_job_id} with data {update_info}"
8282
)
8383
return None
8484

8585
else:
8686
logger.ROOT_LOGGER.error(
87-
"Could not access {} or failed to update scan ID {}. HTTP status code: {}".format(
88-
url, scan_job["id"], response.status_code
89-
)
87+
f"Could not access {url} or failed to update scan ID {scan_job_id}. HTTP status code: {response.status_code}"
9088
)
91-
logger.ROOT_LOGGER.error("Response content: {}".format(response.content))
89+
logger.ROOT_LOGGER.error(f"Response content: {response.content}".format())
9290
return None

ansible-playbooks/roles/master/tasks/main.yml

+16
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,22 @@
151151

152152
# Django
153153
########
154+
- name: Create /var/log/webapp folder.
155+
file:
156+
path: /var/log/webapp
157+
state: directory
158+
owner: root
159+
group: root
160+
mode: 0755
161+
162+
- name: Create /var/log/webapp/django_scantron.log file.
163+
file:
164+
path: /var/log/webapp/django_scantron.log
165+
state: touch
166+
owner: www-data
167+
group: www-data
168+
mode: 0660
169+
154170
- name: Update manage.py with local/production environment variable.
155171
template:
156172
src: templates/manage.py.j2

ansible-playbooks/roles/master/templates/production.py.j2

+21-21
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
"""
22
Production Configuration
3-
43
"""
54
# export DJANGO_SETTINGS_MODULE="config.settings.production"
65
from .base import * # noqa
@@ -17,10 +16,8 @@ DEBUG = False
1716

1817
# set this to 60 seconds and then to 518400 when you can prove it works
1918
# SECURE_HSTS_SECONDS = 60
20-
# SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool(
21-
# 'DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS', default=True)
22-
# SECURE_CONTENT_TYPE_NOSNIFF = env.bool(
23-
# 'DJANGO_SECURE_CONTENT_TYPE_NOSNIFF', default=True)
19+
# SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool("DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True)
20+
# SECURE_CONTENT_TYPE_NOSNIFF = env.bool("DJANGO_SECURE_CONTENT_TYPE_NOSNIFF", default=True)
2421
SECURE_BROWSER_XSS_FILTER = True
2522
SESSION_COOKIE_SECURE = True
2623
SESSION_COOKIE_HTTPONLY = True
@@ -43,30 +40,33 @@ ALLOWED_HOSTS = [
4340

4441
# LOGGING CONFIGURATION
4542
# ------------------------------------------------------------------------------
46-
# See: https://docs.djangoproject.com/en/dev/ref/settings/#logging
47-
# A sample logging configuration. The only tangible logging
48-
# performed by this configuration is to send an email to
49-
# the site admins on every HTTP 500 error when DEBUG=False.
50-
# See https://docs.djangoproject.com/en/dev/topics/logging for
51-
# more details on how to customize your logging configuration.
43+
# fmt: off
5244
LOGGING = {
5345
"version": 1,
5446
"disable_existing_loggers": False,
55-
"filters": {"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}},
56-
"formatters": {"verbose": {"format": "%(levelname)s %(asctime)s %(module)s " "%(process)d %(thread)d %(message)s"}},
47+
"formatters": {
48+
"verbose": {
49+
"format": "%(asctime)s %(levelname)s %(module)s " "%(process)d %(thread)d %(message)s",
50+
},
51+
},
5752
"handlers": {
58-
"mail_admins": {
59-
"level": "ERROR",
60-
"filters": ["require_debug_false"],
61-
"class": "django.utils.log.AdminEmailHandler",
53+
"file": {
54+
"level": "DEBUG",
55+
"class": "logging.handlers.RotatingFileHandler",
56+
"filename": "/var/log/webapp/django_scantron.log",
57+
"maxBytes": 1024 * 1024 * 15, # 15MB
58+
"backupCount": 10,
59+
"formatter": "verbose",
6260
},
63-
"console": {"level": "DEBUG", "class": "logging.StreamHandler", "formatter": "verbose"},
6461
},
6562
"loggers": {
66-
"django.request": {"handlers": ["mail_admins"], "level": "ERROR", "propagate": True},
67-
"django.security.DisallowedHost": {"level": "ERROR", "handlers": ["console", "mail_admins"], "propagate": True},
63+
"django": {
64+
"handlers": ["file"],
65+
"level": "DEBUG",
66+
"propagate": True,
67+
},
6868
},
6969
}
70-
70+
# fmt: on
7171
# Your production stuff: Below this line define 3rd party library settings
7272
# ------------------------------------------------------------------------------

master/django_scantron/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = "1.7"
1+
__version__ = "1.8"

master/django_scantron/admin.py

+18
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,22 @@
11
from django.contrib import admin
2+
# from django.contrib.auth.decorators import login_required
3+
from django.contrib.sessions.models import Session
24
from . import models
35

46

7+
# Taken from django-all-auth: https://django-allauth.readthedocs.io/en/latest/advanced.html#admin
8+
# "require users to login before going to the Django admin site’s login page"
9+
# admin.site.login = login_required(admin.site.login)
10+
11+
12+
# View sessions in Django Admin.
13+
class SessionAdmin(admin.ModelAdmin):
14+
def _session_data(self, obj):
15+
return obj.get_decoded()
16+
17+
list_display = ["session_key", "_session_data", "expire_date"]
18+
19+
520
class AgentAdmin(admin.ModelAdmin):
621

722
list_display = ("id", "scan_agent", "description", "api_token", "last_checkin")
@@ -32,6 +47,7 @@ class ScheduledScanAdmin(admin.ModelAdmin):
3247
"site_name",
3348
"site_name_id",
3449
"scan_id",
50+
"start_time",
3551
"scan_agent",
3652
"scan_agent_id",
3753
"start_datetime",
@@ -52,6 +68,8 @@ def _register(model, admin_class):
5268
admin.site.register(model, admin_class)
5369

5470

71+
_register(Session, SessionAdmin)
72+
5573
_register(models.Agent, AgentAdmin)
5674
_register(models.ScanCommand, ScanCommandAdmin)
5775
_register(models.Scan, ScanAdmin)

master/django_scantron/models.py

+1
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,7 @@ class ScheduledScan(models.Model):
203203
scan_id = models.IntegerField(
204204
validators=[MinValueValidator(1, message="Scan ID must be greater than 0")], verbose_name="Scan ID"
205205
)
206+
start_time = models.TimeField(verbose_name="Scan start time")
206207
scan_agent = models.CharField(
207208
unique=False,
208209
max_length=255,

master/django_scantron/templates/django_scantron/scheduled_scan_list.html

+5-3
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ <h3>
3333
<td>{{ scan.id }}</td>
3434
<td>{{ scan.site_name }}</td>
3535
<td>{{ scan.scan_agent }}</td>
36-
<td>{{ scan.start_time|date:"Y-m-j H:i:s" }}</td>
36+
<td>{{ scan.start_time|date:"H:i" }}</td>
3737
<td>{{ scan.scan_binary }}</td>
3838
<td>{{ scan.scan_binary }} {{ scan.scan_command }}</td>
3939
<td>{{ scan.scan_status }}</td>
@@ -45,8 +45,10 @@ <h3>
4545
<a href="{% url 'retrieve_scan_file' scan.id %}?file_type=xml">{{ scan.result_file_base_name }}.xml</a>
4646
</td>
4747
{% else %}
48-
<td>{{ scan.result_file_base_name }}.nmap</td>
49-
<td>{{ scan.result_file_base_name }}.xml</td>
48+
<td>
49+
{{ scan.result_file_base_name }}.nmap<br>
50+
{{ scan.result_file_base_name }}.xml
51+
</td>
5052
{% endif %}
5153
{% elif scan.scan_binary == "masscan" %}
5254
{% if scan.scan_status == "completed" %}

master/scan_scheduler.py

+1
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ def main():
118118
"site_name": site_name,
119119
"site_name_id": site_name_id, # Can delete in future.
120120
"scan_id": scan_id, # Can delete in future.
121+
"start_time": scan_start_time,
121122
"scan_agent": scan_agent,
122123
"scan_agent_id": scan_agent_id, # Can delete in future.
123124
"start_datetime": start_datetime,

scantron_model_graph.png

-4.63 KB
Loading

0 commit comments

Comments
 (0)