Files
codeql/javascript/ql/test/query-tests/Security/CWE-352/csurf_api_example.js
Asger F cd2c4d5e3a JS: Use post-processed inline test in MissingCsrfMiddleware
This query flags the cookie-parsing middleware in order to consolidate huge numbers of alerts into a single alert, which is more manageable. But simply annotating the cookie-parsing middleware with 'Alert' isn't a very useful, we want to annotate which middlewares are vulnerable.
2025-02-21 14:44:46 +01:00

49 lines
1.4 KiB
JavaScript

// Adapted from https://github.com/expressjs/csurf, which is
// licensed under the MIT license; see file LICENSE.
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// create express app
var app = express()
// create api router
var api = createApiRouter()
// mount api before csrf is appended to the app stack
app.use('/api', api)
// now add csrf and other middlewares, after the "/api" was mounted
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(csrf({ cookie: true }))
app.get('/form', function (req, res) {
let newEmail = req.cookies["newEmail"];
// pass the csrfToken to the view
res.render('send', { csrfToken: req.csrfToken() })
})
app.post('/process', function (req, res) { // OK
let newEmail = req.cookies["newEmail"];
res.send('csrf was required to get here')
})
function createApiRouter () {
var router = new express.Router()
router.post('/getProfile', function (req, res) { // OK - cookies are not parsed
let newEmail = req.cookies["newEmail"];
res.send('no csrf to get here')
})
router.post('/getProfile_unsafe', cookieParser(), function (req, res) { // $ Alert - may use cookies
let newEmail = req.cookies["newEmail"];
res.send('no csrf to get here')
}) // $ RelatedLocation
return router
}