Home
Access Control
Application Security
Business Continuity Planning
Cryptography
CISSP Notes
CISA Notes
Network Security
Security Management
Security Architecture
SAP Audit
SAP Security
BW Security
SNOTE
SAPWorkloadAnalysis
Basis Tcodes
SAP Transport Management
SAP Installation
SAP Email Configuration
Operations Security
Physical Security
Managed Security Services
Law, Investigation and Ethics
Certification Help
About
Site Map
Other
e-mail me

 

 

 

Secure Code Audit

1                 Introduction

The scope of this audit is to determine that the code / application under review is secure.  The Availability, Integrity and Confidentiality of the application and data is maintained. A source code audit for security is differs from a source code audit for functionality. There is no easy way to audit code even though there are a lot of commercial tools available which claim to find all possible flaws and vulnerabilities. With the help of tools the most common mistakes will be detected. The best way would be to read the code and look among other things if function calls are safe, if multiple connections are created by an application or if the C run time rand function is used anywhere. The list of things to look for is never complete and that is what makes a code audit for security so expensive.      

1.1     Need for a Code Audit

Even though the application may be functioning as intended security code audit is necessary to determine that no one can maliciously exploit the same. A security code audit is necessary as the applications use multiple components interacting together with each other over various communication channels and the application is as secure as its weakest link. By itself the different components may have perform well in the unit tests or stress tests but when the whole application goes live and connects to third party data or service it becomes crucial to be sure that nothing is overlooked.

Sometimes Security Code Review may be necessary before your application is allowed to interact with other important third party applications as a way of assurance to those parties example Banks, Hospitals etc.

Before using any open source systems it becomes necessary to check the code to ensure that it does what it says it does.

1.2     Source Code v/s Penetration Testing

If security code audit finds flaws in the application so does Penetration Testing – so how is it different? If at all.

Well, Penetration testing will not and does not find all security bugs in any given application. The main difference between the two is that while conducting Source Code Audit you have the code to review but under Penetration Testing you try to break down the application by trial and error.

1.3     Determine the Components of the Application under Audit

Have a staff member walk you through a high level view of the application on a whiteboard or with the help of design documents to determine the main components of the application like interface, SQL database, authentication devices, data containers, way the various components interact with each other using sockets, pipes, TCP/IP, DCOM, SOAP etc. Make a list of the various languages, components and protocols used. The various user interfaces used etc. 

1.4     Prepare A Test Plan (Risk Assessment)

·        Now that you have understood the various modules of the application. 

·        Plan which of the codes you must check line by line and which ones will be sampled.

·         Find out if the components which are used in the application are  vulnerable to any common bugs or if any patches issued for the particular component has been properly applied.

·        Depending upon the data to be secured are the controls adequate? Sometimes the application itself might need to be secured.

·        Prepare detailed checklists and have all the teams members fill in their findings for the code that they check.

·        Get a list of parts of the module which failed during testing earlier and find out how it was solved. Was it a security issue? If not did the attempt to make it work result is bypassing security.

2                 Authentication

When ever it is necessary to protect as asset authentication becomes necessary. It is the process by which a resource satisfies itself that the user trying to gain access is in fact who it claims to be. A user could be a person or another program. Authentication checks for various things like password and user name or token or other biometric information.

Now when it comes to code audit try to find the reason why a particular authentication scheme is used. It is always directly propositional to the value of the asset to be protected.

The various authentication schemes are listed as under:   Basic authentication – this is the most primitive form of authentication in which the username and password are base64encodedand travel as clear text.

Hash or digest authentication: in this the password and username are neither stored nor exchanged in plaintext.

Forms based authentication:  this is the most commonly used in web applications but is vulnerable and the data is generally exchanged in clear text unless SSL or TLS is used.

X.509 authentication SSL and tls: this is commonly known as digital certificate. This is used when an application connects to a server the authenticity of the server is verified. It is possible to used client side certificates as well. 

IPsec: Short for IP Security, a set of protocols developed by the IETF to support secure exchange of packets at the IP layer. IPsec has been deployed widely to implement Virtual Private Networks (VPNs).

IPsec supports two encryption modes: Transport and Tunnel. Transport mode encrypts only the data portion (payload) of each packet, but leaves the header untouched. The more secure Tunnel mode encrypts both the header and the payload. On the receiving side, an IPSec -compliant device decrypts each packet.

For IPsec to work, the sending and receiving devices must share a public key. This is accomplished through a protocol known as Internet Security Association and Key Management Protocol/Oakley (ISAKMP/Oakley), which allows the receiver to obtain a public key and authenticate the sender using digital certificates.

RADIUS protocol is a widely used protocol for performing network authentication, authorization, and accounting (AAA) functions. It is used to control remote and local user access - via dial-in, VPN, firewall, wireless, LAN, or any combination. It is a key component of any network security architecture.

Check the code to ensure that the password policy has in fact been implemented. Look if the initial password issued has been set to expire at the first login. The user id and password are not allowed to be the same. Check if password size is hard coded as this will not allow longer passwords.

Kerberos is a network authentication protocol. It is designed to provide strong authentication for client/server applications by using secret-key cryptography. It is designed by the Massachusetts Institute of Technology (MIT)    

           

3            Session Management

As the stateless nature of HTTP compels solution developers to find other methods of uniquely tracking a visitor through a web application. Due to the way this protocol works, there is no inbuilt facility to uniquely identify or track a particular visitor (or session) within the application thus the connection between the visitors web browser and the web server is referred to as stateless.  Various methods of managing a visitor’s session are used, but the most popular method is through the use of unique session IDs. Many a times incorrectly applied session ID management schemes leave the application open to abuse and possible hijacking.

The most common method of tracking a visitor through a web site is by assigning a unique session ID and having this information transmitted back to the web server with every request. Once a visitor is authenticated the session ID is used to so that the visitor does not have to authenticate again again at every page request.

The commonly used methods used for maintaining session information are:

·        HTTP GET request

·        HTTP POST request

·        Through cookies

As the session ID is used by the application to grant access to certain areas of the website the security of the application is at risk through a weak session ID.

Factors determining the security of the session ID are the length and the randomness of the session ID.

Length of session ID

If the session ID is sufficiently long it is difficult to derive a valid ID within a reasonable time.

Randomness

In order to derive a strong session ID a very strong algorithm needs to be used to generate a session ID once a user is authenticated.

When using cookies ensure that:

·        Cookies do not hold critical information even temporarily; always store a reference in the cookie to a location on the server where the information is stored.

·        Encrypt information in cookies

·        Expiration time on the cookies should be set to the shortest possible in order to get the work done.

·        Avoid the use of permanent cookies.

 

4         Authorization and Elevation of Privilege

Once a user (can also be a program) is duly authenticated how much access it can have, what resources it can access and what manipulations it can perform is called authorization.

Authorization is finding out if the user, once identified, is permitted to have the resource. This is usually determined by finding out if that user is a part of a particular group, if that user has a subscription to access certain files or directories, or has a particular level of security clearance. Authorization is like finding your place in the ballpark once you are granted admission depending on the price of your ticket or your social standing.

 

5     Data and Input Validation

What is the difference between data and input? Data could be from a program or process and input is data received from a user (person). When forms are used to capture input data from users for a database query, it is necessary to validate the user's input before sending the query to the database. This is especially true while front ends for SQL statements that require a specific data type is used. When SQL statements containing date or numeric comparisons, anything other then what is expected or anything that exceeds the parameters of the given form should be discarded.

All data received from the user whether it is a person or a program should be validated and sanitized. Validation ensures correct processing by the data source. At no time should the input be accepted and passed on to the program for further processing.

 

 

6        Cross Site Scripting XSS

Cross site scripting also known as XSS occurs when a web application gathers malicious data from a user. The data is usually gathered in the form of a hyperlink which contains malicious content within it. The user will most likely click on this link from another website, instant message, or simply just reading a web board or email message. Usually the attacker will encode the malicious portion of the link to the site in HEX (or other encoding methods) so the request is less suspicious looking to the user when clicked on. After the data is collected by the web application, it creates an output page for the user containing the malicious data that was originally sent to it, but in a manner to make it appear as valid content from the website.

The application should be capable of discerning whether the session ID was delivered to the application from the client browser through the HTTP POST method, and not through a manipulated GET request. Converting HTTP POST into a GET request is a common method of conducting cross-site scripting attacks and other distributed brute force attacks.

Never trust user input and always filter metacharacters. This will eliminate the majority of XSS attacks. Converting < and > to &lt; and &gt; is also suggested when it comes to script output.

Buffer Overflows

A buffer is a contiguous allocated chunk of memory, such as an array or a pointer in C. In C and C++, there are no automatic bounds checking on the buffer, which means a user can write past a buffer.

Buffer overflows take place when a lot of code is injected into the buffer than it can hold. Unsafe C library functions such as strcpy (), strcat (), sprintf () and vsprintf () operate on null terminated strings and perform no bounds checking. gets () is another function that reads user input into a buffer from stdin until a terminating newline or EOF is found. The scanf () family of functions also may result in buffer overflows.

Stack execute invalidation: Because malicious code (for example, assembly instructions to spawn a root shell) is an input argument to the program, it resides in the stack and not in the code segment. Therefore, the simplest solution is to invalidate the stack to execute any instructions. Any code that attempts to execute any other code residing in the stack will cause a segmentation violation.

Compiler tools: Over the years, compilers have become more and more aggressive in optimizations and the checks they perform. Various compiler tools already offer warnings on the use of unsafe constructs such as gets (), strcpy () and the like.

Apart from offering warnings, modern compiler tools change the way a program is compiled, allowing bounds checking to go into compiled code automatically, without changing the source code. These compilers generate the code with built-in safeguards that try to prevent the use of illegal addresses. Any code that tries to access an illegal address is not allowed to execute.

These kind of tools, however, require the source code to be recompiled with a newer compiler. This requirement may be a problem if the application is not open source. Furthermore, it may affect the application's performance to a great extent. In some case, executable size and execution time may increase.

Most of the tools concentrate on preventing the return address from being overwritten, as most attacks occur this way. StackShield is a freely available tool that copies the return address of a function to a safe place (usually to the start of the data segment) at the start of the function. When the function terminates, it compares the two function return address, the one in the stack and the one stored in data segment. In the case of a mismatch, the function aborts immediately.

Because a function also can call another function, it needs to maintain a stack kind of structure for storing return addresses. Another tool available is StackGuard, which detects and defeats smash stacking attacks by protecting the return address on the stack from being altered. It places a canary word next to the return address whenever a function is called. If the canary word has been altered when the function returns, then some attempt has been made on the overflow buffers. It responds by emitting an alert and halting.

Dynamic run time checks: When an application has restricted access to prevent attacks. This method primarily relies on the safety code being preloaded before an application is executed. This preloaded component can either provide safer versions of the standard unsafe functions, or it can ensure that return addresses are not overwritten. Libsafe is one such tool. The libsafe library provides a way to secure calls to these functions, even if the function is not available. It makes use of the fact that stack frames are linked together by frame pointers. When a buffer is passed as an argument to any of the unsafe functions, libsafe follows the frame pointers to the correct stack frame. It then checks the distance to the nearest return address, and when the function executes, it makes sure that address is not overwritten.

8       Error Handling (safe mode)

The procedures to prevent programs running in the wrong order or running after failure of prior processing.

When your application displays error messages, it should not give away information that a malicious user might find helpful in attacking your system. For example, if your application unsuccessfully tries to log into a database, it should not display an error message that includes the user name it is using.

There are a number of ways to control error messages:

Configure the application not to show verbose error messages to remote (application) users.

If possible redirect errors to an application page.

Include error handling whenever practical and construct your own error messages. In the error handler, test to see if the user is local and react accordingly.

Create a global error handler at the page or application level that catches all unhandled exceptions and routes them to a generic error page. That way, even if a problem is not anticipated, at least users will not see an exception page.

 

9         Command Injection

Is a vulnerability which potentially can be exploited by malicious users or processes to compromise an application. This is done with a view to get elevated privileges on the system or application and also to corrupt or append data which the system or application uses for further processing with a view to circumvent the controls in a malicious way.

An attacker is able to execute arbitrary shell commands with the privileges of the web server process, such as user nobody.

The vulnerabilities are caused due to some input validation errors. This can e.g. be exploited by a malicious server to inject arbitrary shell commands when a specially crafted channel is joined.

Successful exploitation requires some user interaction.

 

10    Audit Program

 

 

 

 

 

Audit Reporting Procedures

 

 

 

Prior Audit Report

1.

Check if prior audit has been performed (eg. IT Audit)

Ask for copies of prior reports and check information bearing to the current audit.

 

 

 

2.

From copies of the prior audit regarding the queries raised check the following:

  • Check the current status of each query.
  • If the query is still pending make a not of it your report with the explanations or other steps taken towards mitigation.

 

 

 

Audit Report

3.

The auditor in charge of the audit is responsible for preparing a draft audit report.

 

 

4.

The draft is given to the Audit Manager for comment and review.

 

 

5.

The draft report is submitted to the Audit Director for review.

 

 

6.

The draft report is distributed and discussed with the auditee for clarity and correctness.

 

 

7.

Auditee comments are incorporated in the final report.

 

 

8

The final report is sent out y the Audit Manager.

 

 

9

The auditor is responsible for ensuring that all draft reports and a copy of the final report are appropriately filed in the audit work papers.

 

 

 

AUDIT FINDINGS

 

 

10

At the request of the Audit committee,

 

 

 

Information Gathering for Audit

Background:

Internal Audit should obtain a detailed understanding of the application system under review. Meetings should be scheduled with IT Systems Support staff and the business user areas that use critical application system functions. A through understanding of the application should be developed by the auditor with the help of design documents before the fieldwork begins.

 

 

 

Audit Procedures

1

Ask  for the following documents:

  • Copy of Design documents relating to this application.
  • Copy of User Manual detailing the proper use of the application if any.
  • List of users and their levels of access to the application.
  • List of people who have access to the source code of the application and are authorized to change or enhance the same.
  • Backup details pertaining to the application.
  • List of IT staff responsible for providing support for the application.
  • Details of version control and change control maintained.

 

 

2

Understand the main issues pertaining to the application under review and document the profiles of the team members responsible for the application.

 

 

3

Interview the other user departments and ask them their concerns and issues with the application.

 

 

4

Send a letter to Audit Manager for review and approval detailing the scope of the audit from the meetings with the IT team responsible for the application and the various user departments regarding the scope of the audit.

 

 

 

APPLICATION CONTROLS

In order to prevent loss, modification or misuse of applications appropriate controls and audit trails or activity logs should be designed into applications.

 

 

 

Review system documentation obtained to verify that it contains a description of :

   * Transaction types processed

   * Interaction between various application components.

   * System Interfaces

   * Critical program names and processing functions

   * Batch job schedule and critical processing performed

   * Security Administration and access control procedures

 

 

 

INPUT CONTROLS

Any data entered by the user should be validated by the application before it is further processed. The application should explicitly deny any attempt by the user to insert any data other then what is expected or omit any required field.

 

 

 

Verify whether input checks to detect validity and integrity

·     Out of range values.

·       Invalid characters in data fields

·       Missing or incomplete data

·       Exceeding upper and lower data volume limits

·       Unauthorized or inconsistent control data review of the content of key fields.

·       Procedures for responding to validation errors.

 

 

 

OUTPUT CONTROLS

Data output from either user or an application should be checked and validated before further use.

 

 

 

Check and verify if

 

Output data is checked to test whether output data is  reasonable

 

 

 

Reconciliation controls counts to ensure processing of all data are in place.

 

 

 

Sufficient information is provided to subsequent processing system to determine the accuracy, completeness, precision and classification of information.

 

 

 

Procedures for responding to output validation tests are in place.

 

 

 

APPLICATION CODE

The Development Group should ensure that the access to system files is controlled so as to maintain system integrity

 

Check and verify that

 

Updation of operation program libraries should be performed with the proper authorization.

 

 

 

Operational systems should only hold executable code.

 

 

 

And audit trail should be maintained of all updation to operational program libraries.

 

 

 

Previous version of software is retained as contingency.

 

 

 

Source Code

In order to protect source code from corruption strict control should be maintained over access to source codes libraries.

 

 

 

Verify that source code libraries are not held in operational systems.

 

 

 

Verify that each application has a designated person in charge of the source code libraries.

 

 

 

Determine that the support staff’s access to source code is strictly documented, authorized and regulated.

 

 

 

Verify that the applications under development are maintained separate from operational source code files.

 

 

 

Verify that updation of source code is properly authorized.

 

 

 

Verify that the program listings are properly protected.

 

 

 

Determine that an audit trail of all access to source code files is maintained.

 

 

 

Verify that maintenance or copying of source code is subject to strict change control procedures.

 

 

 

Outsource Software Development

 

 

 

That the proper licensing agreement and code ownership agreements are in place.

 

 

 

Whether the necessary audit or certification of third party code is in place.

 

 

 

Whether proper escrow arrangements are made in the event of failure of third party.

 

 

 

Source code submitted by the third party is checked and audited for malware of covert channel and duly sanitized.

 

 

 

CHANGE CONTROL

In order to protect the integrity of code there should be a strict control of implementation changes.

 

 

 

Verify that a record of authorization level for access to code is maintained.

 

 

 

Verify that changes are submitted only by users authorized to access it.

 

 

 

Verify that controls are in place so that the integrity of code is not compromised by changes.

 

 

 

Verify that a list is maintained of all code that requires amendment.

 

 

 

Verify that necessary permission is sought before any change takes place.

 

 

 

Verify that prior to any change authorized users have accepted the change.

 

 

 

Determine if necessary controls are in place so that change to code does not cause major disruptions in business.

 

 

 

Verify that proper documentation is maintained at the completion of each change and old documentation is accordingly updated.

 

 

 

Verify that proper audit trail is maintained of all changes.

 

 

 

If changes are made to third party software

 

 

 

Verify that controls are in place to see that code is not compromised by change.

 

 

 

Verify that proper consent of the vendor is obtained.

 

 

 

Verify if it is possible for vendor to make the necessary change.

 

 

 

Determine as to who will be responsible for the future maintenance and support of software.

 

 

 

SEGREGATION OF DUTIES

The basic principle that the person who initiates an event should not be the one who authorizes it should be followed.

 

 

 

Verify that the development, test and operational functions are segregated.

 

 

 

Verify that the development and operational application is in different domain and directory.

 

 

 

Verify that the development and testing activities are separated.

 

 

 

Verify that the development utilities like compliers, editors are not accessible from the operational environment.

 

 

 

Verify that proper rules are followed for the transfer of application from development to operational status.

 

 

 

Verify that Operational and Test systems have proper menus identifying them as such.

 

 

 

Verify that different passwords and log-on procedures are maintained for operational and test systems.

 

 

 

Verify that the development staff has access to operational systems only for support purposes and the same is well documented.

 

 

 

ACCESS CONTROLS

Access to data and code should be controlled and documented.

 

 

1

And access control policy should clearly mention the levels of access for different jobs functions.

 

 

2

Users should be granted access only to that part of the program which they need to do their jobs properly and it does not compromise segregation of duties.

 

 

3

Check documentation to see that distinction is made between changes in information labels initiated by the system and those initiated by the user.

 

 

4

Determine that proper user registration and de-registration procedures are followed.

 

 

5

Verify that users are given written statements of their access and are required to sign the same indicating they understand the same.

 

 

6

Verify if a formal record is kept of all persons registered to access the system with their levels of access.

 

 

7

Verify that the access rights of all users who have changed their jobs or left the company are terminated.

 

 

8

Check that the old user ids are not issued to new users.

 

 

9

Verify that an authorization process and record of all access granted is maintained. Access is not granted until authorization process is complete.

 

 

10

Verify that controls are in place to ensure that unattended user equipment is appropriately protected.

 

 

11

Verify that controls are in place to check that users terminate active sessions when finished, log-off mainframe computers when the session is finished, secure PC’s or terminals from unauthorized use by a password or other physical control when not in use.

 

 

 

Remote Users

When access is granted to remote users to work from home or from other places.

 

 

 

Obtain a copy of the Remote Access Policy and verify that it is read and understood by all users having access.

 

 

 

Verify that defines the work permitted, time between which access may be granted, the class of information which may held and the systems and services which the user may be entitled to.

 

 

 

Verify that the policy defines the method for securing remote access

 

 

 

Verify that when the user is logged on to the system strict rules regarding physical security, family and visitor access are observed.

 

 

 

Verify that the policy clearly explains rules regarding hardware and software support and maintenance.

 

 

 

Verify the rules in place pertaining to the back up of the work done by the remote users

 

 

 

Determine that all system access by remote users is strictly monitored and recorded.

 

 

 

Determine that proper controls are in place for the revocation of authority, access rights and the return of equipment once the remote access is no longer required.

 

 

 

PHYSICAL ACCESS CONTROLS

Buildings containing application processing areas should be unobtrusive and give no indication of their purpose, with no obvious signs, outside or inside the building identifying that presence of information processing activities.

 

 

 

Determine that only authorized personnel are aware of the existence of, or activities within, a secure processing area on a need to know basis.

 

 

 

Determine that access to secure application processing facilities is controlled and restricted and proper authentication controls e.g. Swipe cards or biometrics with PIN, should be used to authorize and validate all access. An audit trail of all access is maintained securely

 

 

 

Verify that proper records are maintained regarding review and update of access rights to secure areas.

 

 

 

PROBLEM TRACKING (Event logging) AND MANAGEMENT PROCEDURES

Once the application becomes operational any problems associated with its use should be reported to the support staff maintaining the application.

 

 

 

Verify that any security relevant event is preserved and investigated.

 

Verify that audit logs are maintained for

 

 

  • Logging facility being de-activated.
  • Alterations to the messages generated.
  • Log files being edited or deleted.
  • Log file media becoming exhausted and either failing to record events or overwriting itself.

 

 

 

CRYPTOGRAPHIC CONTROLS

These controls are used to protect confidentiality, authenticity and integrity.

 

 

 

Obtain the management policy in place for cryptographic controls.

 

 

 

Verify that proper controls to key management, including methods to deal with the recovery of encrypted information case of lost, compromised or damaged keys is in place.

 

 

 

Verify that roles and responsibilities for the implementation of the policy and key management are properly documented.