Secure Coding

For coders

Title Text

      
   :~> whoami
   
    Alireza Rezaie
    Twitter :
    Blog    :

@Ralireza11

MrBug.ir

WHAT ?

WHY ?

HOW?

Topics

  • Secure SDLC
  • Input validation
  • Authentication and Password Management
  • Error Handling and Logging
  • Memory Management

  • Common Attacks

Input Validation

Input validation

Best practices 

Input validation 

Input validation - Best practice

Data type validators

Input validation - Best practice

Validation against JSON Schema 

Input validation - Best practice

Type conversion

  • Integer.parseInt( )
  • toString( )
  • toHTML( )
  • ...

Input validation - Best practice

Array of allowed values

allow_values = [ 1, 2, 3, 4]
if input in allow_values:
	return true
    
else 
	return false

Input validation - Best practice

Input validation - Best practice

Min & Max

Authentication &

Password Management

Best practices

auth - Best practice

Password Length

auth - Best practice

password strength

auth - Best practice

Secure Password Recovery

  • consistent message for both existent and non-existent accounts
  • tokens:
    • ​Randomly generated
    • protect against brute-force attacks
    • Single-use and expire after an appropriate period
    • Rate limiting

auth - Best practice

Storing password

auth - Best practice - Storing password

  • Hashing vs Encryption

  • how crackers do devils

  • Hashing Concepts (salt, pepper, . . . )

  • strongest algorithm  (SHA-512 > SHA-256 > SHA-1 > MD5)

  • Custom Algorithms : NO !

 

auth - Best practice 

Require Re-authentication for Sensitive Features

auth - Best practice 

Error Messages

  • The user ID  incorrect.
  •  password was incorrect
  • The account does not exist.
  • The account is locked or disabled.
  • . . .

auth - Best practice 

 Automated Attacks

auth - Best practice 

  • Multi-Factor Authentication
  • Account Lockout
  • CAPTCHA
  • Security Questions and Memorable Words
  • Logging and Monitoring

Protect Against Automated Attacks

Error Handling & Logging:

Best practices 

Error Handling and Logging :

Error Handling and Logging - Best practices :

Error Handling and Logging - Best practices :

  • Do not disclose sensitive information in error responses, including system details, session identifiers or account information

 

  • Use error handlers that do not display debugging or stack trace information

Global Error Handler

Error Handling and Logging - Best practices :

Fail Securely

Error Handling and Logging - Best practices :

  • allow the operation
  • disallow the operation
  • exception

isAuthorized(), isAuthenticated(),  validate(), ...

Error Handling and Logging - Best practices :

isAdmin = true; 
try { 
  codeWhichMayFail(); 
  isAdmin = isUserInRole( "Administrator" ); 
}
catch (Exception ex)
{
  log.write(ex.toString()); 
} 
isAdmin = false;
try {
  codeWhichMayFail();
  isAdmin = isUserInrole( "Administrator" );
}
catch (Exception ex)
{
  log.write(ex.toString());
}

GOOD

BAD

Much More Than

Error Handling and Logging - Best practices :

Always Log:

Error Handling and Logging - Best practices :

  • Sequencing failure
  • Excessive use
  • Data changes
  • Fraud and other criminal activities
  • Suspicious, unacceptable or unexpected behavior
  • Modifications to configuration
  • Application code file and/or memory changes

Event attributes:

Error Handling and Logging - Best practices :

  • When
  • where
  • who
  • what

exclude: 

Error Handling and Logging - Best practices :

 
  • Application source code
  • File paths
  • Database connection strings
  • Internal network names and addresses
  • Access tokens
  • Authentication passwords
  • ...

Memory Management:

Memory Management 

  • Buffer overflow
  • Null pointer dereference
  • Use after free
  • Use of uninitialized memory
  • Illegal free (of an already-freed pointer, or a non-malloced pointer)

Attacks

common attacks

  • Brute Force

  • Man-In-the-Middle

  • SQL Injection

  • RAT

  • Code Injection

  • Command Injection

  • XSS

  • CSRF

  • Social Engineering

Brute Force

Brute Force

Defence

  • Increase password length

  • Increase password complexity

  • Limit login attempts

  • Implement Captcha

  • Use multi-factor authentication

MITM

MITM

Defence

  • Authentication

  • Tamper detection

  • Forensic analysis

SQL Injection

Types

  • Boolean-based

SELECT id FROM products WHERE productid=9999 OR 1=1

  • Time-based

SELECT * FROM products WHERE id=1 AND 1>(SELECT count(*) FROM information)

  • Error-based

SELECT * FROM products

  • UNION 
SELECT name FROM products WHERE id=1 UNION SELECT 1 FROM table
  • Stacked

SELECT * FROM products WHERE productid=1; DELETE FROM products

SQLi

Defence

  • Parameterized Queries

  • Sanitized

  • Stored Procedures

Validation checks if the input meets a set of criteria (such as a string contains no standalone single quotation marks).

Sanitization modifies the input to ensure that it is valid (such as doubling single quotes).

RAT

RAT

Defence

  • Update

  • AV & firewall

  • Download & Install from the trust

  • Suspicious link

  • WTF proccess

Code injection

$myvar = "varname";
$x = $_GET['arg'];
eval("\$myvar = \$x;");

Code Injection

Defence

  • Validate and sanitize inputs

  • Avoid vulnerable evaluation constructs

  • Lock down your interpreter

  •  Code integrity check

Command Injection

$ > whoami & echo "test"

Command Injection

Defence

  • Avoid calling OS commands directly

mkdir() vs system("mkdir /dir_name").
  • Validating against a whitelist of permitted values

  •  The input contains only alphanumeric characters

BufferOverflow

...
char buf[BUFSIZE];
cin >> (buf);
...

XSS

cross-site-scripting

Reflected XSS

XSS

Defence

  • Encoding

  • Validation

  • HTTP-only

  • Content Security Policy (CSP):

    No untrusted sources

    No inline resources

    No eval

     

CSRF

CSRF

Defence

  • Token

  • SameSite Cookie

  • Re-Authentication

  • CAPTCHA

Social engineering

 The art of humen hacking

Good links:

secure coding

By AliReza Rezaie

secure coding

  • 1,712