Issues (162)

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.

code/authenticators/JwtAuth.php (9 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
namespace Ntb\RestAPI;
5
6
/**
7
 * Authentication mechanism using a token in the request header and validates it on every request.
8
 *
9
 * The mechanism works stateless. JWT is described in RFC 7519.
10
 * @author Christian Blank <[email protected]>
11
 */
12
class JwtAuth extends \SS_Object implements IAuth {
13
14
    public static function authenticate($email, $password) {
15
        $authenticator = \Injector::inst()->get('ApiMemberAuthenticator');
16 View Code Duplication
        if($user = $authenticator->authenticate(['Password' => $password, 'Email' => $email])) {
0 ignored issues
show
This code seems to be duplicated across 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...
17
	        return self::createSession($user);
18
        }
19
    }
20
21
	/**
22
	 * @param Member $user
23
	 * @return ApiSession
24
	 */
25
	public static function createSession($user) {
26
		// create session
27
		$session = ApiSession::create();
28
		$session->User = $user;
0 ignored issues
show
Documentation Bug introduced by
It seems like $user of type object<Ntb\RestAPI\Member> is incompatible with the declared type object<Member> of property $User.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
29
		$session->Token = JwtAuth::generate_token($user);
30
		return $session;
31
	}
32
33
	public static function delete($request) {
34
        // nothing to do here
35
    }
36
37
    /**
38
     * @param \SS_HTTPRequest $request
39
     * @return \Member
0 ignored issues
show
Should the return type not be \Member|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
40
     */
41 View Code Duplication
    public static function current($request) {
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...
42
        try {
43
            $token = AuthFactory::get_token($request);
44
            return self::get_member_from_token($token);
45
        } catch(\Exception $e) {
46
            \SS_Log::log($e->getMessage(), \SS_Log::INFO);
47
        }
48
        return false;
49
    }
50
51
    /**
52
     *
53
     *
54
     * @param string $token
55
     * @throws RestUserException
56
     * @return \Member
0 ignored issues
show
Should the return type not be \Member|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
57
     */
58
    private static function get_member_from_token($token) {
59
        try {
60
            $data = self::jwt_decode($token, self::get_key());
61
            if($data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
62
                // todo: check expire time
63
                if(time() > $data['expire']) {
64
                    throw new RestUserException("Session expired", 403);
65
                }
66
                $id = (int)$data['userId'];
67
                $user = \DataObject::get(\Config::inst()->get('BaseRestController', 'Owner'))->byID($id);
68
                if(!$user) {
69
                    throw new RestUserException("Owner not found in database", 403);
70
                }
71
                return $user;
72
            }
73
        } catch(RestUserException $e) {
74
            throw $e;
75
        } catch(\Exception $e) {
76 View Code Duplication
            if(\Director::isDev() && $token == \Config::inst()->get('JwtAuth', 'DevToken')) {
0 ignored issues
show
This code seems to be duplicated across 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...
77
                return \DataObject::get(\Config::inst()->get('BaseRestController', 'Owner'))->first();
78
            }
79
        }
80
        throw new RestUserException("Token invalid", 403);
81
    }
82
83
    /**
84
     * @param Member $user
85
     * @return string
86
     */
87
    private static function generate_token($user) {
88
        $iat = time();
89
        $data = [
90
            'iat' => $iat,
91
            'jti' => AuthFactory::generate_token($user),
92
            'iss' => \Config::inst()->get('JwtAuth', 'Issuer'),
93
            'expire' => $iat + \Config::inst()->get('JwtAuth', 'ExpireTime'),
94
            'userId' => $user->ID
95
        ];
96
        $key = self::get_key();
97
        return self::jwt_encode($data, $key);
98
    }
99
100
    /**
101
     * @param array $data
102
     * @param string $key
103
     * @return string
104
     */
105
    public static function jwt_encode($data, $key) {
106
        $header = ['typ' => 'JWT'];
107
        $headerEncoded = self::base64_url_encode(json_encode($header));
108
        $dataEncoded = self::base64_url_encode(json_encode($data));
109
        $signature = hash_hmac(\Config::inst()->get('JwtAuth', 'HashAlgorithm'), "$headerEncoded.$dataEncoded", $key);
110
        return "$headerEncoded.$dataEncoded.$signature";
111
    }
112
113
    private static function get_key() {
114
        return \Config::inst()->get('JwtAuth', 'Key');
115
    }
116
117
    /**
118
     * @param string $token
119
     * @param string $key
120
     * @return array
121
     * @throws \Exception
122
     */
123
    public static function jwt_decode($token, $key) {
124
        $exploded = explode('.', $token);
125
        if(count($exploded) < 3) {
126
            throw new \Exception("No valid JWT token");
127
        }
128
        list($headerEncoded, $dataEncoded, $signature) = $exploded;
129
        $selfRun = hash_hmac(\Config::inst()->get('JwtAuth', 'HashAlgorithm'), "$headerEncoded.$dataEncoded", $key);
130
        if($selfRun === $signature) {
131
            return json_decode(self::base64_url_decode($dataEncoded), true);
132
        }
133
        return false;
134
    }
135
136
    static function base64_url_encode($data) {
0 ignored issues
show
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
137
        return rtrim(base64_encode($data), '=');
138
    }
139
140
    static function base64_url_decode($base64) {
0 ignored issues
show
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
141
        return base64_decode(strtr($base64, '-_', '+/'));
142
    }
143
144
}
145