You are on page 1of 1

PHP Web Security

Vulnerabilities & Concepts Security Related PHP Functions Hardening the PHP Configuration Server Protection with Suhosin
Vulnerability Types Validation and Sanitising Escaping and Encoding Configuration # Features
auto_globals_jit:
# safe_mode & open_basedir Suhosin is a protective system for PHP installations # Executor Options # Configuration of Transparent Encryption suhosin.[source].max_array_index_length:
allow_url_fopen: safe_mode: which protects servers from known and also un- suhosin.executor.max_depth: suhosin.session.encrypt: • Defines the maximum length of array indexes.
Cross Site Scripting (XSS) Functions Functions This chapter provides an overview of security re-
• Activates URL-aware fopen() wrappers, allowing • Controls if the variables REQUEST, SERVER and • Activates PHP‘s safe mode. This will be known weaknesses in PHP applications and the • Defines the maximum stack depth that is per- • Activates transparent encryption of session Supported variable sources are get/post/cookie
This vulnerability allows data to be injected into lated PHP configuration options (PHP version 5.3). ENV are only generated when they are used PHP core. It consists of two parts that can be used and request. Setting a value for the request
PHP-Core-Functions • htmlspecialchars() URLs to be handled like files. dropped with PHP 6. mitted during the execution of PHP scripts. If data.
webpages. This data is then interpreted as code Escapes the characters & < and > as HTML • Default: On (can only be changed via php.ini) for the first time (JIT = Just In Time) or are • Default: Off individually or together. The first part is the Suhosin the stack depth is exceeded, the script will be • Default: On source overrides individual settings of the other
The PHP core provides a few functions suitable # Information Disclosure generated at the start of the execution of the
and executed by the viewer‘s web browser, which entities to protect the application against XSS. • Recommendation: Deactivate, if possible. • Recommendation: As required. patch which adds resistance against buffer over- terminated. • Recommendation: Transparent encryption of three sources.
for sanitising: display_errors: script.
can effectively be seen as remote controlling a The correct character set and the mode flow and other memory corruption exploits to the • Default: 0 (off) session data should always be activated. • Default: Depends on the source
victim‘s browser. • is_numeric() ENT_QUOTES should be used. • Defines if error messages should be displayed allow_url_include: • Default: On safe_mode_gid: PHP core. The second part is the Suhosin extension • Recommendation: This setting should be set to • Recommendation: Default settings should be
Checks a variable for numeric content. in the web browser. • Allows URL wrappers to be used with include(), • Recommendation: Unless access to these vari- • Defines if safe_mode uses UID (false, 0) or which, being a loadable PHP module, implements a value that does not interfere with the appli- suhosin.session.cryptkey: checked. The chosen settings may be too low
• is_array() <?php • Default: 1 include_once(), require() and require_once(). ables is done through variable variables this GID (true, 1) for access checks. various security defences for PHP scripts. The level for popular PHP applications such as
Cross Site Request Forgery (CSRF) cation, but at the same time does not allow to • Defines an application specific key that is
Checks if a variable is an array. echo "Hello " . htmlspecialchars( • Recommendation: Off • Default: Off option can remain activated. • Default: Off of protection is set within the PHP configuration. crash the PHP interpreter, e.g. 500. merged into the encryption key for the trans- phpMyAdmin.
CSRF refers to a type of exploits where the victim‘s
• strlen() $_GET['name'], 'utf-8', • Recommendation: Should remain deactivated • Recommendation: As required. parent session encryption.
browser is being tricked into triggering an authen- display_startup_errors: register_globals:
Returns a string‘s length. ENT_QUOTES); for security reasons. suhosin.executor.include.max_traversal: • Default: <empty> suhosin.[source].max_name_length:
ticated action inside a vulnerable web application. • Defines if errors occurring during request ini- • Defines that EGPCS variables (ENV, GET, POST,
• strip_tags() ?> safe_mode_include_dir: • Defines how often “../” may occur in filenames • Recommendation: Each application should set • Defines the maximum length of variable
The target website can be affected by CSRF re- tialisation should be displayed or logged. COOKIE, SERVER) should additionally be regis-
Removes HTML and PHP tags. magic_quotes_gpc: • Defines a list of directories that are exempt for include-statements before it is considered its own secret key with ini_set(). names. Supported variable sources are get/
gardless of being susceptible to XSS. How danger- • Default: 0 tered as global variables.
Warning: As long as certain HTML tags remain, • htmlentities() • Activates magic_quotes for GET/POST/COOKIE from the safe_mode restrictions for the include to be an attack. A value of zero deactivates the post/cookie and request. Setting a value for the
ous CSRF can be really depends on the kind of • Recommendation: Off unless for debugging. • Default: Off # Logging Configuration
JavaScript can be injected along with tag Applies HTML entity encoding to all applicable (GPC). If activated, all ' (single quotes), " or require statement. This allows to include feature. suhosin.session.cryptua: request source overrides individual settings of
action triggered this way and its impact. • Recommendation: For safety reasons this option
attributes. characters to protect the application against (double quotes), \ (backslash) and NULLs are a central copy of libraries. Multiple paths are suhosin.log.syslog: • Default: 0 • Defines if the content of the User-Agent header the other three sources.
XSS. The correct character set and the mode log_errors: being escaped by \ transparently. This option should never be activated. separated by colons (or semicolons in Win- • Defines which classes of security alerts should • Default: Depends on the source
SQL Injection • Recommendation: Most PHP-applications do is included in the encryption key for the session
ENT_QUOTES should be used. • Defines if errors should be logged. will not be available in PHP 6. dows). be logged to syslog. The class S_MEMORY is • Recommendation: It is usually not necessary to
not require a value greater than 5. encryption.
SQL injection attacks lead to the manipulation • Default: 0 • Default: 1 file_uploads: • Default: <empty> always logged into syslog because damage change the default setting.
• Default: Off
of SQL queries. Vulnerable applications allow <?php • Recommendation: 1, in combination with • Recommendation: This option should be deac- • Controls if HTTP file uploads are permitted or • Recommendation: As required. to the heap could result in all other logging- suhosin.executor.include.whitelist: • Recommendation: This option is known to
dynamically built SQL queries to contain unfiltered echo "Hello " . htmlentities( error_log defining a path outside the web root. tivated. Instead, user input should be escaped not. mechanisms ceasing to function. For an over- suhosin.[source].max_totalname_length:
• Defines a list of URI schemes that are permitted cause problems with IE.
or improperly sanitised user input. If exploited $_GET['name'], 'utf-8', properly and handled in a secure way when • Default: On safe_mode_exec_dir: view of available settings, please refer to the • Defines the maximum length of the complete
CType Extension expose_php: to be used in include statements. If no whitelist
successfully an attacker can gain access to all ENT_QUOTES); building database queries. • Recommendation: If an application does not • Defines a directory that is exempt from list of logging constants. name of a variable including the indexes. Sup-
By default, PHP comes with activated CType exten- • Defines if PHP should add version information is defined, then a potentially defined blacklist suhosin.session.cryptdocroot:
data in the database as well as modify data, lim- ?> require HTTP file uploads, this setting should safe_mode restrictions. Programs within this • Default: S_ALL & ~S_SQL ported variable sources are get/post/cookie
sion. Each of the following functions checks if all to the response‘s HTTP header. is evaluated. This option does only work if URL • Defines that the current document root directory
ited only by the access level of the database user. magic_quotes_runtime: be deactivated. directory are allowed to be executed by • Recommendation: Logging into syslog should and request. Setting a value for the request
characters of a string fall under the described • Default: On inclusions are not completely disabled in the of the web server is merged into the encryption
• urlencode() • Activates backslash escaping for all user input. system() and similar functions. be used primarily. three3 sources.
group of characters: • Recommendation: Off, as it is advisable to di- filter.default: PHP configuration. key for the session encryption.
Insecure Session Handling Applies URL encoding as seen in the query part • Default: 0 • Default: <empty> • Default: Depends on the source
vulge as little information as possible to poten- • Selects the standard filter used for filtering • Default: <empty> • Default: On
This category covers problems enabling attackers • ctype_alnum() of a URL. • Recommendation: This option should remain • Recommendation: As required. List of Logging Constants • Recommendation: It is usually not necessary to
tial attackers. $_GET, $_POST, $_COOKIE and $_REQUEST • Recommendation: URL inclusions should be • Recommendation: Should only be used if the
to access or manipulate a session token in order alphanumeric characters - A-Z, a-z, 0-9 deactivated. Instead, user input should be change the default setting.
variables. deactivated unless absolutely necessary. visitor´s IP address is not expected to change
to control or take over a session. <?php escaped properly and handled in a secure way safe_mode_allowed_env_vars:
• ctype_alpha() • Default: "unsafe_raw" • S_MEMORY Value: 1 during the session. Users of large proxy farms
$url = "http://www.example.com/" . when building database queries. • Defines a list of permitted prefixes for en- suhosin.[source].max_value_length:
alphabetic characters - A-Z, a-z • Recommendation: Change only if the applica- Logs memory access violations. suhosin.executor.include.blacklist: very often change their IP address.
Session Fixation "index.php?param=" . vironment variables that can be used when • Defines the maximum length of variable val-
tion is specifically designed to handle filtered • Defines a list of URI schemes that must not be
• ctype_cntrl() urlencode($_GET['pa']); magic_quotes_sybase: safe_mode is activated. If this value is empty, ues. Supported variable sources are get/post/
Session Fixation allows an attacker to control • S_MISC Value: 2 used in include statements. Other URI schemes suhosin.session.cryptraddr:
control characters - e.g. tab, line feed ?> • Switches to escaping with a single quote values. all variables can be used. cookie and request. Setting a value for the
the session of a user. This is done by injecting a Logs all errors that do not fall remain permitted. In case a whitelist is defined, • Defines how many octets of REMOTE_ADDR
known token to be used as a valid session token. • ctype_digit() instead of a backslash for magic_quotes_gpc • Default: "PHP_" the blacklist will be ignored. This option works (0..4) are included in the encryption key for the source request overrides individual settings of
• addslashes() and magic_quotes_runtime. • Recommendation: As required. into another category. the other three sources.
numerical characters - 0-9 only if URL inclusions are not completely dis- session encryption.
Applies a simple backslash escaping. The input • Default: 0 • Recommendation: Default settings should be
Information Disclosure • S_VARS Value: 4 abled in the PHP configuration. • Default: 0
• ctype_graph() string is assumed to be single-byte encoded. • Recommendation: This option should remain safe_mode_protected_env_vars: checked, as they may be too low for popular
As the name suggests, security related information characters creating visible output addslashes() should not be used to protect # Resource Limits Logs all errors that were caused • Default: <empty> • Recommendation: Should only be used if visi-
deactivated. Instead, user input should be • Defines a list of environment variables, which PHP applications such as CMS systems.
is being divulged by the target system, which may e.g. no whitespace against SQL injections, since most database due to request variables. • Recommendation: URL inclusions should be tors of a site will not have changes of their IP
max_execution_time: escaped properly and handled in a secure way cannot be set by the user with the putenv()
simplify an attack. Such information can be found systems operate with multi-byte encoded strings, deactivated unless absolutely necessary. addresses. Users of large proxy farms very often
• ctype_lower() • Sets the maximum time in seconds before the when building database queries. function, even if they are permitted by the suhosin.[source].max_vars:
in various places, e.g. code comments, directory such as UTF-8. • S_FILES Value: 8 change their IP addresses during a session.
lowercase letters - a-z PHP script is being terminated. Time is mea- safe_mode_allowed_env_vars directive. • Defines the maximum number of variables that
listings, error messages or even in search results Logs all errors that were caused suhosin.executor.func.whitelist:
sured in CPU time, so delays e.g. for database enable_dl: • Default: "LD_LIBRARY_PATH" can be registered. Supported variable sources
of your favourite search engine. • ctype_print() due to uploaded files. • Defines a list of PHP functions that may be suhosin.session.checkraddr:
• addcslashes() queries are omitted. • Allows PHP extensions to be loaded dynami- • Recommendation: As required. are get/post/cookie and request. Setting a
printable characters used by PHP scripts. The use of any other func- • Defines how many octets of REMOTE_ADDR
Applies backslash escaping. This can be used • Default: 30 cally value for the source request overrides individu-
Header Injection • S_INCLUDE Value: 16 tion is prohibited and will lead to a termination (0..4) are checked after decryption. This option
• ctype_punct() to prepare strings for use in a JavaScript string • Recommendation: This option should be set to • Default: 1 open_basedir: al settings of the other three sources.
This vulnerability allows HTTP headers to be in- Logs attempted injection attacks of the script. If the whitelist is empty, a poten- allows, for example, to have strict controls on
punctuation characters - printable characters, context. However, protection against HTML tag a value high enough to recognise only unusual • Recommendation: Deactivate this option to • Defines in which directories files may be • Default: Depends on the source
jected into an HTTP response. against include statements. tially defined black list will be evaluated. administrative backends. The difference to the
but not digits, letters or whitespace, injection is not possible with this function. execution times. prevent arbitrary code to be loaded during opened by a script using fopen() and similar • Recommendation: Default settings should be
# Output • Default: <empty> previous configuration is that it is possible to
e.g. .,!?:;*&$ runtime. functions. The value is used as a prefix. /dir/lib checked, as they may be too low for some
File Inclusion • S_SQL Value: 32 • Recommendation: Should be used if a PHP use the same session for both strict and non-
• mysql_real_escape_string() max_input_time: default_mimetype: would permit access to /dir/lib & /dir/library. popular PHP applications.
• ctype_space() Logs attempted injection attacks script requires only very few functions. strict areas.
The inclusion of local or remote files into a web Escapes a string for use with mysql_query(). • Sets the maximum time in seconds a script disable_functions: • Defines the default mimetype setting. In order to permit only one path, it must end
whitespace characters - e.g. newline, tab against SQL queries. • Default: 0
application is a serious security vulnerability, The character set of the current MySQL con- is allowed process input, e.g. POST, GET, file • Disables specified functions. • Default: "text/html" with a slash. This option is not affected by the suhosin.[source].disallow_nul:
suhosin.executor.func.blacklist: • Recommendation: This should always be used
which may lead to arbitrary code execution on the • ctype_upper() nection is taken into account, so it is safe to uploads. • Default: “” • Recommendation: Default value should not be setting of safe_mode. • Defines if variable values may contain ASCII
• S_EXECUTOR Value: 64 • Defines a list of PHP functions that must not be for the protection of administrative areas.
server. uppercase characters - A-Z operate on multi-byte encoded strings. • Default: -1 (no restriction) • Recommendation: Potentially dangerous and changed. • Default: <empty> (opening of all files is per- NUL bytes or not.
Logs problems that are caused used by PHP scripts. Executing these functions
Applications implementing string escaping as • Recommendation: It may be useful to restrict unused functions should be deactivated, e.g. mitted) • Default: On
• ctype_xdigit() by the executor protection. will lead to a termination of the script. suhosin.cookie.encrypt:
Insecure Configuration protection against SQL injection attacks should the execution time, but it should be decided on system(). default_charset: • Recommendation: This should be restricted to • Recommendation: Should be activated because
hexadecimal digits - 0-9, a-f, A-F • Default: <empty> • Activates transparent encryption of cookie
Misconfiguration of server or application software use this function. a case by case basis for each application. • Defines the default character set. the document root directory. ASCII NUL bytes are hardly ever used for any-
• S_MAIL Value: 128 • Recommendation: Should at least contain all data.
may facilitate or simplify attacks. <?php See also: List of potentially dangerous PHP func- • Default: <empty> thing other than attacks.
max_input_nesting_level: Logs warnings from the mail() functions that are deactivated by • Default: On
if (!ctype_print($_GET['var'])) { <?php tions • Recommendation: The default character set
• Sets the maximum nesting level for input vari- function protection. disable_functions. • Recommendation: The transparent encryption
Weak randomness die("User input contains ". $sql = "SELECT * FROM user WHERE" . should be set according to the application. suhosin.upload.max_uploads:
ables ($_REQUEST, $_POST, $_GET, ...). This disable_classes: of cookie data should always be activated.
"non-printable characters"); " login='" . # Session suhosin.executor.eval.whitelist: • Defines how many files can be uploaded in
This problem refers to predictable random number prevents the interpreter from crashing while • Disables specified classes. • S_SESSION Value: 256
} mysql_real_escape_string( List of potentially dangerous PHP functions: session.save_path: one request at the same time.
generation; e.g. badly chosen random seeds or handling too deeply nested variables. • Default: “” Logs warnings of the transparent • Defines a list of PHP functions that may be suhosin.cookie.cryptkey:
?> $_GET['login'], $db) . • Defines an argument that is passed to the ses- • Default: 25
algorithms using insufficient entropy are known to • Default: 64 • Recommendation: Potentially dangerous and session encryption. used by runtime evaluated PHP code. All other • Defines an application specific key that is
"'"; • system - Program execution sion‘s storage handler. This is usually the path functions are prohibited and their use will lead merged into the encryption key for transparent • Recommendation: The default setting usually
generate weak random numbers. • Recommendation: The default value should be unused classes should be deactivated
?> where the session data is stored. to a termination of the script. If the white list cookie encryption. does not need to be changed.
sufficient for most use cases. • exec - Program execution • S_ALL Value: 511
• Default: <empty> is empty, a potentially defined blacklist will be • Default: <empty>
Filter Extension - ext/filter • preg_quote() See also: List of potentially dangerous PHP classes Combines all classes. suhosin.upload.verification_script:
• shell_exec - Program execution • Recommendation: Each application should evaluated. • Recommendation: Every application should set
Should be used to escape user input to be memory_limit:
Starting with PHP 5.2.0 the filter extension has store its session data in a separate location. • Default: <empty> its own secret key with ini_set(). • Specifies a shell script that is used to verify
• Sets the maximum amount of memory in bytes request_order: • proc_open - Program execution suhosin.log.syslog.facility:
provided a simple API for input validation and inserted into regular expressions. This way the • Recommendation: Should be used if evaluated uploaded files. The script is called with the
a PHP script is allowed to allocate. • Defines the order in which GET, POST and • Sets the syslog facility that should be used for
input filtering. regular expression is safeguarded from seman- • popen - Program execution session.cookie_httponly: PHP code requires only very few functions. suhosin.cookie.cryptua: temporary file name as parameter. This can be
• Default: 128M COOKIE is parsed into REQUEST from left to logging to syslog when warnings are issued.
tic manipulations. • Controls if cookies are tagged with httpOnly • Defines if the content of the User-Agent header used e.g. for virus scans. The upload is only
• filter_input() • Recommendation: Before changing this value right. Later values supersede existing ones. • passthru - Program execution Available facilities depend on the system used
which makes them accessible by HTTP only suhosin.executor.eval.blacklist: is included in the encryption key for the cookie permitted if the script echoes “1”, otherwise the
Retrieves the value of any GET, POST, COOKIE, the script‘s maximum memory requirement • Default: <null> and can be checked in the documentation of
<?php • stream_socket_server – Server socket creation and not by the JavaScript. httpOnly cookies are • Defines a list of PHP functions that must not be encryption. file will be deleted.
ENV or SERVER variable and applies the speci- should be tested empirically and increased by • Recommendation: It is recommended to use the system‘s syslog-daemon.
$repl = preg_replace('/^' . supported by all major browser vendors and used by runtime evaluated PHP code. Executing • Default: Off • Default: <empty>
fied filter. 20%. GP to register GET and POST with REQUEST. • Default: LOG_USER
preg_quote($_GET['part'], '/'). • dl – Load arbitrary PHP modules therefore can be instrumental in minimising the these functions will lead to a termination of the • Recommendation: This option is known to • Recommendation: This feature should be used
• Recommendation: Adjust as suitable. to check if uploaded files contain viruses or
'-[0-9]{1,4}/', '', $str); danger of session hijacking. script. cause problems with IE.
<?php post_max_size: variables_order: • phpinfo – Information about the server
?> • Default: Off malware.
Concepts $url = filter_input(INPUT_GET, • Sets the maximum size of POST data allowed. • Defines the order in which the variables ENV,
• Recommendation: Should be activated.
suhosin.log.syslog.priority: • Default: <empty>
• Default: 8M GET, POST, COOKIE and SERVER are parsed. • mail – Send email • Sets the priority level used when logging to • Recommendation: Should be used to disallow suhosin.cookie.cryptdocroot:
Secure Input Handling 'url', FILTER_URL); suhosin.session.max_id_length:
• escapeshellarg() • Recommendation: This value should match the The parsing is carried out from left to right and dangerous functions that are not absolutely • Defines that the current document root directory
?> • posix_* - Posix functions syslog. Supported priority levels depend on the • Specifies the maximum length of session iden-
Input filters and validators can be used to scan Escapes a single argument of a shell command. new values overwrite old ones. If no value is session.cookie_secure: necessary. of the web server is merged into the encryption
size actually required. File uploads have to be system used and can be checked in the docu-
user input for specific patterns known to trigger In order to prevent shell code injection, single • apache_child_terminate – Terminate apache1 • Controls if cookies are tagged as secure and key for cookie encryption. tifiers. Longer session identifiers are ignored
• filter_var() covered by this setting as well. set, no superglobals will be generated. If e.g. mentation of the system‘s syslog daemon.
unwanted side effects in web applications. User quotes in user input is being escaped and the should therefore be sent over SSL encrypted suhosin.executor.disable_eval: • Default: On and replaced with new ones.
Filters a variable with the specified filter. "SP" is used, $_SERVER and $_POST will be process • Default: LOG_ALERT
input can contain fragments of JavaScript, SQL, whole string enclosed in single quotes. connections only. • Controls if the eval() statement is enabled or • Recommendation: Should remain activated. • Default: 128
upload_max_filesize: generated. • Recommendation: If required.
PHP or other code which - if unfiltered - could <?php • apache_setenv – Set apache environment vari- • Default: Off not. If disabled it is no longer possible to dy- Problems will arise if the session is started from • Recommendation: This setting should not be
• Sets the maximum file upload size allowed. • Default: EGPCS
then lead to code execution within the context of $url = filter_var($var, FILTER_URL); <?php able • Recommendation: Must be activated for SSL namically evaluate PHP code. different root directories. changed.
• Default: 2M • Recommendation: Changing this setting is usu- suhosin.log.sapi:
the web application. ?> system('resize /tmp/image.jpg' . • Recommendation: This value should match the ally not necessary; however, the ENV variables websites. • Default: Off
• virtual - Bypass safe mode • Defines which classes of security alerts are
escapeshellarg($_GET['w']).' '. file size actually required. are rarely used. logged into the SAPI errorlog. Please refer to • Recommendation: Activating this switch will suhosin.cookie.cryptraddr:
Sanitising escapeshellarg($_GET['h'])); session.cookie_lifetime: the list of logger constants for an overview of break a lot of scripts because many rely on the • Defines how many octets of REMOTE_ADDR
Sanitising functions can be used to “repair” user ?> Liste von potentiell gefährlichen PHP- • Defines the maximum lifetime of a cookie in available settings. availability of eval(). (0..4) are included in the encryption key for the
input, according to the application‘s restrictions Klassen: seconds. • Default: S_ALL & ~S_SQL cookie encryption.
(e.g. specific datatypes, maximum length) instead • escapeshellcmd() • Default: 0 (until the browser is closed) • Recommendation: If required. suhosin.executor.disable_emodifier: • Default: 0
of rejecting potentially dangerous input entirely. List of Filters Escapes all meta characters of a shell command • SPLFileObject – Write access to files • Recommendation: Should be adjusted to the • When set the /e modifier cannot be used • Recommendation: Should only be used if the Security Audits
In general, the use of sanitising functions is not in a way that no additional shell commands desired session lifetime. suhosin.log.script: within preg_replace(). Its use is deprecated visitor´s IP address is not expected to change Security Audits for web applications assure the
encouraged, because certain kinds and combina- Validation Filters can be injected. If necessary, arguments should because dynamically evaluating PHP code is during the session. Users of large proxy farms server and client side production readiness of
• Defines which classes of security alerts should
tions of sanitising filters may have security impli- • FILTER_VALIDATE_INT be enclosed in quotes. be logged by a shell script. Errors of class error-prone which can result in arbitrary PHP very often change their IP address. applications. Result of such audits is a security
cations of their own. In addition, the automatic Checks whether the input is an integer numeric S_MEMORY cannot be logged by a shell script code execution. The same functionality as the report structured by OWASP guidelines that
correction of typos could render the input syntacti- value. <?php because the current process might not be in a /e modifier can be achieved by using suhosin.cookie.checkraddr: contain all risks found and recommendations
cally or semantically incorrect. system(escapeshellcmd( stable state after a memory access violation. preg_replace_callback(). • Defines how many octets of REMOTE_ADDR to mitigate them. If the software has been
• FILTER_VALIDATE_BOOLEAN
'resize /tmp/image.jpg "' . Please refer to the list of logging constants for • Default: Off (0..4) are verified after decryption. This option written in-house, an additional workshop with
Checks whether the input is a boolean value.

Secure programming
Escaping $_GET['w']) . '" "' . an overview of available settings. • Recommendation: In addition to activating this allows, for example, to have stricter controls on your developers should be conducted to build
There are several different kinds of escaping: • FILTER_VALIDATE_FLOAT $_GET['h']) . '"')); • Default: 0 switch, it is recommended to check used PHP administrative backends. The difference to the security knowhow and awareness.
• The backslash prefix “\” defines a meta char- Checks whether the input is a floating point ?> • Recommendation: If required. applications for the usage of the /e modifier previous configuration is that it is possible to
acter within strings. For Example: \t is a tab number. and rewrite them to use preg_replace_call- use the same cookies for the strict and the non- Simple Audits
space, \n is a newline character, ... This can back(). strict area. A black box audit examines the web application
• FILTER_VALIDATE_REGEXP Securing HTML Output HTTP Header Output Executing Shell Commands Securing SQL Queries suhosin.log.phpscript:
• Default: 0 from an attackers point of view. The test is accom-
be of particular interest for functions where the Checks the input against a regular expression. • Defines which classes of security alerts should
newline character has a special purpose, e.g. In order to prevent the execution of JavaScript HTTP headers can be set using the header() func- Shell commands can be executed by various SQL query strings should always be protected be logged by a PHP script. Errors of the class • Recommendation: This should always be used plished manually with additional tool support,
header(). Within regular expressions the backs- • FILTER_VALIDATE_URL code originating from user input, it is mandatory tion. User input should always be checked before functions in PHP, e.g. system(), passthru(), exec(), against SQL injections. There are two possible S_MEMORY cannot be logged by a PHP script for the protection of administrative areas. without any knowledge of the application‘s inter-
lash is used to escape special characters, such Checks whether the input is a URL. to perform a suitable string sanitisation on all being passed to header(), otherwise a number of shell_exec(), proc_open(), popen(). Commands strategies: On the one hand, each dynamic part because the current process might not be in a # Other Options nals. A black box audit can significantly increase
as \. or \*, which is relevant for all functions dynamic data before any HTML output. The use of security issues become relevant. built from user input must be properly escaped in of the query string can be escaped appropriately. stable state after a memory access violation. suhosin.simulation: suhosin.cookie.cryptlist: your application‘s security by decreasing the pro-
• FILTER_VALIDATE_EMAIL htmlentities() is considered sufficient within normal order to prevent shell command injections. • Specifies a list of cookies to be encrypted. No
handling regular expressions. Please refer to the list of logging constants for • Activates or deactivates the simulation mode bability of successful hacking attacks by detecting
Checks whether the input is a valid email ad- HTML context. Newline characters should never be used with PHP provides two functions for this purpose – On the other hand, the whole query string can be other cookies are encrypted.
• HTML encoding translates characters nor- an overview of available settings. of Suhosin. If activated violations will only be and removing the “low hanging fruits”.
dress. header() in order to prevent HTTP header injec- escapeshellarg() and escapeshellcmd(). set up as a prepared statement, where dynamic • Default: <empty>
mally interpreted by the web browser as HTML • Default: 0 logged and not blocked.
into their encoded equivalents - e.g. < is &lt; • FILTER_VALIDATE_IP However, if data can be injected into tags or tag tions. Injected headers can be used for XSS and parts are represented by placeholders to be re- • Recommendation: Should only be used in ex- • Default: Off • Recommendation: Should be used if the ma- Extended Audit
attributes, JavaScript can be executed by means HTTP response splitting attacks, too. In general, <?php placed right before the actual query. • Recommendation: During initial deployment jority of cookies are required to be readable on The extended audit adds source code inspection
or &#x003C; or &#60; and > is &gt; or Checks whether the input is a valid IPv4 or ceptional cases for classes of errors that could
of event handlers such as onClick or by modifying user input should be handled in a context-sensi- $param = 'helloworld;'. of Suhosin, this flag should be switched on to the client side (e.g. JavaScript). to the black box audit. The source code is tested
&#x003E; or &#62;. HTML encoding should IPv6. occur during script execution.
style attributes. For these cases it is recommended tive manner. '/usr/bin/id;'; While both methods have pros and cons, pre- ensure that the application continues to work manually supported by automated static code
be used for output handling, where user input
to apply a whitelist filter allowing only predefined system('echo ' . pared statements are most suitable for prevent- under the new configuration. suhosin.cookie.plainlist: analysis tools; input flow and critical function calls
should be reflected in HTML without injecting suhosin.log.script.name:
tag attributes or style sheets to be inserted. Dynamic content within parameters to Location escapeshellarg($param)); ing SQL injections. Dynamic content and the • Specifies a list of cookies that should not be are checked. A complete source code audit pro-
code. (See also: htmlentities()) • Sets the full path name of a logging shell
or Set-Cookie headers should be escaped by ?> prepared static part of a query are conceptually suhosin.multiheader: encrypted. All other cookies are encrypted. vides a good reliability and prevents even hard to
• URL encoding makes sure, that every character script. This script is called with two parameters;
not allowed within URLs, according to RFC Sanitising Filters URLs within tag attributes must be checked as urlencode(). separated and therefore less prone to program- the first represents the error class as a string of • Allows to disable the protection against HTTP • Default: <empty> find security issues.
1738, is properly encoded. E.g. space converts • FILTER_SANITIZE_STRING / well. Some URI schemes, such as data: vbscript: ming errors. characters and the second parameter contains Response splitting. • Recommendation: Should be used if the ma-
to + or %20 and < is %3C. This escaping is FILTER_SANITIZE_STRIPPED and javascript: can be used to execute code. <?php the alert message. • Default: Off jority of cookies are not required to be read- Consulting
relevant for functions handling URLs, such as Strips and HTML-encodes characters according Therefore only specific schemes should be allowed. if (strpbrk($_GET['x'], "\r\n")) In PHP, prepared statements are supported by sev- • Default: <empty> • Recommendation: This should only be allowed able on the client side (e.g. JavaScript). A network and application architecture audit
urlencode() and urldecode(). to flags and applies strip_tags(). Of course, it is always a good idea to encode the die('line break in x'); eral different database APIs. The following exam- • Recommendation: If required. if the application requires this hack and cannot helps assuring the intended level of security as
query part of a URL appropriately as well. header("Location: " . ple shows the execution of a prepared statement be changed. early as during the design phase of the software.
White-/Blacklisting • FILTER_SANITIZE_ENCODED "http://www.example.com/?p=". Secure File Handling using the common PDO API. Its syntax remains suhosin.log.phpscript.name: Security relevant parts and paths of the software
Applies URL encoding. Finally, data put directly into JavaScript code must urlencode($_GET['x'])); unchanged for different database management • Sets the full path name of a logging PHP script. suhosin.mail.protect: are revealed and solutions are provided. That
There are two different approaches to filtering in- • Detect and replace NULL bytes: # Filter Configuration
put data - whitelisting and blacklisting. Blacklisting be prevented from breaking out of its JavaScript header("Set-Cookie: mycookie=". systems (DBMS), even with DBMS not support- When this script is executed the two variables • Defines how strict the mail() protection should allows the development team to focus on their
• FILTER_SANITIZE_SPECIAL_CHARS suhosin.filter.action:
checks input data against a list of “bad patterns”. context. JavaScript strings are known to be par- urlencode($_GET['x']) . <?php ing prepared statements, in which case it can be SUHOSIN_ERRORCLASS and operate. A value of 0 deactivates the protection. core competences while maintaining a state of the
Encodes ' " < > & \0 and optionally all char- • Defines Suhosin‘s reaction to variable filter
This way, unwanted input can be discarded and ticularly prone to incorrect escaping. "; path=/;"); if (strpos($_GET["f"], "\0") === emulated by PDO. SUHOSIN_ERROR are created in the current A value of 1 prohibits line breaks in headers art security.
acters > chr(127) into numeric HTML entities. violations. Different configuration options can
all other content can be processed further. On the ?> true) { variable scope. The logging-script can use and double line breaks in extended headers.
• FILTER_SANITIZE_EMAIL be found in the Suhosin documentation.
other hand, whitelisting checks input data against $file = str_replace("\0", "", The complete SQL query looks like this: them to extract the error type and message. A value of 2 prohibits all addressing through If you are interested in an audit or consulting by
Removes all characters not commonly used in For other HTTP header parameters, unintended • Default: <empty>
a list of known “good patterns”. All unmatched $_GET["f"]); • Default: <empty> extended headers. SektionEins, please contact us at
an email address. context changes must be prevented as well; e.g. <?php • Recommendation: It is recommended that
input can be discarded and only input recognised } • Recommendation: If required. • Default: 0
a semicolon separates several parameters within $sth = $dbh->prepare( only the registration of violating variables is
as valid is accepted. • FILTER_SANITIZE_URL ?> • Recommendation: Should at least be set to 1 SektionEins GmbH
Content-Type. 'SELECT id, gid FROM _users ' . blocked. Anything else could lead to DoS vul-
Removes all characters not allowed in URLs. suhosin.log.use-x-forwarded-for: to activate the basic protection. Eupener Strasse 150
• Prevent remote file inclusion (path prefix) and 'WHERE login = ?' . nerabilities of the application.
In the real world whitelisting turned out to be far • Defines if Suhosin should extract the IP address 50933 Cologne
• FILTER_SANITIZE_NUMBER_INT <?php directory traversal (basename): 'AND passhash = ?');
more resistant to security vulnerabilities than
Removes all characters except digits and + -.
Regular Expressions if (strpbrk($_GET['type'], <?php $sth->execute(
of an attacker from the X-Forwarded-For HTTP suhosin.memory_limit:
suhosin.[source].max_array_depth:
Germany
blacklisting, since it is usually a lot easier to specify header when constructing error messages. • If safe_mode is not set any script can arbitrarily Tel: +49 221 29282933
Every user input placed inside regular expressions ";/\r\n")) $file = "./".basename($_GET["f"]). array('admin', md5('myPass'))); • Defines the maximum depth for arrays of this
the narrow set of valid patterns for the whitelist This is required if the server is behind a reverse change the memory_limit. Suhosin allows to
• FILTER_SANITIZE_NUMBER_FLOAT must be prepared using preg_quote(). Otherwise die('invalid characters'); ".php"; $res = $sth->fetchAll(); variable source. Supported variable sources
than to exclude every invalid input with a blacklist. proxy. configure a hard memory_limit which cannot http://www.sektioneins.de/
Removes all characters not allowed in floating an injection into the expression‘s logic can easily header("Content-Type: text/" . ?> ?> are get/post/cookie and request. Setting a
In particular, whitelisting should be used for input • Default: off be bypassed by the script.
point numbers. lead to incorrect application behaviour, buffer $_GET['type'] . value for the request source overrides individual
directly controlling the program flow, e.g. for • Include only whitelisted files: • Recommendation: If required. • Default: 0
overflows, denial of service or application crash- "; charset=utf-8;"); settings of the other three sources.
include statements or eval(). • FILTER_SANITIZE_MAGIC_QUOTES • Recommendation: If the desired memory_limit
es. ?> • Default: Depends on the source
Applies addslashes(). <?php is not supposed to be altered, it must be set
• Recommendation: It is usually not necessary to
if (in_array($_GET['action'], here. © 2009 SektionEins GmbH
Other Filters <?php Applications should not allow arbitrary HTTP change the default setting.
array('index', 'logout'))) {
• FILTER_UNSAFE_RAW $res = preg_match('/(foo|' . Location redirects, since these can be used for
include './'.$_GET['action'] . Concept: Stefan Esser, fukami, Ben Fuhrmannek
Is a dummy filter. preg_quote($_GET['i'], '/') . phishing attacks. In addition, open redirects can
'.php';
')/i', $input); have a negative impact on the cross domain
} else As of: October 2009
• FILTER_CALLBACK ?> policy infrastructure of Adobe‘s Flash Player.
die('action not permitted');
Calls a userspace callback function defining
?>
the filter.

www.sektioneins.de

You might also like