Sei sulla pagina 1di 14

Transerv Pvt Ltd.

Secure Coding Guidelines Date:03/05/17


Version-01
Rev No.00

Secure Coding Guidelines

11/1/2013
Transerv Pvt Ltd.
Secure Coding Guidelines Date:03/05/17
Version-01
Rev No.00

Table of Contents
1 Introduction.........................................................................................................................4

2 Secure Architecture.............................................................................................................4

3 Secure Designing................................................................................................................7

4 Secure Coding.....................................................................................................................9

5 Secure Configuration of server.........................................................................................12

6 Other General Practices.....................................................................................................14

7 References & Links...........................................................................................................14


Transerv Pvt Ltd.
Secure Coding Guidelines Date:03/05/17
Version-01
Rev No.00

0.2 Revision History


Sl. Version Revision Date of Created / Section Description of
No. No. No. Revision Updated by Changed Change
1 01 00 Divya John Initial Document
Transerv Pvt Ltd.
Secure Coding Guidelines Date:03/05/17
Version-01
Rev No.00

1 IntroductionInformation Security Management


System
You must adopt a defence-in-depth approach to minimise the security risks to web
applications. Security controls must be applied at each layer of the web application and
associated web server to eliminate reliance on any single security control. Security
controls must be selected based on the outcome of a risk assessment, and the
classification of the information that will be processed by or stored on the web server.

This document provides specific guidance for application developers to apply during
web application development.

2 Secure Architecture
2.1 Cryptographic Practices:
Cryptographic systems and techniques must be used for the protection of
information that is considered at risk.
A. Selecting Cryptographic Algorithms:
Cryptographic systems provide authentication, non-repudiation, confidentiality
and integrity. Depending on your risks and requirements, you need to decide
which of these four functions should be used to protect your data. You need to
select an algorithm which is computationally difficult to break. The following are
types of cryptographic systems:

 Symmetric Cryptography:
In Symmetric Cryptography, both parties share the same key for
encryption and decryption. This key needs to be kept secret. If anyone
gets to know the key, he/she can easily decrypt the encrypted
information. A few well-known examples are: DES, Triple-DES (3DES),
IDEA, BLOWFISH, and TWOFISH. (HTTPS is being used here)

 Asymmetric Cryptography:
Asymmetric algorithms use pairs of keys. One is used for encryption and
the other one for decryption. The decryption key is typically kept secret,
therefore called "private key", while the encryption key is spread to the
world for encrypting messages, therefore called "public key". Hence, it is
more secure than symmetric cryptography. A few well-known examples
are RSA, DSA, and ELGAMAL.
Transerv Pvt Ltd.
Secure Coding Guidelines Date:03/05/17
Version-01
Rev No.00

 Hashes:
Hash functions take some data of an arbitrary length and generate a
fixed-length hash value based on this input. A few well-known examples
are MD5, SHA-1, and AES.

B. Recommendation:
Depending on your requirements and risks, you should choose symmetric or
asymmetric cryptography. However, there are some algorithms which are found
to be vulnerable. Hence, you should avoid them. Vulnerable Algorithms: MD5,
SHA-0, SHA-1 and DES
As per an application threat modelling approach, below are some best practices
you should follow while implementing cryptographic systems in your application:

 Symmetric Cryptography:
 Minimum key size of 128 bits should be sufficient for most general
purpose applications.
 Minimum key size of 168 or 256 bits should be sufficient for critical
applications such as financial or containing partner \ client information.

 Asymmetric Cryptography:
 Minimum Key sizes of 1280 bits should be sufficient for most general
purpose applications.

 Minimum key size of 2048 bits should be sufficient for critical


applications such as financial or containing partner \ client information.

 Hashes:
 Minimum hash size of 128 bits should be sufficient for most general
purpose applications.
 Minimum hash size of 168 or 256 bits should be sufficient for critical
applications such as financial or containing partner \ client information.

2.2 Session Management:


Applications should use session management mechanisms instead of custom-
developed mechanisms.

A. Session ID Creation
 The session tokens should be generated via a cryptographically secure
random number generator and handled by the web server.
B. Session Expiration:
 Session should get terminated and all session tokens should get
destroyed after logout action.
C. Session ID Length
 Session tokens should be greater or equal to128-bit.
D. Inactivity Time Out
 Authenticated sessions should time-out after pre-determined period of
inactivity – 15-20 minutes is recommended.
Transerv Pvt Ltd.
Secure Coding Guidelines Date:03/05/17
Version-01
Rev No.00

E. HTTP Only/Secure Flag


 The "HTTP-Only" flag sets to disable malicious script access to the
cookie values, such as the session ID and other sensitive information
passed through cookie parameter.
 Secure flag instructs the browser to never send the cookie over HTTP
channel. The purpose of this flag is to prevent the accidental exposure of
a cookie value if a user follows an HTTP link.
 "HTTP Only" and "Secure" flag should be set during every set-cookie.
F. Other Recommendations:
 Persistent authentication sessions or cookies should be disallowed
 All data should get stored in session variables instead of client-side
cookies.
 All session identifiers and cookies should be sent over encrypted
connections.
 Session identifiers and cookies should never be sent to the web server
as HTTP GET parameters.

2.3 Communication Security:


A. Type of HTTP method:
For transmitting data from client to server, you can use either GET or POST
methods. However, you should use POST method for passing sensitive
information from client to server. This would be the first line of defense

B. Transmission Channel to be used:


For transmitting information between client and server you should always use
HTTPS channel instead of HTTP channel. This should include TLS for
protecting the connections. The TLS protocol allows web applications to
communicate across a network in a way designed to prevent eavesdropping
and tampering.

 Recommendations:
 Use only TLSv1.2. Do not use SSLv2.0/SSLv3.0 since they are affected
with multiple vulnerabilities.
 Avoid using all cipher suites that runs in CBC mode.
 Weak ciphers (less than 128 bits) should not be used.
 Secure Renegotiation should be enabled.
 Avoid using MD5 and RC4 due to collision and crypto-analytical attacks
respectively.
 Server should support Forward Secrecy.
Transerv Pvt Ltd.
Secure Coding Guidelines Date:03/05/17
Version-01
Rev No.00

3 Secure Designing
3.1 Authentication and Password Management
A. Password Policy
Combining the below defined length with complexity makes a password difficult
to guess and/or brute force.
 Password Length: Passwords should be at least eight characters long.
 Password Complexity: Password characters should be a combination of
upper case and lower case letters, special characters and numeric digits.
B. Password Guessing
Applications should defend against password guessing attempts including brute
force attacks by implementing the following methods:

 Temporary Account Lockout - Temporarily lock account for few minutes


after 5failed password attempts or 30 unsuccessful attempts in a day.
 Permanent Account Lockout – follows the same instructions as
Temporary Account Lockout.Anti-Automation
 CAPTCHA–User should successfully complete CAPTCHA after 3 failed
password attempts. (Not applicable to all applications)
C. Password Storage
 If your application manages a credential store, it should store passwords
using strong cryptographic algorithms as defined in section 2 above.
Also any tables or files that store the passwords should be writeable only
by the application.
D. Email Verification Functions
If your application requires verification of ownership of an email address then
the following should be applied:
 Email verification links should only satisfy the requirement of verifying
email address/account ownership and link should not provide the user
with an authenticated session.
 Email verification codes must expire after the first use or expire after 4
hours if not used.

E. General Recommendations:
 All passwords (e.g., User, Admin, SuperAdmin etc.) should be changed
on at least a quarterly basis
 User/Application should not use vendor-supplied/defaults passwords.
 Users should be provided with a mechanism for selecting their own
passwords.
 Generic responses should be returned for all authentication failures such
that they do not indicate which part of the authentication data was
incorrect.
 If temporary passwords (or links to temporary passwords) are used, the
following should get enforced:
o For Reset password we send mail with link to change password,
which gets expired on below scenario.
Transerv Pvt Ltd.
Secure Coding Guidelines Date:03/05/17
Version-01
Rev No.00

o 1: After “5 minutes” on hit of URL


o 2: it will not work on 2nd attempt, user needs to recreated link.
o 3: it will get expired after one hour, if not accessed.
 Passwords on the user’s screen should be obscured so that they cannot
be viewed by ‘shoulder surfing’.
 Password caching or auto complete features should be disabled, e.g. the
auto complete attribute is set to the value ‘off’.
 Facilitate users to use virtual keyboard in case of critical fields like
password, account number, pin number etc.
 For critical, sensitive or highly critical transactions, users should be
forced to re-authenticate or multi-factor authentication should be
enforced prior to performing the transaction.

3.2 Access Control


A. Access to Unrestricted Modules:
 Ensure that access control verification is performed to check that the
user is authorized to access that particular data/module.
 Restrict access to protected URLs, functions, direct object references,
services, application data and security-relevant configuration
information to only authorized users.
 Enforce authorization controls on every request including those made by
server side scripts, "includes" and requests from rich client-side
technologies like AJAX and Flash.
 If state data must be stored on the client, use encryption and integrity
checking on the server side to catch state tampering.
 Ensure that access control verification is performed before an action is
executed within the system.
 It is recommended to not display links or functionality that is not
accessible to a user.
 If long authenticated sessions are allowed, periodically re-validate a
user’s authorization to ensure that their privileges have not changed and
if they have, log the user out and force them to re-authenticate.
Transerv Pvt Ltd.
Secure Coding Guidelines Date:03/05/17
Version-01
Rev No.00

4 Secure Coding
4.1 Database Security
A. Defensive Coding
The use of proper coding practices is a straightforward solution for web
application vulnerabilities especially for SQL injection vulnerability since it is due
to insecure coding of web developers. Below is the defensive coding method
that you should follow:

 Parameterized queries or stored procedures:


 Proper coding style of parameterized queries or stored procedures
forces you to define the structure of SQL code first before including
parameters to the query. It is recommended to use prepared
statements or stored procedures since it ensures that an attacker is not
able to change the intent of a query, even if SQL commands are
inserted by an attacker.
 Data type validation
B. You should validate whether an input is string or numeric. This could easily
reject type-mismatched inputs. This could also simplify the escaping process
because validated numeric inputs need no further cleansing action and could be
safely used in queries.

C. Other Database Recommendation:


 The application should use the lowest possible level of privilege when
accessing the database.
 Connection strings should not be hardcoded within the application.
 Connection strings should be stored in a separate configuration file on
a trusted system and it should be in encrypted format.
 Remove or change all default database administrative passwords.
Utilize strong passwords/phrases or implement multi-factor
authentication.
 Turn off all unnecessary database functionality (e.g., unnecessary
stored procedures or services, utility packages), Install only the
minimum set of features and options required.
 Close the connection as soon as possible.

4.2 File Management


 Do not save user uploaded files in the same web context as the
application. Files should either go to the content server or in the
database.
 Turn off execution privileges on file upload directories.
 You should remove all hard-coded passwords from source code.
 All sensitive information should be encrypted when it is stored.
 Server-side source code should be protected from being downloaded
by unauthorised users.
Transerv Pvt Ltd.
Secure Coding Guidelines Date:03/05/17
Version-01
Rev No.00

 Client-side caching should be disabled on pages containing sensitive


information (e.g. using “Cache-Control: no-store” and “Pragma: no-
cache” headers).
 Do not pass user supplied files directly to any dynamic include
function.
 Ensure application files and resources should be read-only.
 Remove backup or unwanted files from web folder.
4.3 Input Validation
A. Validation of input
Input validation is performed to minimize malformed data from entering the
system. All clients providing data (including all parameters, query strings, URLs,
cookies, HTTP header content, SOAP and other web services requests,
automated post-back content, and redirected content) must be validated before
processing.
 All input should get validated against a "white list" of allowed characters
(e.g. A-Z, a-z, 0-9). In situations where a "white list" filter cannot be used,
all input should get validated against a "blacklist" filter to block any
potentially hazardous characters.
 Examples of common hazardous characters include: <, >,", ', (, ),{,}, &, +,
\, /, Null bytes (%00), New line characters (%0d, %0a, \r, \n), Path
alteration characters (../ or..\)
 All input should get validated for expected range, length, format and data
type.

B. Client Side vs. Server Side Validation:


Though you have validated user inputs at client-side, an attacker can bypass it
using web proxy or disabling JavaScript. Hence, you need to ensure that any
input validation performed on the client-side should also perform on the server-
side.

C. File Upload
 Confirm authentication before allowing a file to be uploaded
 Limit the type of files that can be uploaded to only those types that are
needed for your business purposes.
 Validating extension of a file is not sufficient. Applications should
validate uploaded files are the expected type by checking file Content-
Type and/or headers.
 Never send the absolute file path to the client.
 Scan user uploaded d files for viruses and malware
Transerv Pvt Ltd.
Secure Coding Guidelines Date:03/05/17
Version-01
Rev No.00

4.4 Output Validation


 All untrusted output (e.g. input provided by users either directly or
indirectly via same or another application) has to get encoded before it
is returned to the client (e.g. using .NET HtmlEncode / UrlEncode,
Apache Jakarta Commons Lang Package).
 Contextually sanitize all output of un-trusted data to queries for SQL,
XML, and LDAP

4.5 Memory Management


 You should review all code that accepts input from users via the HTTP
request and ensure that it provides appropriate size checking on all
such inputs.
 It is highly recommended that all buffer overflows be addressed by
fixing the code where they originate.
 Periodically scan your web site with one or more of the commonly
available scanners that look for buffer overflow flaws in your server
products.
Transerv Pvt Ltd.
Secure Coding Guidelines Date:03/05/17
Version-01
Rev No.00

5 Secure Configuration of server


5.1 Server Configuration
A. Hardening of Web Server
 Avoid disclosing server information (e.g. Server version, OS name,
internal IP, favicon etc) through HTTP response header and error
pages.
 Disable directory listing.
 Keep web server version up to date.
 Allow only specific user to view binary and configuration of a web
server.
 You should not allow OPTIONS, PUT, DELETE, and TRACE and
CONNECT methods on web server. Allow only GET HEAD and POST
methods.
 It is recommended to use X-Frame-Options in headers to prevent click-
jacking attacks. Use only DENY or SAMEORIGIN value.
 Avoid using Server Side Includes.
 Force user to enable XSS filter built in web browser by adding XSS
protection (X-XSS-Protection “1; mode=block”) header.
 Disable HTTP 1.0 protocol.
 Disable installing/loading unwanted modules of web server.
B. Hardening of Server
 Avoid using unwanted protocols/ports.
 Keep your operating system/server up to date, especially security
patches.
 User accounts should have very strong passwords.
 Change passwords on a regular basis and do not reuse them.
 SSH hardening.
 Change the port from default to a non-standard one, if possible.
 Unnecessary services should be disabled.
 Maintain server logs; mirror logs to a separate log server
 Disable unwanted binaries
 Limit user accounts to accessing only what they need. Increased
access should only be on an as-needed basis.
 Maintain proper backups
 Ensure that the physical security of the server is maintained.
 Use Web Application Firewall to detect/prevent web attacks such as
DOS, bots/malware etc.
Transerv Pvt Ltd.
Secure Coding Guidelines Date:03/05/17
Version-01
Rev No.00

5.2 Data Protection


 Protect all cached or temporary copies of sensitive data stored on the
server from unauthorized access and purge those temporary working
files a soon as they are no longer required.
 Protect server-side source-code from being downloaded by a user.
 Do not store passwords, connection strings or other sensitive
information in clear text or in any non-cryptographically secure manner
on the client side.
 Remove comments in user accessible production code that may reveal
backend system or other sensitive information.
 Do not include sensitive information in HTTP GET request parameters.
 Disable auto complete features on forms expected to contain sensitive
information, including authentication.
Transerv Pvt Ltd.
Secure Coding Guidelines Date:03/05/17
Version-01
Rev No.00

6 Other General Practices

6.1 Error Handling and Logging


 Applications should 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.
 Implement generic error messages and use custom error pages.
 The application should handle application errors and not rely on the
server configuration.
 Restrict access to logs to only authorized individuals.
 Do not store sensitive information in logs, including unnecessary
system details, session identifiers or passwords.
 Log all input validation failures, authentication attempts (especially
failures), access control failures, apparent tampering events, system
exceptions.
 At a minimum, all logged audit events should record date and time of
the event, subject identity (e.g. user identification or IP address) and
event type identification/description

7 References & Links


https://www.owasp.org/index.php/Category:OWASP_Guide_Project

https://www.owasp.org/images/0/08/OWASP_SCP_Quick_Reference_Guide_v2.pdf

https://www.owasp.org/index.php/Secure_Coding_Cheat_Sheet

http://www.irdindia.in/journal_ijaeee/pdf/vol2_iss3/6.pdf

http://www.testandverification.com/wp-content/uploads/tvs-white-paper-secure-web-development-guide-
SAMPLE.pdf

Potrebbero piacerti anche