Issues (10)

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/AuthProvider/Token.php (4 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
/*
4
 * This file is part of the Pushok package.
5
 *
6
 * (c) Arthur Edamov <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Pushok\AuthProvider;
13
14
use Jose\Component\Core\JWK;
15
use Jose\Component\KeyManagement\JWKFactory;
16
use Jose\Component\Core\AlgorithmManager;
17
use Jose\Component\Signature\JWSBuilder;
18
use Jose\Component\Signature\Algorithm\ES512;
19
use Jose\Component\Signature\Serializer\CompactSerializer;
20
use Pushok\AuthProviderInterface;
21
use Pushok\Request;
22
23
/**
24
 * Class Token
25
 * @package Pushok\AuthProvider
26
 *
27
 * @see http://bit.ly/communicating-with-apns
28
 */
29
class Token implements AuthProviderInterface
0 ignored issues
show
Since you have declared the constructor as private, maybe you should also declare the class as final.
Loading history...
30
{
31
    /**
32
     * Generated auth token.
33
     *
34
     * @var string
35
     */
36
    private $token;
37
38
    /**
39
     * Path to p8 private key.
40
     *
41
     * @var string|null
42
     */
43
    private $privateKeyPath;
44
45
    /**
46
     * Private key data.
47
     *
48
     * @var string|null
49
     */
50
    private $privateKeyContent;
51
52
    /**
53
     * Private key secret.
54
     *
55
     * @var string|null
56
     */
57
    private $privateKeySecret;
58
59
    /**
60
     * The Key ID obtained from Apple developer account.
61
     *
62
     * @var string
63
     */
64
    private $keyId;
65
66
    /**
67
     * The Team ID obtained from Apple developer account.
68
     *
69
     * @var string
70
     */
71
    private $teamId;
72
73
    /**
74
     * The bundle ID for app obtained from Apple developer account.
75
     *
76
     * @var string
77
     */
78
    private $appBundleId;
79
80
    /**
81
     * This provider accepts the following options:
82
     *
83
     * - key_id
84
     * - team_id
85
     * - app_bundle_id
86
     * - private_key_path
87
     * - private_key_content
88
     * - private_key_secret
89
     *
90
     * @param array $options
91
     */
92
    private function __construct(array $options)
93
    {
94
        $this->keyId = $options['key_id'];
95
        $this->teamId = $options['team_id'];
96
        $this->appBundleId = $options['app_bundle_id'];
97
        $this->privateKeyPath = $options['private_key_path'] ?? null;
98
        $this->privateKeyContent = $options['private_key_content'] ?? null;
99
        $this->privateKeySecret = $options['private_key_secret'] ?? null;
100
    }
101
102
    /**
103
     * Create Token Auth Provider.
104
     *
105
     * @param array $options
106
     * @return Token
107
     */
108
    public static function create(array $options): Token
109
    {
110
        $token = new self($options);
111
        $token->token = $token->generate();
112
113
        return $token;
114
    }
115
116
    /**
117
     * Use previously generated token.
118
     *
119
     * @param string $tokenString
120
     * @param array $options
121
     * @return Token
122
     */
123
    public static function useExisting(string $tokenString, array $options): Token
124
    {
125
        $token = new self($options);
126
        $token->token = $tokenString;
127
128
        return $token;
129
    }
130
131
    /**
132
     * Authenticate client.
133
     *
134
     * @param Request $request
135
     */
136
    public function authenticateClient(Request $request)
137
    {
138
        $request->addHeaders([
139
            'apns-topic' => $this->generateApnsTopic($request->getHeaders()['apns-push-type']),
140
            'Authorization' => 'bearer ' . $this->token,
141
        ]);
142
    }
143
144
    /**
145
     * Generate a correct apns-topic string
146
     *
147
     * @param string $pushType
148
     * @return string
149
     */
150 View Code Duplication
    public function generateApnsTopic(string $pushType)
0 ignored issues
show
This method 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...
151
    {
152
        switch ($pushType) {
153
            case 'voip':
154
                return $this->appBundleId . '.voip';
155
156
            case 'complication':
157
                return $this->appBundleId . '.complication';
158
159
            case 'fileprovider':
160
                return $this->appBundleId . '.pushkit.fileprovider';
161
162
            default:
163
                return $this->appBundleId;
164
        }
165
    }
166
167
    /**
168
     * Get last generated token.
169
     *
170
     * @return string
171
     */
172
    public function get(): string
173
    {
174
        return $this->token;
175
    }
176
177
    /**
178
     * Generate private EC key.
179
     *
180
     * @return JWK
181
     */
182
    private function generatePrivateECKey(): JWK
183
    {
184
        if ($this->privateKeyContent) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->privateKeyContent of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
185
            $content = $this->privateKeyContent;
186
        } elseif ($this->privateKeyPath) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->privateKeyPath of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
187
            $content = \file_get_contents($this->privateKeyPath);
188
        } else {
189
            throw new \InvalidArgumentException('Unable to find private key.');
190
        }
191
192
        return JWKFactory::createFromKey($content, $this->privateKeySecret, [
193
            'kid' => $this->keyId,
194
            'alg' => 'ES512',
195
            'use' => 'sig'
196
        ]);
197
    }
198
199
    /**
200
     * Get claims payload.
201
     *
202
     * @return array
203
     */
204
    private function getClaimsPayload(): array
205
    {
206
        return [
207
            'iss' => $this->teamId,
208
            'iat' => time(),
209
        ];
210
    }
211
212
    /**
213
     * Get protected header.
214
     *
215
     * @param JWK $privateECKey
216
     * @return array
217
     */
218
    private function getProtectedHeader(JWK $privateECKey): array
219
    {
220
        return [
221
            'alg' => 'ES512',
222
            'kid' => $privateECKey->get('kid'),
223
        ];
224
    }
225
226
    /**
227
     * Generate new token.
228
     *
229
     * @return string
230
     */
231
    private function generate(): string
232
    {
233
        $algorithmManager = new AlgorithmManager([
234
          new ES512(),
235
        ]);
236
237
        $jwsBuilder = new JWSBuilder($algorithmManager);
238
        $payload = json_encode($this->getClaimsPayload(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
239
240
        $privateECKey = $this->generatePrivateECKey();
241
242
        $jws = $jwsBuilder
243
            ->create()
244
            ->withPayload($payload)
245
            ->addSignature($privateECKey, $this->getProtectedHeader($privateECKey))
246
            ->build();
247
248
        $serializer = new CompactSerializer();
249
        $this->token = $serializer->serialize($jws);
250
251
        return $this->token;
252
    }
253
}
254