blob: 0c51e342b97a7b477652a89ccb4f01ca6256ae9a [file] [log] [blame]
Derek Jones8ede1a22011-10-05 13:34:52 -05001##############
2Security Class
3##############
4
5The Security Class contains methods that help you create a secure
6application, processing input data for security.
7
Andrey Andreevcc042092014-01-03 17:08:27 +02008.. contents::
9 :local:
10
11.. raw:: html
12
13 <div class="custom-index container"></div>
14
Derek Jones8ede1a22011-10-05 13:34:52 -050015XSS Filtering
16=============
17
18CodeIgniter comes with a Cross Site Scripting Hack prevention filter
19which can either run automatically to filter all POST and COOKIE data
20that is encountered, or you can run it on a per item basis. By default
21it does **not** run globally since it requires a bit of processing
22overhead, and since you may not need it in all cases.
23
24The XSS filter looks for commonly used techniques to trigger Javascript
25or other types of code that attempt to hijack cookies or do other
26malicious things. If anything disallowed is encountered it is rendered
27safe by converting the data to character entities.
28
29Note: This function should only be used to deal with data upon
30submission. It's not something that should be used for general runtime
31processing since it requires a fair amount of processing overhead.
32
Andrey Andreev5363f462014-01-03 12:31:53 +020033To filter data through the XSS filter use the ``xss_clean()`` method::
Derek Jones8ede1a22011-10-05 13:34:52 -050034
35 $data = $this->security->xss_clean($data);
36
37If you want the filter to run automatically every time it encounters
38POST or COOKIE data you can enable it by opening your
39application/config/config.php file and setting this::
40
41 $config['global_xss_filtering'] = TRUE;
42
Andrey Andreev5363f462014-01-03 12:31:53 +020043.. note:: If you use the form validation class, it gives you the option of
44 XSS filtering as well.
Derek Jones8ede1a22011-10-05 13:34:52 -050045
Andrey Andreev5363f462014-01-03 12:31:53 +020046An optional second parameter, *is_image*, allows this function to be used
Derek Jones8ede1a22011-10-05 13:34:52 -050047to test images for potential XSS attacks, useful for file upload
48security. When this second parameter is set to TRUE, instead of
49returning an altered string, the function returns TRUE if the image is
50safe, and FALSE if it contained potentially malicious information that a
51browser may attempt to execute.
52
53::
54
Derek Joneseb946d02011-10-05 15:47:43 -050055 if ($this->security->xss_clean($file, TRUE) === FALSE)
56 {
Andrey Andreev5363f462014-01-03 12:31:53 +020057 // file failed the XSS test
Derek Joneseb946d02011-10-05 15:47:43 -050058 }
Derek Jones8ede1a22011-10-05 13:34:52 -050059
Derek Jones8ede1a22011-10-05 13:34:52 -050060Cross-site request forgery (CSRF)
61=================================
62
Andrey Andreev5363f462014-01-03 12:31:53 +020063You can enable CSRF protection by altering your **application/config/config.php**
64file in the following way::
Derek Jones8ede1a22011-10-05 13:34:52 -050065
66 $config['csrf_protection'] = TRUE;
67
Andrey Andreevf795ab52012-10-24 21:28:25 +030068If you use the :doc:`form helper <../helpers/form_helper>`, then
Andrey Andreev5363f462014-01-03 12:31:53 +020069:func:`form_open()` will automatically insert a hidden csrf field in
Andrey Andreev25a246c2013-12-17 13:07:26 +020070your forms. If not, then you can use ``get_csrf_token_name()``
71and ``get_csrf_hash()``
Andrey Andreevf795ab52012-10-24 21:28:25 +030072::
73
74 $csrf = array(
Andrey Andreev25a246c2013-12-17 13:07:26 +020075 'name' => $this->security->get_csrf_token_name(),
76 'hash' => $this->security->get_csrf_hash()
Andrey Andreevf795ab52012-10-24 21:28:25 +030077 );
78
79 ...
80
81 <input type="hidden" name="<?=$csrf['name'];?>" value="<?=$csrf['hash'];?>" />
82
83Tokens may be either regenerated on every submission (default) or
84kept the same throughout the life of the CSRF cookie. The default
85regeneration of tokens provides stricter security, but may result
86in usability concerns as other tokens become invalid (back/forward
87navigation, multiple tabs/windows, asynchronous actions, etc). You
88may alter this behavior by editing the following config parameter
89
90::
RS7123ea93b2012-01-03 12:43:16 -020091
92 $config['csrf_regeneration'] = TRUE;
93
Derek Jones8ede1a22011-10-05 13:34:52 -050094Select URIs can be whitelisted from csrf protection (for example API
95endpoints expecting externally POSTed content). You can add these URIs
96by editing the 'csrf_exclude_uris' config parameter::
97
98 $config['csrf_exclude_uris'] = array('api/person/add');
99
Andrey Andreev6c520962014-08-18 12:24:42 +0300100Regular expressions are also supported (case-insensitive)::
Casey Hancock2f4c3bc2014-08-11 12:52:20 -0400101
Andrey Andreev6c520962014-08-18 12:24:42 +0300102 $config['csrf_exclude_uris'] = array(
103 'api/record/[0-9]+',
104 'api/title/[a-z]+'
105 );
Casey Hancock2f4c3bc2014-08-11 12:52:20 -0400106
Andrey Andreev5363f462014-01-03 12:31:53 +0200107***************
108Class Reference
109***************
Andrey Andreevf795ab52012-10-24 21:28:25 +0300110
Andrey Andreev5363f462014-01-03 12:31:53 +0200111.. class:: CI_Security
Andrey Andreevf795ab52012-10-24 21:28:25 +0300112
Andrey Andreev5363f462014-01-03 12:31:53 +0200113 .. method:: xss_clean($str[, $is_image = FALSE])
Andrey Andreevf795ab52012-10-24 21:28:25 +0300114
Andrey Andreev28c2c972014-02-08 04:27:48 +0200115 :param mixed $str: Input string or an array of strings
116 :returns: XSS-clean data
117 :rtype: mixed
Andrey Andreev5363f462014-01-03 12:31:53 +0200118
119 Tries to remove XSS exploits from the input data and returns the cleaned string.
120 If the optional second parameter is set to true, it will return boolean TRUE if the image is safe to use and FALSE if malicious data was detected in it.
121
122 .. method:: sanitize_filename($str[, $relative_path = FALSE])
123
Andrey Andreev28c2c972014-02-08 04:27:48 +0200124 :param string $str: File name/path
125 :param bool $relative_path: Whether to preserve any directories in the file path
126 :returns: Sanitized file name/path
127 :rtype: string
Andrey Andreev5363f462014-01-03 12:31:53 +0200128
129 Tries to sanitize filenames in order to prevent directory traversal attempts
130 and other security threats, which is particularly useful for files that were supplied via user input.
131 ::
132
133 $filename = $this->security->sanitize_filename($this->input->post('filename'));
134
135 If it is acceptable for the user input to include relative paths, e.g.
136 *file/in/some/approved/folder.txt*, you can set the second optional parameter, ``$relative_path`` to TRUE.
137 ::
138
139 $filename = $this->security->sanitize_filename($this->input->post('filename'), TRUE);
140
141 .. method:: get_csrf_token_name()
142
Andrey Andreev28c2c972014-02-08 04:27:48 +0200143 :returns: CSRF token name
144 :rtype: string
Andrey Andreev5363f462014-01-03 12:31:53 +0200145
146 Returns the CSRF token name (the ``$config['csrf_token_name']`` value).
147
148 .. method:: get_csrf_hash()
149
Andrey Andreev28c2c972014-02-08 04:27:48 +0200150 :returns: CSRF hash
151 :rtype: string
Andrey Andreev5363f462014-01-03 12:31:53 +0200152
153 Returns the CSRF hash value. Useful in combination with ``get_csrf_token_name()``
154 for manually building forms or sending valid AJAX POST requests.
155
156 .. method:: entity_decode($str[, $charset = NULL])
157
Andrey Andreev28c2c972014-02-08 04:27:48 +0200158 :param string $str: Input string
159 :param string $charset: Character set of the input string
160 :returns: Entity-decoded string
161 :rtype: string
Andrey Andreev5363f462014-01-03 12:31:53 +0200162
163 This method acts a lot like PHP's own native ``html_entity_decode()`` function in ENT_COMPAT mode, only
164 it tries to detect HTML entities that don't end in a semicolon because some browsers allow that.
165
Andrey Andreev487ccc92014-08-27 16:26:23 +0300166 If the ``$charset`` parameter is left empty, then your configured ``$config['charset']`` value will be used.
167
168 .. method:: get_random_bytes($length)
169
170 :param int $length: Output length
171 :returns: A binary stream of random bytes or FALSE on failure
172 :rtype: string
173
174 A convenience method for getting proper random bytes via ``mcrypt_create_iv()``,
175 ``/dev/urandom`` or ``openssl_random_pseudo_bytes()`` (in that order), if one
176 of them is available.
177
178 Used for generating CSRF and XSS tokens.
179
180 .. note:: The output is NOT guaranteed to be cryptographically secure,
181 just the best attempt at that.