Skip to content

Commit

Permalink
feat: fixing stegonography
Browse files Browse the repository at this point in the history
  • Loading branch information
William Franco committed Aug 7, 2024
1 parent 13a98dd commit c421269
Show file tree
Hide file tree
Showing 2 changed files with 135 additions and 105 deletions.
206 changes: 109 additions & 97 deletions owasp-top10-2021-apps/a5/stegonography/app/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,143 +3,155 @@ const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const router = express.Router();
const cookieParser = require('cookie-parser');
const cookieParser = require("cookie-parser");
require("dotenv-safe").load();
const jwt = require('jsonwebtoken');
var mongo = require('mongodb')
const jwt = require("jsonwebtoken");
var mongo = require("mongodb");

// Configures everything needed for the app
app.use(express.static('static'));
app.use('/css', express.static('./css'));
app.use('/js', express.static('./js'));
app.use('/images', express.static('./images'));
app.set('views', 'static/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static("static"));
app.use("/css", express.static("./css"));
app.use("/js", express.static("./js"));
app.use("/images", express.static("./images"));
app.set("views", "static/views");
app.engine("html", require("ejs").renderFile);
app.set("view engine", "html");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true}));
app.use(cookieParser())
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());

// Creates a connection to the database
var port = process.env.MONGO_PORT
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://db:27017/stego"
var port = process.env.MONGO_PORT;
var MongoClient = require("mongodb").MongoClient;
var url = "mongodb://db:27017/stego";

// Connect to the database
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
MongoClient.connect(url, function (err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});

// Create "users" collection
var url = "mongodb://db:27017/stego"
MongoClient.connect(url, function(err, db) {
var url = "mongodb://db:27017/stego";
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("stego");
dbo.createCollection("users", function (err, ress) {
if (err) throw err;
var dbo = db.db("stego");
dbo.createCollection("users", function(err, ress) {
if (err) throw err;
console.log("Users collection created!");
db.close();
})
console.log("Users collection created!");
db.close();
});
});

// Add "admin" default user to the database
MongoClient.connect(url, function(err, db) {
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("stego");
var myobj = { username: process.env.USER, password: process.env.PASS };
dbo.collection("users").insertOne(myobj, function (err, res) {
if (err) throw err;
var dbo = db.db("stego");
var myobj = { username: "admin", password: "admin" };
dbo.collection("users").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("Admin user added to the database");
db.close();
});
console.log("Admin user added to the database");
db.close();
});
});

// User login route, get webpage
router.get("/login", function(req,res) {
res.render("login.html");
})
router.get("/login", function (req, res) {
res.render("login.html");
});

// User login route, submit POST request to server
router.post("/login", function(req,res) {
var username = req.body.user.name;
var password = req.body.user.password;

// Verifies user credentials
function VerifiesUser(callback) {
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("stego");
var query = { username: username, password: password };
dbo.collection("users").find(query).toArray(function(err, result) {
if (err) throw err;
db.close();
if( result.length == 0 ){
callback('not_found')
} else {
callback(result[0].username);
}
});
router.post("/login", function (req, res) {
var username = req.body.user.name;
var password = req.body.user.password;

// Verifies user credentials
function VerifiesUser(callback) {
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("stego");
var query = { username: username, password: password };
dbo
.collection("users")
.find(query)
.toArray(function (err, result) {
if (err) throw err;
db.close();
if (result.length == 0) {
callback("not_found");
} else {
callback(result[0].username);
}
});
};

VerifiesUser((username) => {
if (username == "admin") {
var token = jwt.sign({ username }, process.env.SECRET, {
expiresIn: 300 // Token expires in 5 minutes
});
res.cookie('nodejsSessionToken', token).redirect(301, "/admin");
} else {
res.status(500).send('Invalid username or password!').redirect(301, "/logout");
}
});
})
}

// User: admin, password: admin, userRole: 1 //normal 2 //admin

VerifiesUser((username) => {
if (username == process.env.USER) {
var token = jwt.sign({ username }, process.env.SECRET, {
expiresIn: 300, // Token expires in 5 minutes
});
res.cookie("SessionToken", token).redirect(301, "/as-admin");
} else {
res
.status(500)
.send("Invalid username or password!")
.redirect(301, "/logout");
}
});
});

// Logout route to deauthorize user session tokens
router.get("/logout", function(req, res) {
res.status(200).clearCookie('nodejsSessionToken').redirect(301, "/");
router.get("/logout", function (req, res) {
res.status(200).clearCookie("SessionToken").redirect(301, "/");
});

// Admin maintenance page
router.get("/admin", verifyJWT, (req, res, next) => {
res.status(200).render("admin.html");
res.status(200).render("admin.html");
});

// Change password route
router.get("/changepassword", verifyJWT, function(req, res, next) {
// Code to change user password in the database
})
router.get("/changepassword", verifyJWT, function (req, res, next) {
// Code to change user password in the database
});

// Healthcheck route
router.get("/healthcheck", function(req,res) {
res.send("WORKING");
})
router.get("/healthcheck", function (req, res) {
res.send("WORKING");
});

// Main page
router.get("/", function(req,res) {
res.render("index.html")
})
router.get("/", function (req, res) {
res.render("index.html");
});

// Returns the error web-page if none other is found
app.use('/', router);
app.use(function(req, res, next) {
res.status(404).render("error.html")
app.use("/", router);
app.use(function (req, res, next) {
res.status(404).render("error.html");
});
// Listen on port 10006
app.listen(10006, () => {
console.log("Server running on port 10006!");
})
console.log("Server running on port 10006!");
});

// Verifies the JWT token
function verifyJWT(req, res, next){
var token = req.cookies.nodejsSessionToken;
if (!token) return res.status(401).send({auth: false, message: 'No token provided'});

jwt.verify(token, process.env.SECRET, function(err, decoded) {
if (err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });

req.userId = decoded.id;
next();
});
}
function verifyJWT(req, res, next) {
var token = req.cookies.SessionToken;
if (!token)
return res.status(401).send({ auth: false, message: "No token provided" });

jwt.verify(token, process.env.SECRET, function (err, decoded) {
if (err)
return res
.status(500)
.send({ auth: false, message: "Failed to authenticate token." });

req.userId = decoded.id;
next();
});
}
34 changes: 26 additions & 8 deletions owasp-top10-2021-apps/a5/stegonography/deployments/generate-env.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,41 @@
#

# API environment variables
SECRET=$RANDOM$RANDOM
SECRET=$(pwgen -s $KEY_LENGTH 1 | md5sum | awk '{print $1}')
USER=$(pwgen -s $KEY_LENGTH 1 | md5sum | awk '{print $1}')
PASS=$(pwgen -s $KEY_LENGTH 1 | md5sum | awk '{print $1}')

echo "#.env" > app/.env
echo "SECRET=$SECRET" >> app/.env
# echo "USER=$USER" >> app/.env
# echo "PASS=$PASS" >> app/.env


# Database environment variables
# MONGO_DATABASE="stego"
MONGO_DATABASE_USERNAME=User$RANDOM$RANDOM
MONGO_DATABASE_PASSWORD=Pass$RANDOM$RANDOM
# MONGO_PORT=27017
MONGO_DATABASE="stego$(pwgen -s $KEY_LENGTH 1 | md5sum | awk '{print $1}')"
MONGO_DATABASE_USERNAME=User$(pwgen -s $KEY_LENGTH 1 | md5sum | awk '{print $1}')
MONGO_DATABASE_PASSWORD=Pass$(pwgen -s $KEY_LENGTH 1 | md5sum | awk '{print $1}')
MONGO_PORT=27017
MONGO_ROOT_PASSWORD=Root$(pwgen -s $KEY_LENGTH 1 | md5sum | awk '{print $1}')

echo "#" > deployments/.dockers.env
echo "# This file is auto generated and contains all environment variables needed by Stegonography's database" >> deployments/.dockers.env
echo "#" >> deployments/.dockers.env
echo "MONGO_ROOT_PASSWORD=$MONGO_ROOT_PASSWORD" >> deployments/.dockers.env
echo "MONGO_DATABASE=$MONGO_DATABASE" >> deployments/.dockers.env
echo "MONGO_USER=$MONGO_USER" >> deployments/.dockers.env
echo "MONGO_PASSWORD=$MONGO_PASSWORD" >> deployments/.dockers.env
echo "MONGO_PORT=$MONGO_PORT" >> deployments/.dockers.env
echo "MONGO_USER=$MONGO_DATABASE_USERNAME" >> deployments/.dockers.env
echo "MONGO_PASSWORD=$MONGO_DATABASE_PASSWORD" >> deployments/.dockers.env
echo "MONGO_PORT=$MONGO_PORT" >> deployments/.dockers.env
echo "USER=$USER" >> deployments/.dockers.env
echo "PASS=$PASS" >> deployments/.dockers.env




# KEY_LENGTH=32

# # Gera uma chave criptograficamente segura
# SECURE_KEY=$(pwgen -s $KEY_LENGTH 1 | md5sum | awk '{print $1}')

# # Exibe a chave gerada
# echo "Chave gerada: $SECURE_KEY"

0 comments on commit c421269

Please sign in to comment.