Đang xem trước 10 trên tổng 15 trang, để tải xuống xem đầy đủ hãy nhấn vào bên trên
Vietnam and Japan Joint
ICT HRD Program
Content
1. Environment variables
2. Setting Response Header
3. Encoding and escaping
4. Cross site scripting
ICT 5 Web Development
Chapter 10. Web Techniques and
Security
Nguyen Thi Thu Trang
trangntt@soict.hut.edu.vn
2
1. Environment variables
1.1. Global arrays
If the register_globals option in php.ini
is enabled (it is disabled by default),
default) PHP
creates a separate global variable for
every form parameter, every piece of
request information, and every server
configuration value.
This functionality is convenient but
dangerous, as it lets the browser provide
initial values for any of the variables in
your program
Server
configuration and request
i f
information
ti
– form parameters
– Cookies
can be accessible in three different
ways from your PHP scripts.
scripts
Æ Referred to as EGPCS
(Environment, GET, POST, Cookies,
and Server).
3
4
1
1.1. Global arrays (2)
1.1. Global arrays (2)
$_COOKIE
– Contains any cookie values passed as part of the
request, where the keys of the array are the names of
the cookies
– Contains information about any uploaded files
$_GET
– Contains any parameters that are part of a GET request,
where the keys of the array are the names of the form
parameters
$_FILES
$_SERVER
– Contains useful information about the web
server, as described in the next section
$_ENV
– Contains the values of any environment
variables, where the keys of the array are the
$ POST
$_POST
– Contains any parameters that are part of a POST
request, where the keys of the array are the names of
the form parameters
names of the environment variables.
5
6
1.1. Global arrays (2)
1.2. Server Information
PHP also creates automatically
– $_REQUEST
$ REQUEST
The $_SERVER array contains a lot of
useful information from the web server
– SERVER_SOFTWARE
contains
the elements of the $_GET, $_POST, and
$_COOKIE arrays all in one array variable.
A
string that identifies the server (e.g.,
"Apache/1.3.33 (Unix) mod_perl/1.26 PHP/5.0.4").
– $PHP_SELF
– SERVER_NAME
holds
the name of the current script, relative to the
document root
can be also accessible as $
$_SERVER[
SERVER['PHP
PHP_SELF
SELF']]
The
hostname, DNS alias, or IP address for selfselfreferencing URLs (e.g.,
(e g "www
"www.example.com
www example com")
com")).
– HTTP_USER_AGENT
The
string the browser used to identify itself (e.g.,
"Mozilla/5.0 (Windows 2000; U) Opera 6.0 [en]“)
7
8
2
1.2. Server Information (2)
1.2. Server Information (3)
SERVER_PROTOCOL
– The name and revision of the request protocol (e.g.,
(e g
"HTTP/1.1").
– Everything after the ? in the URL (e.g.,
(e g
"name=Fred&age=35").
SERVER_PORT
– The server port number to which the request was sent
(e.g., "80").
REMOTE_HOST
– The hostname of the machine that requested this page
(e.g., ""dialup
dialup--192192-168168-0-1.example.com
1.example.com").
"). If there's no
DNS for the machine, this is blank and REMOTE_ADDR is
the only information given.
REQUEST_METHOD
– The method the client used to fetch the document ((e.g.,
g,
"GET").
QUERY_STRING
REMOTE ADDR
REMOTE_ADDR
– A string containing the IP address of the machine that
requested this page (e.g., "192.168.0.250").
PHP_SELF
– holds the name of the current script, relative to the
document root.
9
Temperature Conversion
11
12
3
Sticky form - Example
Temperature Conversion
Content
1. Environment variables
2. Setting Response Header
3. Encoding and escaping
4. Cross site scripting
13
2. Setting Response Header
14
2. Setting Response Header (2)
HTTP Request
User
Agent
Web
Server
HTTP Response
All calls to header( ) (or setcookie( ), if you're
setting cookies) must happen before any of the
body is generated
Æ at the very top of your file, even before the
tag.
Date: today
From: fred
To: barney
Subject: hands off!
My lunchbox is mine and mine alone. Get your own,
you filthy scrounger!
Send back something
that's
that s not HTML
– Set the expiration time for a
page
– Redirect the client's browser
– Generate a specific HTTP error
Æ Using header() function
15
16
4
2.1. Different Content Types
2.2. Redirections
The Content
Content--Type header identifies the
type of document being returned.
returned
– "text/html " indicating an HTML document
– "text/plain" forces the browser to treat the
page as plain text. This type is like an
automatic "view source," and it is useful when
debugging.
– "image/jpeg", "image/png": Image content
–…
Send the browser to a new URL, known as
a redirection Æ set the Location header
17
18
2.3. Expiration
2.3. Expiration (2)
Proxy and browser caches can hold the
document until a specific date and time
(expire time/date)
Repeated reloads of a cached document
do not contact the server
To set the expiration time of a document
To expire a document three hours from the time
the page was generated
$now = time( );
$then = gmstrftime("%a, %d %b %Y %H:%M:%S GMT",
$now + 60*60*3);
header("Expires: $then");
– header('Expires:
h d ('E i
F
Fri,
i 18 J
Jan 2006
05:30:00 GMT');
To indicate that a document "never" expires, use
the time a y
year from now
$now = time( );
$then = gmstrftime("%a, %d %b %Y %H:%M:%S GMT",
$now + 365*86440);
header("Expires: $then");
19
20
5
2.3. Expiration (3)
Content
To mark a document as already expired, use the
current time or a time in the past:
$then = gmstrftime("%a, %d %b %Y %H:%M:%S GMT");
header("Expires: $then");
Prevent a browser or proxy cache from storing your
document:
1. Environment variables
2. Setting Response Header
3. Encoding and escaping
4. Cross site scripting
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Lastheader("Last
-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cacheheader("Cache
-Control: no
no-store, no
no-cache, must
must-revalidate");
header("Cacheheader("Cache
-Control: post
post-check=0, pre
pre-check=0", false);
header("Pragma: nono-cache");
21
22
3. Encoding and escaping
3.1. HTML Encoding
HTML, web page addresses, and database
commands are all strings, but they each require
different characters to be escaped in different
ways.
– a space in a web address must be written as %20,
– a literal less
less--than sign (<) in an HTML document must
be written as <
Special characters in HTML are
represented by entities such as &
and <.
There are two PHP functions that turn
special characters in a string into their
entities
PHP has a number of builtbuilt-in functions to convert
to and from these encodings
23
– htmlentities( )
– htmlspecialchars()
24
6
3.1.1. Entity
Entity--quoting all special characters
3.1.1. Entity
Entity--quoting all special characters (2)
htmlentities( ):
– Changes all characters with HTML entity
equivalents into those equivalents (with the
exception of the space character).
– < (<), > (>), & (&), and accented
characters.
– E.g.
htmlentities( ) function actually takes up to three
arguments:
$output = htmlentities(input
htmlentities(input,
, quote_style
quote_style,
,
charset);
charset
);
– charset: if given, identifies the character set (default is
"ISO--8859"ISO
8859-1")
– quote_style: controls whether single and double quotes
are turned into their entity forms.
$string = htmlentities("Einstürzende Neubauten");
echo $string;
Æ The entityentity-escaped version (ü seen by viewing the
source) correctly displays as ü in the rendered web page
ENT_COMPAT (the default) converts only double quotes,
ENT_QUOTES converts both types of quotes,
ENT_NOQUOTES converts neither
25
26
E.g. Cleaning a string function
Example
$input = <<< End
"Stop pulling my hair!" Jane's eyes flashed.
End;
$double = htmlentities($input);
//"Stop pulling my hair!" Jane's eyes flashed.<p>
$both = htmlentities($input, ENT_QUOTES);
//"Stop pulling my hair!" Jane's eyes flashed.<p>
$neither = htmlentities($input, ENT_NOQUOTES);
// "Stop pulling my hair!" Jane's eyes flashed.<p>
27
function clean_for_mysql($string,$max_length) {
$in_string
g = ltrim($string);
g
$in_string = rtrim($in_string);
if (round($max_length) < 1) {
$max_length = 131072; // 128K
}
if (strlen($in_string) > $max_length) {
$new_string = substr($in_string,0,$max_length);
}
$new_string = mysql_real_escape_string($new_string);
return $new_string;
}
28
7
3.1.3. Removing HTML tags
3.1.2. EntityEntity-quoting only HTML syntax characters
htmlspecialchars( ) function
– converts the smallest set of entities possible to generate
valid HTML.
– htmlspecialchars(input
htmlspecialchars(input,, [quote_style
[quote_style,, [charset]]
[charset]]);
);
– The following entities are converted:
Ampersands (&) are converted to &.
Double quotes (") are converted to ".
Single quotes (') are converted to ' (if ENT_QUOTES is on,
as described for htmlentities( )).
Less--than signs (<) are converted to <.
Less
Greater--than signs (>) are converted to >.
Greater
The strip_tags( ) function removes HTML
tags from a string:
– $input = '
Howdy, "Cowboy"
';
– $output = strip_tags($input);
– // $output is 'Howdy, "Cowboy"'
The function may take a second argument that
specifies a string of tags to leave in the string
$input = 'The bold tags will stay';
$output = strip_tags($input, '');
// $output is 'The bold tags will stay'
E.g.
– "angle < 30" or "sturm & drang"
29
30
3.2. URL encoding
3.2.1. RFC 1738 encoding and decoding
Convert to and from URL encoding, which
allows you to build and decode URLs.
URLs
Two types of URL encoding
– Specified by RFC 1738: treats a space as just
another illegal character in a URL and encodes
it as %20.
– Implementing
p
g the application/xapplication/x
pp
/ -wwwwww-formformurlencoded system: encodes a space as a +
and is used in building query strings.
rawurlencode( ): encode a string
according to the URL conventions
$name = "Programming PHP";
$output = rawurlencode($name);
echo "http://localhost/$output";
Æ Result: http://localhost/Programming%20PHP
rawurldecode(): decodes URL
URL--encoded
strings
$encoded = 'Programming%20PHP';
echo rawurldecode($encoded);
Æ Result: Programming PHP
31
32
8
Content
3.2.2. QueryQuery-string encoding and decoding
urlencode( ) and urldecode( ):
): encode and
decode spaces as plus signs (+) instead of as the
sequence %20.
Æ useful for generating query strings:
E.g.
$base_url = 'http://www.google.com/q=';
$query = 'PHP sessions -cookies';
$url = $base
$base_url
url . urlencode($query);
echo $url;
1. Environment variables
2. Setting Response Header
3. Encoding and escaping
4. Cross site scripting
ÆResult:
http://www.google.com/q=PHP+sessions+--cookies
http://www.google.com/q=PHP+sessions+
33
34
Three top web site vulnerabilites
Three top web site vulnerabilites
XSS – CrossCross-site scripting
– Bad web site sends innocent victim a script that steals
information from an honest web site
CSRF – CrossCross-site request forgery
– Bad web site sends innocent
contextvictim a script that steals
information from an honest web site
SQL Injection
– Browser sends malicious input
p to server
– Bad input checking leads to malicious SQL query
CSRF – CrossCross-site request forgery
Leverages
user’s session
at sever
– Bad web site sends
request
to good
web site, using
credentials of an innocent victim who “visits” site
– Bad web site sends browser request to good web site,
using credentials of an innocent victim
XSS – CrossCross-site
Injectsscripting
malicious script into trusted
SQL Injection
– Browser sends malicious input
p to server
U SQL
Uses
– Bad input checking leads to malicious SQL query
9
4. Cross site scripting
4. Cross site scripting (2)
Cross--site scripting (XSS)
Cross
– most common web application security vulnerability
– with the rising popularity of Ajax technologies, XSS
attacks are likely to become more advanced and to
occur more frequently
– malicious user embeds HTML or other clientclient-side script
into your Web site
Example
–
– If value of username parameter is:
What will happen?
2
types
– Reflected XSS
– Stored XSS
37
38
4.1. Reflected XSS
Javascript URL
jjavascript:
p alert(document.cookie)
(
)
Most common type of XSS and the easiest
The attacker uses social engineering techniques
to get a user to click on a link to your site. The
link has malicious code embedded in it.
Can be used to deliver a virus or malformed
cookie or grab data from the user’s system
E.g. The malicious code would be tacked onto the
end of a search link of Google’s search.
search
Solution: Validate the input before displaying any
user--generated data
user
Displays all cookies for current document
40
10
This site is protected by reCAPTCHA and the Google
Privacy Policy
and
Terms of Service
apply.