Issues (34)

Security Analysis    no request data  

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.

src/activities/ValidateAssetActivity.php (7 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
#!/usr/bin/php
2
3
<?php
4
5
/*
6
 *   This class validate input assets and get mime type and metadata 
7
 *   Using the ValidateAsset activity you can confirm your asset can be transcoded
8
 *
9
 *   Copyright (C) 2016  BFan Sports - Sport Archive Inc.
10
 *
11
 *   This program is free software; you can redistribute it and/or modify
12
 *   it under the terms of the GNU General Public License as published by
13
 *   the Free Software Foundation; either version 2 of the License, or
14
 *   (at your option) any later version.
15
 *
16
 *   This program is distributed in the hope that it will be useful,
17
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 *   GNU General Public License for more details.
20
 *
21
 *   You should have received a copy of the GNU General Public License along
22
 *   with this program; if not, write to the Free Software Foundation, Inc.,
23
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24
 */
25
26
require_once __DIR__.'/BasicActivity.php';
27
28
use SA\CpeSdk;
29
30
class ValidateAssetActivity extends BasicActivity
31
{
32
    private $finfo;
0 ignored issues
show
The property $finfo is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
33
    private $s3;
34
    private $curl_data = '';
35
    
36
    public function __construct($client = null, $params, $debug, $cpeLogger)
37
    {
38
        # Check if preper env vars are setup
39
        if (!($region = getenv("AWS_DEFAULT_REGION")))
40
            throw new CpeSdk\CpeException("Set 'AWS_DEFAULT_REGION' environment variable!");
41
        
42
        parent::__construct($client, $params, $debug, $cpeLogger);
43
        
44
        $this->s3 = new \Aws\S3\S3Client([
45
            "version" => "latest",
46
            "region"  => $region
47
        ]);
48
    }
49
50
    // Used to limit the curl download in case of an HTTP encode
51
    private function writefn($ch, $chunk)
52
    {
53
        static $limit = 1024; // 500 bytes, it's only a test
54
        
55
        $len = strlen($this->curl_data) + strlen($chunk);
56
        if ($len >= $limit ) {
57
            $this->curl_data .= substr($chunk, 0, $limit-strlen($this->curl_data));
58
            return -1;
59
        }
60
        
61
        $this->curl_data .= $chunk;
62
        return strlen($chunk);
63
    }
64
    
65
    // Perform the activity
66
    public function process($task)
67
    {
68
        $this->cpeLogger->logOut(
69
            "INFO",
70
            basename(__FILE__),
71
            "Preparing Asset validation ...",
72
            $this->logKey
73
        );
74
75
        // Call parent process:
76
        parent::process($task);
77
        
78
        $this->activityHeartbeat();
79
        $tmpFile = tempnam(sys_get_temp_dir(), 'ct');
80
81
        if (isset($this->input->{'input_asset'}->{'http'})) {
82
            $ch = curl_init();
83
            curl_setopt($ch, CURLOPT_URL, $this->input->{'input_asset'}->{'http'});
84
            curl_setopt($ch, CURLOPT_RANGE, '0-1024');
85
            curl_setopt($ch, CURLOPT_WRITEFUNCTION, array($this, 'writefn'));
86
            curl_exec($ch);
87
            curl_close($ch);
88
            $chunk = $this->curl_data;
89
        }
90
        else if (isset($this->input->{'input_asset'}->{'bucket'}) &&
91
                 isset($this->input->{'input_asset'}->{'file'})) {
92
            // Fetch first 1 KiB of the file for Magic number validation
93
            $obj = $this->s3->getObject([
94
                'Bucket' => $this->input->{'input_asset'}->{'bucket'},
95
                'Key'    => $this->input->{'input_asset'}->{'file'},
96
                'Range'  => 'bytes=0-1024'
97
            ]);
98
            $chunk = (string) $obj['Body'];
99
        }
100
        
101
        $this->activityHeartbeat();
102
103
        // Determine file type
104
        file_put_contents($tmpFile, $chunk);
0 ignored issues
show
The variable $chunk does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
105
        $mime = trim((new CommandExecuter($this->cpeLogger, $this->logKey))->execute(
106
            'file -b --mime-type '.escapeshellarg($tmpFile))['out']);
107
        $type = substr($mime, 0, strpos($mime, '/'));
108
109
        if ($this->debug)
110
            $this->cpeLogger->logOut(
111
                "DEBUG",
112
                basename(__FILE__),
113
                "File meta information gathered. Mime: $mime | Type: $type",
114
                $this->logKey
115
        );
116
117
        // Load the right transcoder base on input_type
118
        // Get asset detailed info
119
        switch ($type)
120
        {
121
        case 'audio':
122
        case 'video':
123
        case 'image':
124
        default:
125
            require_once __DIR__.'/transcoders/VideoTranscoder.php';
126
127
            // Initiate transcoder obj
128
            $videoTranscoder = new VideoTranscoder($this, $task);
129
            // Get input video information
130
            $assetInfo = $videoTranscoder->getAssetInfo($this->inputFilePath);
131
132
            // Liberate memory
133
            unset($videoTranscoder);
134
        }
135
136
        if ($mime === 'application/octet-stream' && isset($assetInfo->streams)) {
137
            // Check all stream types
138
            foreach ($assetInfo->streams as $stream) {
139
                if ($stream->codec_type === 'video') {
140
                    // For a video type, set type to video and break
141
                    $type = 'video';
142
                    break;
143
                } elseif ($stream->codec_type === 'audio') {
144
                    // For an audio type, set to audio, but don't break
145
                    // in case there's a video stream later
146
                    $type = 'audio';
147
                }
148
            }
149
        }
150
        
151
        $assetInfo->mime = $mime;
152
        $assetInfo->type = $type;
153
154
        $result['input_asset']     = $this->input->{'input_asset'};
0 ignored issues
show
Coding Style Comprehensibility introduced by
$result was never initialized. Although not strictly required by PHP, it is generally a good practice to add $result = 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...
155
        $result['input_metadata']  = $assetInfo;
156
        $result['output_assets']   = $this->input->{'output_assets'};
157
        
158
        return json_encode($result);
159
    }
160
}
161
162
163
/*
164
 ***************************
165
 * Activity Startup SCRIPT
166
 ***************************
167
*/
168
169
// Usage
170 View Code Duplication
function usage()
0 ignored issues
show
The function usage() has been defined more than once; this definition is ignored, only the first definition in src/activities/TranscodeAssetActivity.php (L282-292) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
171
{
172
    echo("Usage: php ". basename(__FILE__) . " -A <Snf ARN> [-C <client class path>] [-N <activity name>] [-h] [-d] [-l <log path>]\n");
173
    echo("-h: Print this help\n");
174
    echo("-d: Debug mode\n");
175
    echo("-l <log_path>: Location where logs will be dumped in (folder).\n");
176
    echo("-A <activity_name>: Activity name this Poller can process. Or use 'SNF_ACTIVITY_ARN' environment variable. Command line arguments have precedence\n");
177
    echo("-C <client class path>: Path to the PHP file that contains the class that implements your Client Interface\n");
178
    echo("-N <activity name>: Override the default activity name. Useful if you want to have different client interfaces for the same activity type.\n");
179
    exit(0);
180
}
181
182
// Check command line input parameters
183 View Code Duplication
function check_activity_arguments()
0 ignored issues
show
The function check_activity_arguments() has been defined more than once; this definition is ignored, only the first definition in src/activities/TranscodeAssetActivity.php (L295-334) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
184
{
185
    // Filling the globals with input
186
    global $arn;
187
    global $logPath;
188
    global $debug;
189
    global $clientClassPath;
190
    global $name;
191
    
192
    // Handle input parameters
193
    if (!($options = getopt("N:A:l:C:hd")))
194
        usage();
195
    
196
    if (isset($options['h']))
197
        usage();
198
199
    // Debug
200
    if (isset($options['d']))
201
        $debug = true;
202
203
    if (isset($options['A']) && $options['A']) {
204
        $arn = $options['A'];
205
    } else if (getenv('SNF_ACTIVITY_ARN')) {
206
        $arn = getenv('SNF_ACTIVITY_ARN');
207
    } else {
208
        echo "ERROR: You must provide the ARN of your activity (Sfn ARN). Use option [-A <ARN>] or environment variable: 'SNF_ACTIVITY_ARN'\n";
209
        usage();
210
    }
211
212
    if (isset($options['C']) && $options['C']) {
213
        $clientClassPath = $options['C'];
214
    }
215
216
    if (isset($options['N']) && $options['N']) {
217
        $name = $options['N'];
218
    }
219
    
220
    if (isset($options['l']))
221
        $logPath = $options['l'];
222
}
223
224
225
/*
226
 * START THE SCRIPT ACTITIVY
227
 */
228
229
// Globals
230
$debug = false;
231
$logPath = null;
232
$arn;
233
$name = 'ValidateAsset';
234
$clientClassPath = null;
235
236
check_activity_arguments();
237
238
$cpeLogger = new SA\CpeSdk\CpeLogger($name, $logPath);
239
$cpeLogger->logOut("INFO", basename(__FILE__),
240
                   "\033[1mStarting activity\033[0m: $name");
241
242
// We instanciate the Activity 'ValidateAsset' and give it a name for Snf
243
$activityPoller = new ValidateAssetActivity(
244
    $clientClassPath,
245
    [
246
        'arn'  => $arn,
247
        'name' => $name
248
    ],
249
    $debug,
250
    $cpeLogger);
251
252
// Initiate the polling loop and will call your `process` function upon trigger
253
$activityPoller->doActivity();
254
255
256