Google search

Search IT Security Blog:


Showing posts with label Database Security. Show all posts
Showing posts with label Database Security. Show all posts

Saturday, October 10, 2009

Database Security - Threats and Countermeasures

Database Security - Threats and Countermeasures

Database security begins with physical security for the computer systems that host the DBMS. No DBMS is safe from intrusion, corruption, or destruction by people who have physical access to the computers. After physical security has been established, database administrators must protect the data from unauthorized user and from unauthorized access by authorized users.There are three main objects when designing a secure database application, and anything prevents from a DBMS to achieve these goals would be consider a threat to Database Security.

Integrity

Database integrity refers to the requirement that information be protected from improper modification. Modification of data includes creation, insertion, modification, changing the status of data, and deletion.Integrity is lost if unauthorized changes are made to the data by either intentional or accidental acts.

To prevent the loss of integrity from happening-->Only authorized users should be allowed to modify data.
e.g. Students may be allowed to see their grades, yet not allowed to modify it.

Availability

Authorized user or program should not be denied access. For example, an instructor who wishes to change a grade should be allowed to do so.

Secrecy

Information should not be disclosed to unauthorized users. For example, a student should not be allowed to examine other students¡¦ grades.

To achieve these objectives, a clear and consistent security policy should be developed to describe what security measures must be enforced. In particular, we must determine what part of the data is to be protected and which users get access to which portions of the data. Next, the security mechanisms of the underlying DBMS and operating system, as well as external mechanisms, such as securing access to buildings, must be utilized to enforce the policy. We emphasize that security measures must be taken at several levels.

Why is database security important?

If the loss of system or data integrity is not corrected, continued use of the contaminated system or corrupted data could result in inaccuracy, fraud, or erroneous decisions. In addition, unauthorized, unanticipated, or unintentional disclosure could result in loss of public confidence, embarrassment, or legal action against the organization.

Countermeasures to database security threats

Inference control -->The corresponding countermeasure to statistical database security.

Statistical database is a database which contains specific information on individuals or events but is intended to permit only statistical queries. (e.g. averages, sums, counts, maximums, minimums and standard deviations. However, it is possible to obtain confidential data on individuals by using only statistical queries. Inference control technique are used to prevent this from happening. (e.g. we can prohibit sequences of queries that refer repeatedly to the same population of tuples.

(2) Flow Control

"Flow control regulates the distribution or flow of information among accessible objects. A flow between object X and object Y occurs when a program reads values from X and writes values into Y. Flow controls check that information contained in some objects does not flow explicitly or implicitly into less protected objects. Thus, S user cannot get indirectly in Y what he or she cannot get directly from X." Elmasri,Navathe(P747)

(3) Encryption

"The idea behind encryption is to apply an encryption algorithm to the data, using a user-specified or DBA-specified encryption key. The output of the algorithm is the encrypted version of the data. There is also a decryption algorithm, which takes the encrypted data and a decryption key as input and then returns the original data." Elmasri,Navathe(P709)

(4) Access Control

A database for an enterprise contains a great deal of information and usually has several groups of users. Most users need to access only a small part of the database to carry out their tasks. Allowing users unrestricted access to all the data can be undesirable, and a DBMS should provide mechanisms to control access to data. The main idea behind access control is to protect unauthorized persons from accessing the system.

How it works?

1:Discretionary Access Control

Discretionary access control is based on the idea of access rights, or privileges, and mechanisms for giving users such privileges. A privilege allows a user to access some data object in a certain manner (e.g. to read or modify). A user who creates data object such as a table or a view automatically gets all applicable privileges on that object and the user can also propagate privileges using "Grant Option". The DBMS subsequently keeps track of how these privileges are granted to other users, and possibly revoked, and ensures that at all times only users with the necessary privileges can access an object.

SQL Syntax

SQL supports discretionary access control through the GRANT and REVOKE commands.

The GRANT command gives users privileges to base tables and views.

The REVOKE command cancels uses' privileges.

For example: GRANT privilege1, privilege2, ... ROVOKE privilege1, privilege2, ...
ON object_name ON object_name
TO user1, user2, ... ; FROM user1, user2, ... ;

GRANT SELECT, ALTER ROVOKE SELECT, ATLER
ON student ON student
TO db2_14 FROM db2_14

Example from Textbook (R.Elmasri, S. B. Navathe, Fundamentals of Database Systems, Ed.4, Addison-Wesley, 2003.Chapter 23)

Suppose that A1 creates the two base relations EMPLOYEE and DEPARTMENT

EMPLOYEE NAME SSN BDATE ADDRESS SEX SALARY DNO DEPARTMENT DNUMBER DNAME MGRSSN

A1 is then the owner of these two relations and hence has all the relation privileges on each of them. A1 wants to grant to account A2 the privilege to insert and delete tuples in both of these relations

GRANT INSERT, DELETE ON EMPLOYEE, DEPARTMENT TO A2;

A2 cannot grant INSERT and DELETE privileges on the EMPLOYEE and DEPARTMENT tables, because A2 was not given the GRANT OPTION in the preceding command.

GRANT SELECT ON EMPLOYEE, DEPARTMENT TO A3 with GRANT OPTION;

The clause WITH GRANT OPTION means that A3 can now propagate the privilege to other accounts by using GRANT. For example, A3 can grant the SELECT privilege on the EMPLOYEE relation to A4 by issuing the following command:

GRANT SELECT ON EMPLOYEE TO A4;

Now suppose that A1 decides to revoke the SELECT privilege on the EMPLOYEE relation from A3; A1 then can issue this command:

REVOKE SELECT ON EMPLOYEE FROM A3;

The DBMS must now automatically revoke the SELECT privilege on EMPLOYEE from A4, too, because A3 granted that privileges to A4 and A3 does not have the privilege any more.

MySQL grant revoke syntax

Limits on propagation of privileges

The techniques to limit the propagation of privileges have been developed, but they have not been implemented in most DBMSs and are not a part of SQL.

Horizontal propagation limits:
An account B given the GRANT OPTION can grant the privilege to at most i other accounts.

Vertical Propagation limits:
It limits the depth to which an account can pass on the privilege in terms of levels.

Pros and Cons of discretionary access control

Advantages:

Being flexible and suitable for various types of systems and application like commercial and industrial environtments.

Disadvantages:

Not providing real assurance on the satisfaction of the protection requirements.
Not imposing any restriction on the usage of information once it is obtained by a user and makes system vulnerable to attacks.

2:Mandatory Access control

Mandatory access control are aimed at addressing such loopholes in discretionary access control. The popular model for mandatory access control called the Bell-LaPadula model, is described in terms of objects, subjects, security classes, and clearances. Each database object is assigned a security class, and each subject is assigned clearance for a security class.

The Bell-LaPadula model imposes two restrictions on all reads and writes of database objects:

1: Simple Security Property: Subject S is allowed to read object O only if class(S)≥ class(O). For example, a user with TS (top
secret) clearance can read a table with C (confidential) clearance, but a user with C(Confidential) clearance is not allowed to
read a table with TS (top secret) classification.

2. *-Property: Subject S is allowed to write object O only if class(S)≤ class(O). For example, a user with S (secret) clearance can
write only objects with S (secret) or TS (top secret) classification.

If discretionary access controls are also specified, these rules represent additional restrictions. Therefore, to read or write a database object, a user must have the necessary privileges and the security classes of the user and the object must satisfy the preceding restrictions.

Advantages: Mandatory policies ensure a high degree of protection.-->suitable for military types of applications, which require a
high degree of protection.

Disadvantages: Applicable to very few environment for being too rigid.

Current State and Future-->Role-Based Access Control

Role-Based Access Control emerged rapidly in the 1990s and it's adopted by most DBMS since then. Its basic concept is that privileges are associated with roles, and users are assigned to appropriate roles. Roles can then be granted to users and other roles. (Roles can be created and destroyed using the CREATE ROLE and DROP ROLE commands.) RBAC appears to be a viable alternative to traditional discretionary and mandatory access controls; it ensures that only authorized users given access to certain data or resources.
Advantages of RBAC

A properly-administered RBAC system enables users to carry out a broad range of authorized operations, and provides great flexibility and breadth of application. System administrators can control access at a level of abstraction that is natural to the way that enterprises typically conduct business. This is achieved by statically and dynamically regulating users' actions through the establishment and definition of roles, role hierarchies, relationships, and constraints. Thus, once an RBAC framework is established for an organization, the principal administrative actions are the granting and revoking of users into and out of roles. Role associations can be established when new operations are instituted, and old operations can be deleted as organizational functions change and evolve. This simplifies the administration and management of privileges; roles can be updated without updating the privileges for every user on an individual basis. With these outstanding features and the easier deployment over the Internet, Role-Based Access Control undoubtedly will continue to be dominant in the future.

Conclustion
With the extensive use of database systems nowadays, everyone could become a victim of database crime, and a single database crime event might even result in a serious consequence on individual or public affairs. Because of that, database developers are always trying to create new technique to prevent unauthorized, unanticipated or unintentional disclosure of data from happening. No matter how good a security measure or technique is, database administrators always play a very important role in database securities issues. In addition to user account management, database administrator also contributes to developing security policy and enforcing the security-related aspects of a database design. But at the same time, advanced algorithms and technologies used to increase database security also raise challenges to both database developers and administrators. While databases with inference control, access control, encryption, etc. have become more and more complicated for developers, we can see that DBAs will need more knowledge to become qualified in the future.

Database Security Part 2

Database Security

Nowadays, databases are cardinal components of any web based application by enabling websites to provide varying dynamic content. Since very sensitive or secret informations can be stored in such database, you should strongly consider to protect them somehow.

To retrieve or to store any information you need to connect to the database, send a legitimate query, fetch the result, and close the connecion. Nowadays, the commonly used query language in this interaction is the Structured Query Language (SQL).

As you can realize, PHP cannot protect your database by itself. The following sections aim to be an introduction into the very basics of how to access and manipulate databases within PHP scripts.

Keep in mind this simple rule: defence in depth. In the more place you take the more action to increase the protection of your database, the less probability of that an attacker succeeds, and exposes or abuse any stored secret information. Good design of the database schema and the application deals with your greatest fears.
Designing Databases

The first step is always to create the database, unless you want to use an existing third party's one. When a database is created, it is assigned to an owner, who executed the creation statement. Usually, only the owner (or a superuser) can do anything with the objects in that database, and in order to allow other users to use it, privileges must be granted.

Applications should never connect to the database as its owner or a superuser, because these users can execute any query at will, for example, modifying the schema (e.g. dropping tables) or deleting its entire content.

You may create different database users for every aspect of your application with very limited rights to database objects. The most required privileges should be granted only, and avoid that the same user can interact with the database in different use cases. This means that if intruders gain access to your database using one of these credentials, they can only effect as many changes as your application can.

You are encouraged not to implement all the business logic in the web application (i.e. your script), instead to do it in the database schema using views, triggers or rules. If the system evolves, new ports will be intended to open to the database, and you have to reimplement the logic in each separate database client. Over and above, triggers can be used to transparently and automatically handle fields, which often provides insight when debugging problems with your application or tracing back transactions.
Connecting to Database

You may want to estabilish the connections over SSL to encrypt client/server communications for increased security, or you can use ssh to encrypt the network connection between clients and the database server. If either of them is done, then monitoring your traffic and gaining informations in this way will be a hard work.
Encrypted Storage Model

SSL/SSH protects data travelling from the client to the server, SSL/SSH does not protect the persistent data stored in a database. SSL is an on-the-wire protocol.

Once an attacker gains access to your database directly (bypassing the webserver), the stored sensitive data may be exposed or misused, unless the information is protected by the database itself. Encrypting the data is a good way to mitigate this threat, but very few databases offer this type of data encryption.

The easiest way to work around this problem is to first create your own encryption package, and then use it from within your PHP scripts. PHP can assist you in this case with its several extensions, covering a wide variety of encryption algorithms. The script encrypts the data be stored first, and decrypts it when retrieving. See the references for further examples how encryption works.

In case of truly hidden data, if its raw representation is not needed (i.e. not be displayed), hashing may be also taken into consideration. The well-known example for the hashing is storing the MD5 hash of a password in a database, instead of the password itself.
Example 1.5. Using hashed password field
$query = sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
addslashes($username), md5($password));
$result = pg_exec($connection, $query);

// querying if user submitted the right password
$query = sprintf("SELECT 1 FROM users WHERE name='%s' AND pwd='%s';",
addslashes($username), md5($password));
$result = pg_exec($connection, $query);

if (pg_numrows($result) > 0) {
echo "Welcome, $username!";
}
else {
echo "Authentication failed for $username.";
} ?>
SQL Injection

Many web developers are unaware of how SQL queries can be tampered with, and assume that an SQL query is a trusted command. It means that SQL queries are able to circumvent access controls, thereby bypassing standard authentication and authorization checks, and sometimes SQL queries even may allow access to host operating system level commands.

Direct SQL Command Injection is a technique where an attacker creates or alters existing SQL commands to expose hidden data, or to override valuable ones, or even to execute dangerous system level commands on the database host. This is accomplished by the application taking user input and combining it with static parameters to build a SQL query. The following examples are based on true stories, unfortunately.

Owing to the lack of input validation and connecting to the database on behalf of a superuser or the one who can create users, the attacker may create a superuser in your database.

Example 1.6. Splitting the result set into pages ... and making superusers (PostgreSQL and MySQL)

$query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
// with PostgreSQL
$result = pg_exec($conn, $query);
// with MySQL
$result = mysql_query($query); ?>

Normal users click on the 'next', 'prev' links where the $offset is encoded into the URL. The script expects that the incoming $offset is decimal number. However, someone tries to break in with appending form of the following to the URL
// in case of PostgreSQL
0;

insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
select 'crack', usesysid, 't','t','crack'
from pg_shadow where usename='postgres';
--

// in case of MySQL
0;
UPDATE user SET Password=PASSWORD('crack') WHERE user='root';
FLUSH PRIVILEGES;

If it happened, then the script would present a superuser access to him. Note that 0; is to supply a valid offset to the original query and to terminate it.
Note:

It is common technique to force the SQL parser to ignore the rest of the query written by the developer with -- which is the comment sign in SQL.

A feasible way to gain passwords is to circumvent your search result pages. What the attacker needs only is to try if there is any submitted variable used in SQL statement which is not handled properly. These filters can be set commonly in a preceding form to customize WHERE, ORDER BY, LIMIT and OFFSET clauses in SELECT statements. If your database supports the UNION construct, the attacker may try to append an entire query to the original one to list passwords from an arbitrary table. Using encrypted password fields is strongly encouraged.

Example 1.7. Listing out articles ... and some passwords (any database server)

WHERE size = '$size'
ORDER BY $order LIMIT $limit, $offset;";
$result = odbc_exec($conn, $query); ?>

The static part of the query can be combined with another SELECT statement which reveals all passwords:
'
union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable;
--

If this query (playing with the ' and --) were assigned to one of the variables used in $query, the query beast awakened.

SQL UPDATEs are also subject to attacking your database. These queries are also threatened by chopping and appending an entirely new query to it. But the attacker might fiddle with the SET clause. In this case some schema information must be possessed to manipulate the query successfully. This can be acquired by examing the form variable names, or just simply brute forcing. There are not so many naming convention for fields storing passwords or usernames.
Example 1.8. From resetting a password ... to gaining more privileges


But a malicious user sumbits the value ' or uid like'%admin%'; -- to $uid to change the admin's password, or simply sets $pwd to "hehehe', admin='yes', trusted=100 " (with a trailing space) to gain more privileges. Then, the query will be twisted:
$query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%'; --";

// $pwd == "hehehe', admin='yes', trusted=100 "
$query = "UPDATE usertable SET pwd='hehehe', admin='yes', trusted=100 WHERE ...;" ?>

A frightening example how operating system level commands can be accessed on some database hosts.
Example 1.9. Attacking the database host's operating system (MSSQL Server)
$result = mssql_query($query); ?>

If attacker submits the value a%' exec master..xp_cmdshell 'net user test testpass /ADD' -- to $prod, then the $query will be:
WHERE id LIKE '%a%'
exec master..xp_cmdshell 'net user test testpass /ADD'--";
$result = mssql_query($query); ?>

MSSQL Server executes the SQL statements in the batch including a command to add a new user to the local accounts database. If this application were running as sa and the MSSQLSERVER service is running with sufficient privileges, the attacker would now have an account with which to access this machine.
Note:

Some of the examples above is tied to a specific database server. This does not mean that a similar attack is impossible against other products. Your database server may be so vulnerable in other manner.
Avoiding techniques

You may plead that the attacker must possess a piece of information about the database schema in most examples. You are right, but you never know when and how it can be taken out, and if it happens, your database may be exposed. If you are using an open source, or publicly available database handling package, which may belong to a content management system or forum, the intruders easily produce a copy of a piece of your code. It may be also a security risk if it is a poorly designed one.

These attacks are mainly based on exploiting the code not being written with security in mind. Never trust on any kind of input, especially which comes from the client side, even though it comes from a select box, a hidden input field or a cookie. The first example shows that such a blameless query can cause disasters.

* Never connect to the database as a superuser or as the database owner. Use always customized users with very limited privileges.
* Check if the given input has the expected data type. PHP has a wide range of input validating functions, from the simplest ones found in Variable Functions and in Character Type Functions (e.g. is_numeric(), ctype_digit() respectively) onwards the Perl compatible Regular Expressions support.
*

If the application waits for numerical input, consider to verify data with is_numeric(), or silently change its type using settype(), or use its numeric representation by sprintf().
Example 1.10. A more secure way to compose a query for paging
$query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";

// please note %d in the format string, using %s would be meaningless
$query = sprintf("SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;",
$offset); ?>
* Quote each non numeric user input which is passed to the database with addslashes() or addcslashes(). See the first example. As the examples shows, quotes burnt into the static part of the query is not enough, and can be easily hacked.
* Do not print out any database specific information, especially about the schema, by fair means or foul. See also Error Reporting and Error Handling and Logging Functions.
* You may use stored procedures and previously defined cursors to abstract data access so that users do not directly access tables or views, but this solution has another impacts.

Besides these, you benefit from logging queries either within your script or by the database itself, if it supports. Obviously, the logging is unable to prevent any harmful attempt, but it can be helpful to trace back which application has been circumvented. The log is not useful by itself, but through the information it contains. The more detail is generally better.

Database security

Database security

Database security is the system, processes, and procedures that protect a database from unintended activity. Unintended activity can be categorized as authenticated misuse, malicious attacks or inadvertent mistakes made by authorized individuals or processes. Database security is also a specialty within the broader discipline of computer security.
Traditionally databases have been protected from external connections by firewalls or routers on the network perimeter with the database environment existing on the internal network opposed to being located within a demilitarized zone. Additional network security devices that detect and alert on malicious database protocol traffic include network intrusion detection systems along with host-based intrusion detection systems.

Database security is more critical as networks have become more open.
Databases provide many layers and types of information security, typically specified in the data dictionary, including:
• Access control
• Auditing
• Authentication
• Encryption
• Integrity controls

Database security can begin with the process of creation and publishing of appropriate security standards for the database environment. The standards may include specific controls for the various relevant database platforms; a set of best practices that cross over the platforms; and linkages of the standards to higher level polices and governmental regulations.

Protecting the data in our enterprise databases is extremely important. At one level we have the database authorization and roles built directly into the DBMS products, GRANT and REVOKE statements that can be used to authorize access to database objects, resources and statements. This level of database security is important, but is by no means sufficient. And many DBMS products are evolving to deliver additional security.

For example, DB2 offers multi-level security, which gives the ability to protect data and authorize use of data at the row level. A multilevel security system allows the protection of data based on both traditional discretionary access controls, and controls that check the sensitivity of the data itself through mandatory access controls. These mandatory access controls are at the heart of a multilevel security environment, which prevents unauthorized users from accessing information at a classification they are not authorized to, or changing the classification of information they do have access to. These mandatory access controls provide a way to segregate users and their data from other users and their data regardless of the discretionary access they are given though access lists, etc. The primary arena where multilevel security is valuable is government agencies that need a security environment that keeps information classified and compartmentalized between users.

Another method to better secure database data is through encryption. But there are problems with encrypting database data. First of all, encryption is supported differently in every DBMS. Also, performance is an issue. It takes CPU cycles to encrypt and decrypt that data, so is security more important than rapid access? Even more problematic is indexed access. If indexed columns are encrypted, the DBMS will sort the encrypted strings -- and they won't match the real, unencrypted data.

There are actually two types of encryption with respect to database data - encryption at rest and encryption over the wire. Basically, encrypting the database data on disk. But there are also encryption products that will encrypt the data before it is sent across the network and decrypt it once it is received. Encryption over the wire is helpful to prevent surreptitious access to data as it flies throughout your network, but it won't help combat thieves who target the database files on disk.
Another burgeoning field is database access auditing. This type of solution monitors database activity (INSERT, UPDATE, DELETE, and even SELECT) and reports on who is accessing and changing what data when. Such information can be very helpful to ensure that only appropriate personnel are accessing appropriate data within the database. Such solutions can help to track the activity of privileged users (such as SYSADMs). And they can be invaluable in terms of being in compliance with regulations such as PCI-DSS and HIPAA.

Taking things yet another step further, auditing data can be achieved in an active manner - - let’s call it data trend monitoring. This type of solution monitors all database requests as they happen and discovers access patterns and trends. Configure policy-based access and control such that invalid data requests and/or modifications can be stopped and alerts can be generated when such actions are attempted. Trends can be monitored so that any behavior outside of the norm can be highlighted and investigated. This can be important, for example, to watch for suspect activity initiated by authorized users. Some analysts suggest that such activity is more pervasive and potentially damaging to data than external attacks. And it can be very hard to detect.

Database

Database

A database is an organized collection of information. Common examples of a database would be a telephone book, mailing list, recipe book, or a check book.
The term database is a little different in Access. An Access database refers to a set of data related to a specific purpose or topic, along with the tools needed to utilize and manipulate that data, such as sorting, extracting, or summarizing.

Database Terminology

The first term to become familiar with is a Table. An Access table is a list of related information presented in a column/row format.

A table is broken down into additional components such as a row in a table. Each row is referred to as a Record. So if you look up your information in a telephone book you are reviewing your record.

Each column in a table is a category of information referred to as a Field. In a telephone book the column of phone numbers would be considered the Phone Number field.
One item of data, such as a single phone number, is called a Data Value.

Relational Database Concepts

Prior to understanding the concept of a Relational Database you should first understand the concept of a Flat File Database. A spreadsheet would be considered a Flat File database.

Relationships

Each relationship will have a Primary (parent) table and a Related (child) table as previously described.

An easy way to determine the Primary table in the relationship is to note the Primary key. Typically the Primary table is the table that holds the Primary key field in the relationship.
In the above image, the Customers table is the Primary table and the Orders table would be the Related table.

How each table is related to each other is another key concept in a relational database.
There are two main types of Relationships: One-to-One and One-to-Many.