Day 3-Vulnerability Scanner
Day 3-Vulnerability Scanner
old kid
Hi there, little coder! Today, we’re building a database and setting up the API structure for our
vulnerability scanner. Think of the database as a big toy box where we store all our important
data (like scan results), and the API as the magic postman that helps our frontend and backend
talk to each other. Let’s go step by step and build this together!
We’ll use SQLite, which is a super lightweight database that’s easy to set up and works perfectly
for small projects.
If you don’t have VS Code, use Notepad or any editor to create the file.
@app.route('/api/scans', methods=['POST'])
def add_scan():
data = request.json # Get data from the frontend
new_scan = ScanResult(
target=data['target'],
scan_type=data['scan_type'],
result=data['result'],
timestamp=datetime.now()
)
db.session.add(new_scan) # Add to the database
db.session.commit() # Save changes
return jsonify({'message': 'Scan saved successfully!'}), 201
@app.route('/api/scans', methods=['GET'])
def get_scans():
scans = ScanResult.query.all() # Get all scan results
scan_list = [{
'id': scan.id,
'target': scan.target,
'scan_type': scan.scan_type,
'result': scan.result,
'timestamp': scan.timestamp
} for scan in scans]
return jsonify(scan_list)
Let’s see if our APIs work using Postman (a tool to test APIs):
1. Install Postman:
Download and install Postman from https://www.postman.com/.
1. Open Postman.
2. Select POST and enter http://127.0.0.1:5000/api/scans.
3. Go to the Body tab, choose raw, and select JSON.
4. Enter this sample data:
5. {
6. "target": "example.com",
7. "scan_type": "TCP",
8. "result": "Open ports: 80, 443"
9. }
10. Click Send. You should see a response:
11. {"message": "Scan saved successfully!"}
Awesome job, little coder! Your backend is now super smart and ready to handle data.
Tomorrow, we’ll start adding more features to your app. 😊
i dont under how to update app.py file, give me fully updated code of app.py file for Day 3: Database
Design and API Structure
Here is the fully updated app.py file for Day 3: Database Design and API Structure. This
includes everything needed to set up the backend, connect the database, and implement API
routes.
1. Imports Libraries:
o Flask: To create the backend web server.
o SQLAlchemy: To work with the SQLite database.
o datetime: To add timestamps to scan results.
2. Sets Up the Database:
o Uses SQLite to create a file named scans.db.
o Defines a table named ScanResult with columns:
id: Unique ID for each scan.
target: The website or IP address scanned.
scan_type: The type of scan performed (e.g., TCP, XSS).
result: The details of the scan result.
timestamp: The time the scan was performed.
3. Creates API Routes:
o POST /api/scans: Saves a new scan result in the database.
o GET /api/scans: Fetches all stored scan results.
o GET /: Basic route to check if the backend is running.
4. Initializes the Database:
o Ensures that tables are created the first time the app runs.
5. Runs the Server:
o Starts the Flask app on http://127.0.0.1:5000.
How to Test This Code
Folder Structure
Next Steps
Let’s break this down step by step so you can easily send a POST request to the API. You can use
Postman (a graphical interface) or cURL (a command-line tool) to do this. We’ll go through
both methods.
After sending the POST request, the scan data is saved in your scans.db database. To verify:
1. Use the GET API (http://127.0.0.1:5000/api/scans) to fetch all saved scan results.
2. The saved data should appear in the JSON response.
1. Press the Windows key and type cmd, then press Enter.
After running the command, you should see this response in the terminal:
{
"message": "Scan saved successfully!"
}
Troubleshooting Tips
Instead of using @app.before_first_request, we’ll create the database tables explicitly when
the app starts. Follow these steps:
Updated app.py
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
1. Replaced @app.before_first_request:
o Instead of waiting for the first request, the database tables are created immediately
when the app starts using:
o with app.app_context():
o db.create_all()
2. No Dependency on before_first_request:
o This ensures compatibility with all Flask versions.
Follow the steps to test the APIs using Postman or cURL, as described earlier.
Using with app.app_context(): ensures that the database initialization happens correctly
within the application context, avoiding compatibility issues with Flask's lifecycle events.
The 404 Not Found error indicates that the route you’re trying to access does not exist on the
server. This can happen for several reasons in your Flask app. Let’s go step by step to identify
and resolve the issue.
1. Open your browser and ensure you are accessing the correct URL:
o For the home route: http://127.0.0.1:5000/
o For the POST API: http://127.0.0.1:5000/api/scans
2. If you’re testing an API, use tools like Postman or cURL instead of directly typing the
URL in the browser.
Open your app.py file and confirm that the route you’re trying to access is defined. For
example:
Home Route
@app.route('/')
def home():
return jsonify({'message': 'Vulnerability Scanner Backend is Running!'})
If this route is missing, add it to your file, save, and restart the app.
@app.route('/api/scans', methods=['POST'])
def add_scan():
# Code to handle saving scan data
pass
@app.route('/api/scans', methods=['GET'])
def get_scans():
# Code to handle retrieving scan data
pass
If these routes are missing, add them as shown above, save, and restart the app.
Make sure the URL you’re entering matches exactly with the route defined in app.py.
For example:
o If the route is /api/scans, entering /apis/scans will result in a 404 error.
Step 6: Debugging Tips
This will show you all defined routes and the methods they accept (e.g., GET, POST).
Common Issues
1. Missing Routes: Ensure all routes you’re trying to access are defined in app.py.
2. Typos in URLs: Double-check for spelling errors in the URL.
3. App Not Running: Verify that app.py is running.
4. Incorrect Method: Ensure you’re using the correct HTTP method (e.g., GET or POST)
for the route.
Share the exact URL you’re trying to access and the code from your app.py file.
I’ll help you debug further! 😊
I perform step 4: Test the App Locally, Test the home route in your browser, this step successfully
output on browser, but tell me Test the API routes using Postman is necessary or not, if not necessary I
don't perform this step.
Testing the API routes using Postman is not strictly necessary if you’re confident that your
code is correct and don’t need to manually verify the API's behavior at this stage. However,
here’s why you might or might not want to perform this step:
Recommendation
If You’re Comfortable: You can skip Postman testing and directly move on to
integrating the frontend with the backend.
If You Want to Be Thorough: Test the POST and GET APIs using Postman now. This
step ensures your backend works before adding the complexity of frontend integration.
If you skip Postman testing now, be ready to revisit API testing if:
Let’s go through testing the POST API using cURL step by step. cURL is a command-line tool
that allows you to make HTTP requests like GET and POST. It’s great for testing APIs without
needing additional software like Postman.
Although not required, it’s a good practice to navigate to your project directory:
cd C:\Users\mscit\Desktop\vuln-scanner\backend
This helps you stay organized if you want to check logs or access files related to your project.
After running the command, you should see a response in the Command Prompt similar to this:
1. You can use the GET API to retrieve all saved scans and verify that the data was stored.
o Run the following cURL command:
o curl http://127.0.0.1:5000/api/scans
2. You should see a JSON response listing all saved scans, similar to this:
3. [
4. {
5. "id": 1,
6. "target": "example.com",
7. "scan_type": "TCP",
8. "result": "Open ports: 80, 443",
9. "timestamp": "2024-12-19 10:30:00"
10. }
11. ]
Troubleshooting Tips
Next Steps