application security• cert/cc instructor of advanced incident handling for technical staff –

Post on 12-Aug-2020

4 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Application Security

•• sylphid.su@sti.com.twsylphid.su@sti.com.tw–

• Defcon 9 ( )• - Web

–• CISSP (Certified Information Systems Security

Professional) • CERT/CC Instructor of Advanced Incident Handling for

Technical Staff–

••• /

Agenda

• Apache Security• PHP Security• MySQL Security

Apache Security

Apache exploits

Installation and configuration

• Use Apache 2• Keep up-to-date• Use only the modules you need• Configure limits• Use SSL

Keep up-to-date

Keep up-to-date : Sony

• Linux nobody apache

apacheuser apachegroup apache

• Linux apache

– Ex.mod_imap, mod_include, mod_info, mod_userdir, mod_status, mod_cgi, mod_autoindex

root apache

• cd /usr/local/apache• chown 0 . bin conf logs• chgrp 0 . bin conf logs• chmod 755 . bin conf logs

• chown 0 /usr/local/apache/bin/httpd• chgrp 0 /usr/local/apache/bin/httpd• chmod 511 /usr/local/apache/bin/httpd

httpd.conf

• Most administrators (>80%) use the default configuration provided by the Apache

• This configuration file is fine but may be optimized security-wise by– Define an explicit IP address and port Apache should listen

on– Define a user and group Apache should run as– Remove any default content (e.g. manual, CGI scripts),

unused modules as well as possibly vendor-provided extras (e.g. SDB)

– Restrict access to local file system– Reduce amount of information leakage

Default httpd.conf (cont.)

• Disable directory indexing and symbolic links<Directory “/usr/local/apache2/htdocs">Options Indexes FollowSymLinksOrder allow,denyAllow from all</Directory>

<Directory “/usr/local/apache2/htdocs">Options NoneOrder allow,denyAllow from all</Directory>

Changing Web Server Identity

• ServerTokens: Configures the Server HTTP response header– ServerTokens Prod

• ServerSignature: Defines the content of the footer available on server-generated documents– ServerSignature Off

• Mod_security– SecServerSignature “Microsoft-IIS/5.0”

ServerTokensDescription: Configures the Server HTTP response headerSyntax: ServerTokens Major|Minor|Min[imal]|Prod[uctOnly]|OS|FullDefault: ServerTokens Full

• ServerTokens Prod[uctOnly]– Server sends (e.g.): Server: Apache

• ServerTokens Major– Server sends (e.g.): Server: Apache/2

• ServerTokens Minor– Server sends (e.g.): Server: Apache/2.0

• ServerTokens Min[imal]– Server sends (e.g.): Server: Apache/2.0.41

• ServerTokens OS– Server sends (e.g.): Server: Apache/2.0.41 (Unix)

• ServerTokens Full (or not specified)– Server sends (e.g.): Server: Apache/2.0.41 (Unix) PHP/4.2.2 MyMod/1.2

ServerTokensDescription: Configures the Server HTTP response headerSyntax: ServerTokens Major|Minor|Min[imal]|Prod[uctOnly]|OS|FullDefault: ServerTokens Full

• ServerTokens Prod[uctOnly]– Server sends (e.g.): Server: Apache

• ServerTokens Major– Server sends (e.g.): Server: Apache/2

• ServerTokens Minor– Server sends (e.g.): Server: Apache/2.0

• ServerTokens Min[imal]– Server sends (e.g.): Server: Apache/2.0.41

• ServerTokens OS– Server sends (e.g.): Server: Apache/2.0.41 (Unix)

• ServerTokens Full (or not specified)– Server sends (e.g.): Server: Apache/2.0.41 (Unix) PHP/4.2.2 MyMod/1.2

Server banner in HTTP response

ServerSignature

IP

• Order Deny,Allow• Deny from all• Allow from 192.168.1.0/24

Putting Apache in Jail

• Jails are an excellent tool to isolate Apache from the rest of the web server.

• Mod_security provides built-in chroot support:– SecChrootDir /usr/local/apache2

• Things to consider:– Do not leave any setuid binaries inside.– Do not have processes of the Apache user running

outside.– Do not allow the Apache user to write anywhere.

• How to 'chroot' an Apache tree with Linux and Solarishttp://penguin.triumf.ca/chroot.html

Logging Basics

• # Access log– LogFormat "%h %l %u %t \"%r\" %>s %b

\"%{Referer}i\" \"%{User-Agent}i\"" combined CustomLog logs/access_log combined

• # Error Log– LogLevel info– ErrorLog logs/error_log

• Use mod_security:– Log POST data– Performance measurement

Apache Health Monitoring

• Performance• Availability• mod_status• mod_watch• apache-monitor

An hour of activity of the Apache running on

www.apache.org. Produced with apache-monitor.

Timeout DoS

Description: Amount of time the server will wait for certain events before failing a request

Syntax: TimeOut secondsDefault: TimeOut 300Context: server config, virtual hostStatus: CoreModule: core• Timeout 45

Indexing

• Disable indexing to prevent content from being accidentally exposed to the public and eventually found by Google (e.g. “Indexof /backup“): – Options None or Options –Indexes

• If necessary, re-enable it only for certain directories you are aware of

SSI

• Best practice: Disable server-side includes completely– Options –IncludesNOEXEC– XBitHack off

• If necessary, use suexec, enable SSI and disable certain commands (e.g. #exec cmdand #exec cgi):– Note: Users will still be able to #include virtual CGI

scripts from ScriptAliased directories.• suexec:

http://httpd.apache.org/docs/2.2/suexec.html

httpd.conf

• includes– Directory Option

Option None Includes• CGI

– CGINone -ExecCGI

– Options –ExecCGI• Apache

– None -FollowSymLinks– Options -FollowSymLinks

Basic HTTP Authentication <Directory /var/www/html/test>

Options Indexes FollowSymLinksAuthType BasicAllowOverride AuthConfigAuthUserFile /var/www/userpasswordrequire valid-userOrder allow,denyallow from 192.168.1.0/24

/Directory>

• htpasswd –c /var/www/userpassword zeng• htpasswd /var/www/userpassword wang

Mod_Security

• http://www.modsecurity.org/• SecRuleSecRule VARIABLES OPERATOR VARIABLES OPERATOR

[ACTIONS] [ACTIONS] VARIABLESOPERATORACTIONS (optional)

• Mod Security http transactionPhase 1:Request Headers Phase

2:Request Body Phase 3: Response Headers Phase 4: Response Body Phase 5:logging

Mod_Security (cont. 1)

•<Location /apps/script.php>

SecRule &ARGS "!@eq 1"SecRule ARGS_NAMES "!^statid$"SecRule ARGS:statID "!^\d{1,3}$“

</Location>

• IP SecRule REMOTE_ADDR "@streq 192.168.254.1" \

allow,phase:1,nologSecRule REMOTE_ADDR "@beginsWith 192.168.254." \

allow,phase:1,nologSecRule REMOTE_ADDR "@rx ^192\.168\.254\.(1|2|5)$" \

allow,phase:1,nolog

Mod_Security (cont. 2)

• Command execution attacks– SecFilter /etc/password– SecFilter /bin/ls

• Directory traversal and XSS attacks– SecFilter "\.\./“– SecFilter "<(.|\n)+>"– SecFilter "<[[:space:]]*script“

• Forbid file upload– SecFilterSelective "HTTP_CONTENT_TYPE" multipart/form-

data

Mod_Evasive

• http://www.zdziarski.com/projects/mod_evasive/• Mod_Evasive example(in httpd.conf):

<IfModule mod_evasive.c>DOSHashTableSize 3097DOSPageCount 2DOSSiteCount 50DOSPageInterval 1DOSSiteInterval 1DOSBlockingPeriod 300DOSLogDir <PathToYourApacheLogDirHere>DOSEmailNotify myemal@email.com</IfModule>

PHP Security

Types of PHP Attacks

• PHP vulnerabilities• Command execution and/or writing to the

file system.• SQL injection• Session Hijacking• Cross Site Scripting (XSS) • Cross Site Request Forgeries (CSRF)• Session reading/predicting

PHP vulnerabilities

PHP 5.3.6 Buffer Overflow PoC

PHP 5.3.6 patch

• http://svn.php.net/viewvc/php/php-src/trunk/ext/sockets/sockets.c?r1=311369&r2=311368&pathrev=311369

php.net security notice

• [19-Mar-2011]• The wiki.php.net box was compromised and the

attackers were able to collect wiki account credentials. No other machines in the php.net infrastructure appear to have been affected. Our biggest concern is, of course, the integrity of our source code. We did an extensive code audit and looked at every commit since 5.3.5 to make sure that no stolen accounts were used to inject anything malicious. Nothing was found. The compromised machine has been wiped and we are forcing a password change for all svn accounts.

• We are still investigating the details of the attack which combined a vulnerability in the Wiki software with a Linux root exploit.

Securing PHP

• Default php.ini < V4.8 (5.3.6 now); WARNING ;; This is the default settings file for new PHP installations.; By default, PHP installs itself with a configuration suitable for; development purposes, and *NOT* for production purposes.

• Newer installs are better.• Many PHP applications are installed with a

default php.ini. Therefore vulnerabilities can be exploited.

Secure PHP Settings

• Turn of display errors in– display_errors = Off

• Log errors instead of showing them on screen– log_errors = On

• Users get information about your webserver through these errors – handle errors!

Fatal error: Call to undefined function view_details() in D:\wamp\www\security\fatal.php on line 2

• error_reporting = E_ALL (better error reporting)

More Settings

• session.save_path=/opt/php/session (Should be specified by the user. Where /opt has no apache quota)

• session.gc_maxlifetime=600 (ten minutes of inactivity)• Turn off magic_quotes_gpc in php.ini

– magic_quotes_gpc = off

• Why?– Problematic adds extra slashes in most cases– Requires more processing power and memory if turned on

• mysql_real_escape_string is better

More Settings

• register_globals = Off – Never turn on– Too easy to write insecure code– Auto initializes variables from

Get/Post/Cookie data

URL= index.php?administrator=xyz<?php

if (isset($administrator)){

$authorized = true;}?>

More Settings

safe_mode = On (enable if possible)safe_mode_gid = On (enable if possible)

• Especially useful in Highly Critical attacks.• Can not see files not owned by script owner.• Can not execute files not owned by script

owner.• Functions restricted/disabled by safe mode

(http://tw2.php.net/manual/zh/features.safe-mode.functions.php)

Developing Best Practices

• Develop with security and production in mind.• Form strict policies concerning how data is sanitized and at what

stage.• $_GET, $_COOKIE, $_POST should always be sanitized according

to where it’s going not where it came from.

Mysql = mysql_real_escape_string() Postgres = pg_escape_string ()The P.E.A.R. DB class handles database data with “?”

replacements.To browser = htmlentities () or strip_tags() To Shell = escapeshellcmd()

To Remove Javascript and reduce XSS attacks

• Use preg_replace() on …

• javascript: onclick ondblclick onmousedown onmouseup onmouseover onmousemove onmouseout onkeypress onkeydown onkeyup

Developing Best Practices cont.

• Form strict policies concerning sessions. (storage, timeouts, session id length, etc.)

• If on a multiuser machine make a custom session.save_path or save session data to a database.

• Use session_regenerate_id() to prevent fixation. Especially after privilege escalation.

File Extension for your code

• Don't use .inc to save php code• Must end in .php• Most default installations are geared interpret

only .php files • .inc files may show up your php code as text

in the browser

Developing Best Practices cont. Securing Includes

• Place them outside of document root.• ini_set("include_path",".:/home/user/libs");• But, if you have to place them in root…

End them in .php, so source is not revealed. Ex. database.inc.php

<Files ~ "\.inc$">Order allow,denyDeny from all

</Files>

Where to put db_connect.inc.php

• Not in document root.• If possible, make it non-world readable.

Apache group readable.

PHP SecurityWeb Applications

Cross-Site Scripting

• A technique that allows hackers to:– Execute malicious script in a client’s Web browser– Insert <script>, <object>, <applet>, <form>, and

<embed> tags– Steal Web session information and authentication

cookies– Access the client computer

Any Web page that renders HTMLcontaining user input is vulnerable

Cross-Site Scripting Attack

Cross Site Scripting Cross Site Scripting

Fixing XSS• White list

• Htmlentities() – Converts all possible characters

to html entities &lt; &gt; ....

• Htmlspecialchars()– Converts only <,>,',”,$ to html entities

• strip_tags ( string $str [, string $allowable_tags ] ) – Removes all tags or retains only selective tags– Partial Removal of tags still cause problems

How XSRF Works - 1

/viewbalanceCookie: sessionid=40a4c04de

“Your balance is $25,000”“Your balance is $25,000”

Alice bank.com/login.html

/authuname=victim&pass=fmd9032Cookie: sessionid=40a4c04de

evil.org

How XSRF Works - 2

Alice bank.com/login.html

/authuname=victim&pass=fmd9032Cookie: sessionid=40a4c04de

/evil.html<IMG SRC=http://bank.com/paybill?addr=123 evil st & amt=$10000>

/paybill?addr=123 evil st, amt=$10000Cookie: sessionid=40a4c04de

“OK. Payment Sent!”“OK. Payment Sent!”

XSRF – Protection - 1

• Ensure that there are no XSS vulnerabilities in your application

• Insert custom random tokens into every form and URL that will not be automatically submitted by the browser. For example:<form action="/transfer.do" method="post"><input type="hidden" name="8438927730" value="43847384383">…</form>

XSRF – Protection - 2

• For sensitive data or value transactions, re-authenticate or use transaction signing to ensure that the request is genuine.

• Do not use GET requests (URLs) for sensitive data or to perform value transactions.

• POST alone is insufficient a protection. • Get data correctly

– GET : Request.QueryString[“name”]– POST : Request.Form[“name”] – General : Request ["name"]

File Uploads

• Be careful with what you let users upload• Disable directory browsing using htaccess• Use htaccess to deny access to php, pl or

other executable scripts in upload directories

SQL Injection

• The ability of a user to change the SQL generated in your application and exploit it.

• Prevention – White list– Type cast inputs– Use mysql_real_escape_string()– Using mysqli and prepared statements

exec and fopen

• Clean your inputs before using them in exec and fopen

• exec allows php to run system level commands!

• fopen/file_get_contents allow opening of files from external urls!

• PHP: Disable allow_url_fopen and allow_url_include in php.ini

Sessions – secure them

• Sessions can be spoofed or stolen• Use session_regenerate_id to generate a

new id • session_destroy does not change the

session id !• Prompt for user's password on any critical

changes

Secure Configuration of Common PHP Applications - phpMyAdmin

• Protect config.inc.php if db access is “config”• If possible use mod_cas• If using http authentication force ssl using

mod_rewriteRewriteRule ^/$ /index.php RewriteCond %{SERVER_PORT}!443$

RewriteRule ^(.*) https://host.com:443$1 [R=301,L]

Secure Configuration of Common PHP Applications - phpbb

• If configuring remotely via the web, use ssl.• Sanity.A worm attacked a flaw that allowed for system calls to be

sent using GET vars.

Evil PHP:<?php$term = urldecode($_GET['sterm']);?>

$_GET is decoded once by php then again by urldecode. The second time quotes or other harmful symbols can be decoded and applied to system(). Assuming no magic quotes would have prevented the problem using escapecmd().

Secure Configuration of Common PHP Applications - Gallery

• Verify that gallery has written to the .htaccess and config.php file after install.

Then: chmod 644 .htaccess chmod 644 config.php

chmod 400 setup

Secure Configuration of Common PHP Applications - phpnuke

• Move config.php outside of DocumentRoot• Edit mainfile.php to path of moved config.php.

Web Applications

• When installing free web applications always be aware of security advisories.

• Maintain a backup of your database.• Practice restoring the database.• Be familiar with how to update the application.• If possible always use mod_cas. Especially

with tools like phpMyAdmin.

PHPIDS (1)

• php-ids.org• Interface

PHPIDS (2)

• Rule

<filter><rule><![CDATA[(?:^>[\w\s]*<\/?\w{2,}>)]]></rule><description>finds unquoted attribute breaking in...</description><tags>

<tag>xss</tag><tag>csrf</tag>

</tags><impact>2</impact>

</filter>

PHPIDS – installation

• mkdir /var/www/web1/phpids(document root /var/www/web1/web)

• cd /tmp– wget http://php-ids.org/files/phpids-0.5.4.tar.gz– tar xvfz phpids-0.5.4.tar.gz– cd phpids-0.5.4– mv lib/ /var/www/web1/phpids/

• cd /var/www/web1/phpids/lib/IDS• chown -R www:www tmp/ • cd Config/• vi Config.ini

PHPIDS sample <?phpset_include_path(

get_include_path(). PATH_SEPARATOR. '/var/www/web1/phpids/lib');

require_once 'IDS/Init.php';$request = array(

'REQUEST' => $_REQUEST,'GET' => $_GET,'POST' => $_POST,'COOKIE' => $_COOKIE

);$init = IDS_Init::init('/var/www/web1/phpids/lib/IDS/Config/Config.ini');$ids = new IDS_Monitor($request, $init);$result = $ids->run();

if (!$result->isEmpty()) {// Take a look at the result objectecho $result;require_once 'IDS/Log/File.php';require_once 'IDS/Log/Composite.php';

$compositeLog = new IDS_Log_Composite();$compositeLog->addLogger(IDS_Log_File::getInstance($init));$compositeLog->execute($result);}

?>

PHPIDS screenshot

Suhosin• http://www.hardened-php.net/suhosin/index.html• PHP

PHP Suhosin

– cookies – preg_replace() /e – eval()– infinite

recursion– memory_limit– mail() newline – preg_replace() \0 – session – session – GLOBALS _GET _COOKIE

––

Suhosin - installation

• tar zxvf php-x.x.x.tar.gz• gunzip suhosin-patch-x.x.x-0.x.x.x.patch.gz• cd php-x.x.x• patch -p1 -i ../suhosin-patch-x.x.x-

0.x.x.x.patch• PHP phpinfo()

This server is protected with the Suhosin Patch x.x.x.x

MySQL Security

Secure your configuration

• Simple principles:– Don’t run mysqld as (Unix) root. Run it as a user

created specifically for this purpose, e.g. mysql. Don’t use this account for anything else. (Note that the MySQL root user has nothing to do with Unix users so this doesn’t affect MySQL internally at all.)

– Set permissions on the database directories so that only your mysqld user (e.g. mysql) can access them.

Secure your configuration (cont.)

– Disable symlinks to tables with --skip-symbolic-links.

– Disallow access to port 3306 (or whatever port you have MySQL running on) except from trusted hosts

Accounts and Privileges

• All MySQL accounts need a password, especially root. (Don’t forget anonymous users, either.)– mysql> set password for

root@localhost=password('mysqlpasswd'); • Grant users the minimum level of privilege

required to do their job. (Principle of Least Privilege)– mysql> create database db1;– mysql> grant

select,insert,update,delete,create,drop privileges on db1.* to test1@localhost identified by 'admindb';

Accounts and Privileges (cont.)

• Some privileges require special attention:– Only the root user should have access to the mysql database,

which contains privilege information– Keep FILE, PROCESS, and SUPER for administrative users.

FILE enables file creation, PROCESS allows you to see executing processes (including passwords in plaintext), and SUPER can be allowed to e.g. terminate client connections.

• Avoid wildcards in hostnames in the host table.• Use IPs instead of hostnames in the host table if you

don’t trust your DNS

Mysql

• Mysql /usr/local/mysql/usr/local/mysql/var

– # chown -R mysql.mysql /usr/local/mysql/var– # chmod -R go-rwx /usr/local/mysql/var

Security Issues with LOAD DATA LOCAL

• In a Web environment where the clients are connecting from a Web server, a user could use LOAD DATA LOCAL to read any files.

• You can disable all LOAD DATA LOCAL commands from the server side by starting mysqld with the --local-infile=0 option.

Using encryption

• Don’t store application passwords in plaintext in the database. (Use one way hashing)

• Require database connections to be via ssh or tunneled through it

• Avoid old MySQL passwords (pre 4.1). (Disable with --secure-auth, and avoid use of --old-passwords.)

Q&A

top related