Issues (1177)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

application/helpers/dx_captcha_helper.php (13 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
if (!defined('BASEPATH')) {
4
    exit('No direct script access allowed');
5
}
6
/**
7
 * CodeIgniter
8
 *
9
 * An open source application development framework for PHP 4.3.2 or newer
10
 *
11
 * @package		CodeIgniter
12
 * @author		ExpressionEngine Dev Team
13
 * @copyright	Copyright (c) 2006, EllisLab, Inc.
14
 * @license		http://codeigniter.com/user_guide/license.html
15
 * @link		http://codeigniter.com
16
 * @since		Version 1.0
17
 * @filesource
18
 */
19
// ------------------------------------------------------------------------
20
21
/*
22
  Instructions:
23
24
  Load the plugin using:
25
26
  $this->load->helper('captcha');
27
28
  Once loaded you can generate a captcha like this:
29
30
  $vals = array(
31
  'word'		 => 'Random word',
32
  'img_path'	 => './captcha/',
33
  'img_url'	 => 'http://www.your-site.com/captcha/',
34
  'font_path'	 => './system/texb.ttf',
35
  'img_width'	 => rand(500, 600),
36
  'img_height' => rand(80, 120),
37
  'expiration' => 7200
38
  );
39
40
  $cap = create_captcha($vals);
41
  echo $cap['image'];
42
43
44
  NOTES:
45
46
  The captcha function requires the GD image library.
47
48
  Only the img_path and img_url are required.
49
50
  If a "word" is not supplied, the function will generate a random
51
  ASCII string.  You might put together your own word library that
52
  you can draw randomly from.
53
54
  If you do not specify a path to a TRUE TYPE font, the native ugly GD
55
  font will be used.
56
57
  The "captcha" folder must be writable (666, or 777)
58
59
  The "expiration" (in seconds) signifies how long an image will
60
  remain in the captcha folder before it will be deleted.  The default
61
  is two hours.
62
63
  RETURNED DATA
64
65
  The create_captcha() function returns an associative array with this data:
66
67
  [array]
68
  (
69
  'image' => IMAGE TAG
70
  'time'	=> TIMESTAMP (in microtime)
71
  'word'	=> CAPTCHA WORD
72
  )
73
74
  The "image" is the actual image tag:
75
  <img src="http://your-site.com/captcha/12345.jpg" width="140" height="50" />
76
77
  The "time" is the micro timestamp used as the image name without the file
78
  extension.  It will be a number like this:  1139612155.3422
79
80
  The "word" is the word that appears in the captcha image, which if not
81
  supplied to the function, will be a random string.
82
83
84
  ADDING A DATABASE
85
86
  In order for the captcha function to prevent someone from posting, you will need
87
  to add the information returned from create_captcha() function to your database.
88
  Then, when the data from the form is submitted by the user you will need to verify
89
  that the data exists in the database and has not expired.
90
91
  Here is a table prototype:
92
93
  CREATE TABLE captcha (
94
  captcha_id bigint(13) unsigned NOT NULL auto_increment,
95
  captcha_time int(10) unsigned NOT NULL,
96
  ip_address varchar(16) default '0' NOT NULL,
97
  word varchar(20) NOT NULL,
98
  PRIMARY KEY (captcha_id),
99
  KEY (word)
100
  )
101
102
103
  Here is an example of usage with a DB.
104
105
  On the page where the captcha will be shown you'll have something like this:
106
107
  $this->load->helper('captcha');
108
  $vals = array(
109
  'img_path'	 => './captcha/',
110
  'img_url'	 => 'http://www.your-site.com/captcha/'
111
  );
112
113
  $cap = create_captcha($vals);
114
115
  $data = array(
116
  'captcha_id'	=> '',
117
  'captcha_time'	=> $cap['time'],
118
  'ip_address'	=> $this->input->ip_address(),
119
  'word'			=> $cap['word']
120
  );
121
122
  $query = $this->db->insert_string('captcha', $data);
123
  $this->db->query($query);
124
125
  echo 'Submit the word you see below:';
126
  echo $cap['image'];
127
  echo '<input type="text" name="captcha" value="" />';
128
129
130
  Then, on the page that accepts the submission you'll have something like this:
131
132
  // First, delete old captchas
133
  $expiration = time()-7200; // Two hour limit
134
  $DB->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
135
136
  // Then see if a captcha exists:
137
  $sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND date > ?";
138
  $binds = array($_POST['captcha'], $this->input->ip_address(), $expiration);
139
  $query = $this->db->query($sql, $binds);
140
  $row = $query->row();
141
142
  if ($row->count == 0)
143
  {
144
  echo "You must submit the word that appears in the image";
145
  }
146
147
 */
148
149
/**
150
  |==========================================================
151
  | Create Captcha
152
  |==========================================================
153
  |
154
 */
155
if (!function_exists('create_captcha')) {
156
157
    function create_captcha($data = '', $img_path = '', $img_url = '', $font_path = '') {
158
        /**
159
         * Function to create a random color
160
         * Note: We aren't using this outside this function so we will sit it inside
161
         * @auteur mastercode.nl
162
         * @param $type string Mode for the color
163
         * @return int
164
         * */
165
        if (!function_exists('color')) {
166
167
            function color($type) {
168
                switch ($type) {
169
                    case 'bg':
170
                        //$color = rand(224,255);
171
                        $color = 255;
172
                        break;
173
                    case 'text':
174
                        $color = rand(0, 127);
175
                        break;
176
                    case 'grid':
177
                        $color = rand(200, 224);
178
                        break;
179
                    default:
180
                        $color = rand(0, 255);
181
                        break;
182
                }
183
                return $color;
184
            }
185
186
        }
187
188
        $defaults = [
189
                     'word'       => '',
190
                     'img_path'   => '',
191
                     'img_url'    => '',
192
                     'img_width'  => '150',
193
                     'img_height' => '30',
194
                     'font_size'  => '',
195
                     'font_path'  => '',
196
                     'show_grid'  => true,
197
                     'skew'       => true,
198
                     'expiration' => 7200,
199
                     'alt'        => 'captcha',
200
                    ];
201
202
        foreach ($defaults as $key => $val) {
203
            if (!is_array($data)) {
204
                if (!isset($$key) OR $ $key == '') {
205
                    $$key = $val;
206
                }
207
            } else {
208
                $$key = (!isset($data[$key])) ? $val : $data[$key];
209
            }
210
        }
211
212
        if ($img_path == '' OR $img_url == '') {
213
214
            return FALSE;
215
        }
216
217
        if (!@is_dir($img_path)) {
218
            return FALSE;
219
        }
220
221
        if (!is_really_writable($img_path)) {
222
            return FALSE;
223
        }
224
225
        if (!extension_loaded('gd')) {
226
            return FALSE;
227
        }
228
229
        // -----------------------------------
230
        // Select random Font from folder
231
        // -----------------------------------
232
233
        if (is_dir($font_path)) {
234
            $handle = opendir($font_path);
235
236
            while (($file = @readdir($handle)) !== false) {
237
                if (!in_array($file, ['.', '..']) && substr($file, strlen($file) - 4, 4) == '.ttf') {
238
                    $fonts[] = $file;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$fonts was never initialized. Although not strictly required by PHP, it is generally a good practice to add $fonts = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
239
                }
240
            }
241
242
            $font_file = $font_path . DIRECTORY_SEPARATOR . $fonts[array_rand($fonts)];
243
        } else {
244
            $font_file = $font_path;
245
        }
246
247
        // -----------------------------------
248
        // Remove old images
249
        // -----------------------------------
250
251
        list($usec, $sec) = explode(' ', microtime());
252
        $now = ((float) $usec + (float) $sec);
253
254
        $current_dir = @opendir($img_path);
255
256
        while ($filename = @readdir($current_dir)) {
257
            if ($filename != '.' and $filename != '..' and $filename != 'index.html') {
258
                $name = str_replace('.png', '', $filename);
259
260
                if (($name + $expiration) < $now) {
0 ignored issues
show
The variable $expiration does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
261
                    @unlink($img_path . $filename);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
262
                }
263
            }
264
        }
265
266
        @closedir($current_dir);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
267
268
        // -----------------------------------
269
        // Do we have a "word" yet?
270
        // -----------------------------------
271
272
        if ($word == '') {
0 ignored issues
show
The variable $word seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
273
            // No Zero (for user clarity);
274
            $pool = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
275
276
            $str = '';
277 View Code Duplication
            for ($i = 0; $i < 6; $i++) {
278
                $str .= substr($pool, mt_rand(0, strlen($pool) - 1), 1);
279
            }
280
281
            $word = strtoupper($str);
282
        }
283
284
        // -----------------------------------
285
        // Length of Word
286
        // -----------------------------------
287
288
        $length = strlen($word);
289
290
        // -----------------------------------
291
        // Create image
292
        // -----------------------------------
293
294
        $im = imagecreatetruecolor($img_width, $img_height);
0 ignored issues
show
The variable $img_width does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
The variable $img_height does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
295
296
        // -----------------------------------
297
        //  Assign colors
298
        // -----------------------------------
299
300
        $bg_color = imagecolorallocatealpha($im, color('bg'), color('bg'), color('bg'), 0);
301
        $border_color = imagecolorallocate($im, 255, 255, 255);
302
        $text_color = imagecolorallocate($im, color('text'), color('text'), color('text'));
303
        $grid_color[] = imagecolorallocate($im, color('grid'), color('grid'), color('grid'));
0 ignored issues
show
Coding Style Comprehensibility introduced by
$grid_color was never initialized. Although not strictly required by PHP, it is generally a good practice to add $grid_color = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
304
        $grid_color[] = $grid_color[0] + 150;
305
        $grid_color[] = $grid_color[0] + 180;
306
        $grid_color[] = $grid_color[0] + 210;
307
        $shadow_color = imagecolorallocate($im, 255, 240, 240);
0 ignored issues
show
$shadow_color is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
308
309
        // -----------------------------------
310
        //  Create the rectangle
311
        // -----------------------------------
312
313
        imagefilledrectangle($im, 0, 0, $img_width, $img_height, $bg_color);
314
315
        if ($show_grid == TRUE) {
0 ignored issues
show
The variable $show_grid does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
316
            // X grid
317
            $grid = rand(20, 25);
318 View Code Duplication
            for ($x = 0; $x < $img_width; $x += mt_rand($grid - 2, $grid + 2)) {
319
                $current_colour = $grid_color[array_rand($grid_color)];
320
                imagedashedline($im, mt_rand($x - 3, $x + 3), mt_rand(0, 4), mt_rand($x - 3, $x + 3), mt_rand($img_height - 5, $img_height), $current_colour);
321
            }
322
323
            // Y grid
324 View Code Duplication
            for ($y = 0; $y < $img_height; $y += mt_rand($grid - 2, $grid + 2)) {
325
                $current_colour = $grid_color[array_rand($grid_color)];
326
                imageline($im, mt_rand(0, 4), mt_rand($y - 3, $y), mt_rand($img_width - 5, $img_width), mt_rand($y - 3, $y), $current_colour);
327
            }
328
        }
329
330
        // -----------------------------------
331
        //  Write the text
332
        // -----------------------------------
333
334
        $use_font = ($font_file != '' AND file_exists($font_file) AND function_exists('imagettftext')) ? TRUE : FALSE;
335
336
        if ($use_font == FALSE) {
337
            $font_size = 5;
338
            $x = rand(2, $img_width / ($length / 3));
339
            // y isnt used here
340
        } else {
341
            // Make font proportional to the image size
342
            $font_size = !empty($font_size) ? $font_size : mt_rand(18, 25);
0 ignored issues
show
The variable $font_size seems only to be defined at a later point. As such the call to empty() seems to always evaluate to true.

This check marks calls to isset(...) or empty(...) that are found before the variable itself is defined. These will always have the same result.

This is likely the result of code being shifted around. Consider removing these calls.

Loading history...
343
            $x = rand(4, $img_width - (($font_size + ($font_size >> 1)) * $length));
344
            // y isnt used here
345
        }
346
        $wordLen = strlen($word);
347
        for ($i = 0; $i < $wordLen; $i++) {
348
            if ($use_font == FALSE) {
349
                $y = rand(0, $img_height / 2);
350
                imagestring($im, $font_size, $x, $y, substr($word, $i, 1), $text_color);
351
                $x += ($font_size * 2);
352
            } else {
353
                $letter = substr($word, $i, 1);
354
                $less_rotate = [
355
                                'c',
356
                                'N',
357
                                'U',
358
                                'Z',
359
                                '7',
360
                                '6',
361
                                '9',
362
                               ]; //letters that we don't want rotated too much...
363
364
                $angle = $skew == TRUE ? (in_array($letter, $less_rotate)) ? rand(-5, 5) : rand(-15, 15) : 0;
0 ignored issues
show
The variable $skew does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
365
                $y = $img_height / 2 + ($font_size >> 1) + ($skew == TRUE ? rand(-9, 9) : 0);
366
                $x += ($font_size >> 2);
367
                imagettftext($im, $font_size, $angle, $x, $y, $text_color, $font_file, $letter);
368
                $x += $font_size + ($font_size >> 2);
369
            }
370
        }
371
372
        // -----------------------------------
373
        //  Create the border
374
        // -----------------------------------
375
376
        imagerectangle($im, 0, 0, $img_width - 1, $img_height - 1, $border_color);
377
378
        // -----------------------------------
379
        //  Generate the image
380
        // -----------------------------------
381
382
        $img_name = $now . '.png';
383
384
        imagepng($im, $img_path . $img_name);
385
386
        $img = "<img src=\"$img_url$img_name\" width=\"$img_width\" height=\"$img_height\" style=\"border:0;\" alt=\"$alt\" />";
0 ignored issues
show
The variable $alt does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
387
388
        imagedestroy($im);
389
390
        return [
391
                'word'  => $word,
392
                'time'  => $now,
393
                'image' => $img,
394
               ];
395
    }
396
397
}