0% found this document useful (0 votes)
11 views16 pages

Lec08 .8m

The document discusses various server-side security vulnerabilities, including command injection, SQL injection, NoSQL injection, XML External Entity (XXE) injection, unrestricted file uploads, and Denial of Service (DoS) attacks. It provides examples of vulnerable code and outlines best practices for mitigating these risks, such as using parameterized queries, validating user input, and implementing file upload restrictions. Additionally, it emphasizes the importance of secure coding practices to protect applications from these common threats.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views16 pages

Lec08 .8m

The document discusses various server-side security vulnerabilities, including command injection, SQL injection, NoSQL injection, XML External Entity (XXE) injection, unrestricted file uploads, and Denial of Service (DoS) attacks. It provides examples of vulnerable code and outlines best practices for mitigating these risks, such as using parameterized queries, validating user input, and implementing file upload restrictions. Additionally, it emphasizes the importance of secure coding practices to protect applications from these common threats.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

05/05/2024

Lec 09.
Server-side Security

Code Injection

2
05/05/2024

Command Injection

• Goal: Execute arbitrary commands on the host


operating system via a vulnerable application
• Command injection attacks are possible when an
application passes unsafe user supplied data
(forms, cookies, HTTP headers, etc.) to a system
shell

Command injection in Node.js

• Vulnerable code:
const filename = process.argv[2]
const stdout = childProcess.execSync(`cat
${filename}`)
console.log(stdout.toString())
• Input: file.txt
• Resulting command: cat file.txt
• Malicious input: file.txt; rm -rf /
• Resulting command: cat file.txt; rm -rf /

4
05/05/2024

Running commands safely

• Unsafe
const filename = process.argv[2]
const stdout = childProcess.execSync(`cat
${filename}`)
• Safe
const filename = process.argv[2]
const { stdout } =
childProcess.spawnSync('cat', [filename])

SQL injection

• SQL injection (SQLi): Injecting SQL into queries


constructed by the server to cause malicious
behavior
• Typically caused by using vulnerable string manipulation
for SQL queries
• Attack is possible when an application combines unsafe
user supplied data (forms, cookies, HTTP headers, etc.)
with a SQL query
• Allows the attacker to execute arbitrary SQL on the
SQL server!
• Leak data
• Add records
• Modify records
• Delete records/tables
• Basically anything that the SQL server can do

6
05/05/2024

SQL injection: Example

• Vulnerable code:
const { username, password } = req.body
const query = `SELECT * FROM users WHERE username =
"${username}" AND password = "${password}"`
db.get(query, (err, row) => {
if (err) {
console.error(err)
res.send('fail!’)
return
}
if (!row) {
res.send('fail!’)
return
}
/* Success */
})

SQL injection: Example

• SQL template:
SELECT * FROM users WHERE username =
"${username}" AND password = "${password}"
• Input: { username: ‘alice’, password: ‘123456’ }
• Resulting query:
SELECT * FROM users WHERE username = “alice" AND
password = "123456"
• Malicious input: {username: ‘alice” OR 1=1 --’, password:
‘any’}
• Resulting query:
SELECT * FROM users WHERE username =
"alice" OR 1=1--“AND password = “any"

8
05/05/2024

SQL injection: Example

db.exec(`INSERT INTO logs VALUES ("Login


attempt from ${username}")`)
• Unlike db.get, turns out db.exec can execute multiple
queries
• Usernames to try (password can be anything):
"); UPDATE users SET password = "root" WHERE
username = "bob" -- (change Bob's password)
"); DROP TABLE users -- (delete the users table)

SQL injection defenses

• Never build SQL queries with string concatenation


• Instead, use one of the following:
• Parameterized SQL
• Object Relational Mappers (ORMs)

10
05/05/2024

Parameterized SQL

• Vulnerable code:
const query = `SELECT * FROM users WHERE username =
"${username}"`
const results = db.all(query)
• Safe code:
const query = 'SELECT * FROM users WHERE username = ?’
const results = db.all(query, username)
• Will automatically handle escaping untrusted user input for
you

11

Objection relational mappers (ORMs)

• ORMs provide a JavaScript object interface for a


relational database
• Will automatically handle escaping untrusted
user input for you
class User extends Model {
static tableName = 'users'
}

const user = await User.query()


.where('username', username)
.where('password', password)

12
05/05/2024

NoSQL Injection: Example

let username = req.query.username;


query = { $where: `this.username == '${username}'` }
User.find(query, function (err, users) {
if (err) {
// Handle errors
} else {
res.render('userlookup', { title: 'User Lookup’,
users: users });
}
});

• Malicious input: any' || 'a'=='a

13

NoSQL Injection: Example

const { username, password } = req.body;

const user = await User.findOne({ username, password


}).exec();
res.json({
message: `Logged in as ${user.username}`,
});

• Malicious input: {"username": "test1", "password": {


"$ne": null }}

14
05/05/2024

NoSQl Injection Defense

• Sanitize and Validate User Input: Always sanitize


and validate user input before incorporating it
into database queries.
• NodeJS:
• Parameterized Queries: Instead of directly
concatenating user input into queries, utilize
parameterized queries or prepared statements.
• Object-Document Mapping (ODM) or Object-
Relational Mapping (ORM) Libraries

15

Parameterized Queries: Example

const { username, password } = req.body;


const query = { name: { $eq: username }, password: { $eq:
password }};
User.findOne(query, (err, result) => {
// Handle the result
});

16
05/05/2024

ORM: Example

// Mongoose example with validation and sanitization


const userSchema = new mongoose.Schema({
name: { type: String, required: true },
password: {type: String, required: true},
});
const UserModel = mongoose.model('User', userSchema);

const { username, password } = req.body;


const query = UserModel.find({ name: name, password:
password });

query.exec((err, result) => {


// Handle the result
});

17

XXE

18
05/05/2024

Introduction

• XML eXternal Entity injection (XXE): attack


against applications that parse XML input
• XXE attack occurs when untrusted XML input
with a reference to an external entity is
processed by a weakly configured XML parser
• Attack could be used to stage multiple incidents
• A DoS attack on the system
• A Server Side Request Forgery (SSRF) attack
• The ability to scan ports from the machine where the
parser is located
• Other system impacts.

19

XXE: Example
app.post('/load_xml', upload.single('xml'), async
function (req, res) {
if (!req.file) {
res.sendStatus(500);
return;
}
try {
const xml = req.file.buffer;
const doc = libxmljs.parseXml(xml, {noent: true});
res.send(doc.text());
} catch (err) {
res.send(err.toString());
res.sendStatus(500);
}
});

• Malicious input: <!DOCTYPE d [<!ENTITY e SYSTEM


"file:///etc/passwd">]><t>&e;</t>

20
05/05/2024

XXE Prevention

• Disable XML external entity and DTD processing in all


XML parsers in the application
• Human factor: Different ways on different XML processor
• Example: For libxmljs, parsing of external entities is disabled by
default
• Whenever possible, use less complex data formats such
as JSON, and avoiding serialization of sensitive data
• Implement positive (“whitelisting”) server-side input
validation, filtering, or sanitization

21

Read more

• XML External Entity Prevention Cheat Sheet:


https://cheatsheetseries.owasp.org/cheatsheets
/XML_External_Entity_Prevention_Cheat_Sheet.
html

22
05/05/2024

Unrestricted File Upload

23

Unrestricted File Upload

• An unrestricted upload of files vulnerability


occurs when an application performs insufficient
filtering — or lacks filtering entirely — when
accepting file uploads.
• Risk Factors:
• Executing any malicious code
• Trigger vulnerabilities in broken libraries/applications
• Put a phishing page into the website or deface the
website
• Exploit other vulnerable sections of an application
• Disclose internal information such as server internal
paths in their error messages

24
05/05/2024

Unrestricted File Upload: Example

app.post("/avatars/upload", (req, res) => {


let avatar = req.files.file;
let filename = avatar.name;

// Write the avatar to the avatars folder


fs.writeFile(`static/avatars/${user_id}/${filename}`,
avatar.data, (err) => {
if (err)
res.status(500).send('Error uploading avatar');
else
res.json({ URL:
`static/avatars/${user_id}/${filename}` });
});
});

25

Example: Mitigation

• Decide what kind of files you want to allow and


deny
• Implement allow lists instead of deny lists (deny
lists tend to be easier for an attacker to bypass)
• Generate file names yourself
• Uploaded files shouldn’t be publicly accessible
unless really needed. Even then, try to implement
proper authorization to ensure only the right
people have access to them

26
05/05/2024

Example: Mitigation

const fileUpload = require('express-fileupload');


app.use(fileUpload({safeFileNames: true}))
const allowedExtensions = ['png', 'jpg', 'gif']

app.post("/avatars/upload", (req, res) => {


let avatar = req.files.file;
let extension = path.extname(avatar.name).substr(1)
if (!allowedExtensions.includes(extension))
return

// Create the filename by generating a unique name and


// appending the original allowed extension
let filename = `${shortid.generate()}.${extension}`

// Write the avatar to the avatars folder


//...
});

27

Read more

• Unrestricted File Upload: https://owasp.org/www-


community/vulnerabilities/Unrestricted_File_Upload

28
05/05/2024

DoS

29

What is DoS?

• Denial of Service: An attack that disrupts


availability of a service, making it unavailable for
legitimate users
• Application attacks focus on rendering
applications unavailable by exhausting resources
or by making it unusable in a functional way.
• Session (or protocol) attacks focus on consuming
server resources, or resources of intermediary
equipment like firewalls and load-balancers.
• Network (or volumetric) attacks focus on
saturating the bandwidth of the network
resource.

30
05/05/2024

DoS mitigation

• Session
• Limit server side session time based on inactivity and
a final timeout
• Limit session bound information storage
• Input validation
• Limit file upload size and extensions
• Limit total request size
• Prevent input based resource allocation
• Prevent input based function and threading
interaction

31

Read more

• Denial of Service Cheat Sheet:


https://cheatsheetseries.owasp.org/cheatsheets
/Denial_of_Service_Cheat_Sheet.html

32

You might also like