Skip to content
Snippets Groups Projects
Commit 5647fad9 authored by Troy's avatar Troy
Browse files

Add the shodan changes. Added dates to recs

parent b9f25c72
No related branches found
No related tags found
No related merge requests found
No preview for this file type
from django.contrib import admin
from .models import ScanResult, Service, Recommendation
# Register your models here.
admin.site.register(ScanResult)
class ScanResultAdmin(admin.ModelAdmin):
list_display = ('ip_address', 'hostname', 'mac_address', 'scan_date') # Display in list view
readonly_fields = ('scan_date',) # Make scan_date readonly
def get_fields(self, request, obj=None):
# This method ensures that scan_date is shown but not editable in detail view
fields = ['ip_address', 'hostname', 'mac_address']
if obj: # Checks if this is an existing object
fields.append('scan_date') # Add 'scan_date' to fields if the object already exists
return fields
admin.site.register(ScanResult, ScanResultAdmin)
admin.site.register(Service)
admin.site.register(Recommendation)
......@@ -7,6 +7,7 @@ class ScanResult(models.Model):
ip_address = models.CharField(max_length=100)
hostname = models.CharField(max_length=255)
mac_address = models.CharField(max_length=100)
scan_date = models.DateField(auto_now_add=True) # Automatically set the field to today's date when the object is first created
def __str__(self):
return f"{self.ip_address} - {self.hostname}"
......
......@@ -34,7 +34,8 @@ def recommendations_view(request):
all_recommendations.extend([{
'id': rec.id,
'ip_address': rec.scan_result.ip_address,
'recommendation_text': rec.recommendation_text
'recommendation_text': rec.recommendation_text,
'scan_date': scan.scan_date.strftime('%Y-%m-%d') # Formatting the date as YYYY-MM-DD
} for rec in recommendations])
else:
# Generate recommendations if none exist
......@@ -44,7 +45,8 @@ def recommendations_view(request):
all_recommendations.append({
'id': new_rec.id,
'ip_address': scan.ip_address,
'recommendation_text': recommendation_text
'recommendation_text': recommendation_text,
'scan_date': scan.scan_date.strftime('%Y-%m-%d') # Formatting the date as YYYY-MM-DD
})
if all_recommendations:
......
import shodan
def shodan_scan(api_key, ips):
api = shodan.Shodan(api_key)
scan_results = []
for ip in ips:
try:
# Host information
host_info = api.host(ip)
# Append scan results to the list
scan_results.append({
scan_result = {
'ip_address': ip,
'open_ports': [{
'port': port_info['port'],
'protocol': port_info['_shodan']['module'],
'banner': port_info.get('banner', None)
} for port_info in host_info['data']],
'banner': port_info.get('banner', '')
} for port_info in host_info.get('data', []) if isinstance(port_info, dict)],
'geolocation': {
'country': host_info.get('country_name', None),
'city': host_info.get('city', None),
'latitude': host_info.get('latitude', None),
'longitude': host_info.get('longitude', None)
'country': host_info.get('country_name', 'Unknown'),
'city': host_info.get('city', 'Unknown'),
'latitude': host_info.get('latitude', 0),
'longitude': host_info.get('longitude', 0)
},
'vulnerabilities': [{
'vuln': host_info['vulns'][vuln]['summary']
} for vuln in host_info.get('vulns', {})]
'vulnerabilities': []
}
vulns_info = host_info.get('vulns', [])
if isinstance(vulns_info, list):
for cve in vulns_info:
if isinstance(cve, str):
scan_result['vulnerabilities'].append({
'cve': cve,
'summary': 'Details not provided by Shodan' # Placeholder text
})
else:
print(f"Unexpected format for vulnerability detail: {cve}")
else:
print(f"Vulnerabilities data is not in expected list format: {type(vulns_info)}")
scan_results.append(scan_result)
except shodan.APIError as e:
print(f"Error: {e}")
print(f"Error scanning IP {ip}: {e}")
except KeyError as ke:
print(f"Key error: {ke} - Possible incorrect data structure access.")
return scan_results
\ No newline at end of file
......@@ -38,6 +38,7 @@
"react": "^18.2.0",
"react-app-polyfill": "^3.0.0",
"react-dom": "^18.2.0",
"react-markdown": "^9.0.1",
"react-redux": "^8.1.1",
"react-router-dom": "^6.22.2",
"redux": "4.2.1",
......
......@@ -25,9 +25,8 @@ const RecommendationsPage = () => {
setRecommendations(response.data)
} catch (error) {
console.error('Error fetching recommendations:', error)
// Handle different errors appropriately here without redirecting
if (error.response) {
console.error('Error status:', error.response.status) // Log specific error status
console.error('Error status:', error.response.status)
}
}
}
......@@ -42,8 +41,7 @@ const RecommendationsPage = () => {
<thead>
<tr>
<th>IP Address</th>
<th>Port</th>
<th>Service Name</th>
<th>Scan Date</th>
<th>Recommendation</th>
</tr>
</thead>
......@@ -51,9 +49,8 @@ const RecommendationsPage = () => {
{recommendations.map((rec) => (
<tr key={rec.id}>
<td>{rec.ip_address}</td>
<td>{rec.port}</td>
<td>{rec.service_name}</td>
<td>{rec.recommendation_text}</td>
<td>{rec.scan_date}</td>
<td style={{ whiteSpace: 'pre-wrap' }}>{rec.recommendation_text}</td>
</tr>
))}
</tbody>
......
......@@ -8,7 +8,6 @@ import {
CForm,
CFormInput,
CInputGroup,
CInputGroupText,
CRow,
} from '@coreui/react'
import CIcon from '@coreui/icons-react'
......@@ -19,7 +18,6 @@ const ShodanScanner = () => {
const [scanResults, setScanResults] = useState([])
const handleAddIpAddress = () => setIpAddresses([...ipAddresses, { address: '' }])
const handleRemoveIpAddress = (index) => {
const newIpAddresses = [...ipAddresses]
newIpAddresses.splice(index, 1)
......@@ -37,8 +35,6 @@ const ShodanScanner = () => {
})
const data = await response.json()
// Log or process the scan results from the backend
console.log('Scan results:', data)
setScanResults(data.scan_results)
} catch (error) {
......@@ -108,10 +104,16 @@ const ShodanScanner = () => {
</div>
<div>
<h5>Vulnerabilities</h5>
{result.vulnerabilities &&
result.vulnerabilities.map((vuln, vulnIndex) => (
{result.vulnerabilities.map((vuln, vulnIndex) => (
<p key={vulnIndex}>
{Object.keys(vuln)[0]}: {Object.values(vuln)[0]}
<a
href={`https://nvd.nist.gov/vuln/detail/${vuln.cve}`}
target="_blank"
rel="noopener noreferrer"
>
{vuln.cve}
</a>
{vuln.cve}: {vuln.summary} (CVSS: {vuln.cvss || 'N/A'})
</p>
))}
</div>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment