Issues (431)

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.

include/classes/token.class.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
$defflip = (!cfip()) ? exit(header('HTTP/1.1 401 Unauthorized')) : 1;
3
4
class Token Extends Base {
5
  protected $table = 'tokens';
6
7
  /**
8
   * Return time token was created
9
   * @param id int Token ID
10
   * @param time string Creation timestamp
11
   **/
12
  public function getCreationTime($token) {
13
    return $this->getSingle($token, 'time', 'token', 's');
14
  }
15
  
16
  /**
17
   * Fetch a token from our table
18
   * @param name string Setting name
19
   * @return value string Value
20
   **/
21
  public function getToken($strToken, $strType=NULL) {
22 View Code Duplication
    if (empty($strType) || ! $iToken_id = $this->tokentype->getTypeId($strType)) {
0 ignored issues
show
The property tokentype does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
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...
23
      $this->setErrorMessage('Invalid token type: ' . $strType);
24
      return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Token::getToken of type value.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
25
    }
26
    $stmt = $this->mysqli->prepare("SELECT * FROM $this->table WHERE token = ? LIMIT 1");
27
    if ($stmt && $stmt->bind_param('s', $strToken) && $stmt->execute() && $result = $stmt->get_result())
28
      return $result->fetch_assoc();
29
    return $this->sqlError();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->sqlError(); (boolean) is incompatible with the return type documented by Token::getToken of type value.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
30
  }
31
  
32
  /**
33
   * Check if a token we're passing in is completely valid
34
   * @param account_id int Account id of user
35
   * @param token string Token to check
36
   * @param type int Type of token
37
   * @param checkTimeExplicitly Check the token time for expiration; can cause issues w/ timezone & sync
38
   * @return int 0 or 1
39
   */
40
  public function isTokenValid($account_id, $token, $type, $checkTimeExplicitly=false) {
41
    if (!is_int($account_id) || !is_int($type)) {
42
      $this->setErrorMessage("Invalid token");
43
      return 0;
44
    }
45
    $expiretime = $this->tokentype->getExpiration($type);
46
    $ctimedata = new DateTime($this->getCreationTime($token));
47
    $checktime = $ctimedata->getTimestamp() + $expiretime;
48
    $now = time();
49
    if ($checktime >= $now && $checkTimeExplicitly || !$checkTimeExplicitly) {
50
      if ($checkTimeExplicitly) {
51
        $stmt = $this->mysqli->prepare("SELECT * FROM $this->table WHERE account_id = ? AND token = ? AND type = ? AND ? >= UNIX_TIMESTAMP() LIMIT 1");
52
        $stmt->bind_param('isii', $account_id, $token, $type, $checktime);
53
      } else {
54
        $stmt = $this->mysqli->prepare("SELECT * FROM $this->table WHERE account_id = ? AND token = ? AND type = ? LIMIT 1");
55
        $stmt->bind_param('isi', $account_id, $token, $type);
56
      }
57
      if ($stmt->execute())
58
        $res = $stmt->get_result();
59
        return $res->num_rows;
0 ignored issues
show
The variable $res 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...
60
      return $this->sqlError();
0 ignored issues
show
return $this->sqlError(); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
61
    } else {
62
      $this->setErrorMessage("Token has expired or is invalid");
63
      return 0;
64
    }
65
  }
66
  
67
  /**
68
   * Check if a token of this type already exists for a given account_id
69
   * @param strType string Name of the type of token
70
   * @param account_id int Account id of user to check
71
   * @return mixed Number of rows on success, false on failure
72
   */
73
  public function doesTokenExist($strType=NULL, $account_id=NULL) {
74 View Code Duplication
    if (!$iToken_id = $this->tokentype->getTypeId($strType)) {
75
      $this->setErrorMessage('Invalid token type: ' . $strType);
76
      return false;
77
    }
78
    $stmt = $this->mysqli->prepare("SELECT * FROM $this->table WHERE account_id = ? AND type = ? LIMIT 1");
79
    if ($stmt && $stmt->bind_param('ii', $account_id, $iToken_id) && $stmt->execute())
80
      return $stmt->get_result()->num_rows;
81
    return $this->sqlError();
82
  }
83
84
  /**
85
   * Insert a new token
86
   * @param name string Name of the variable
87
   * @param value string Variable value
88
   * @return mixed Token string on success, false on failure
89
   **/
90
  public function createToken($strType, $account_id=NULL) {
91 View Code Duplication
    if (!$iToken_id = $this->tokentype->getTypeId($strType)) {
92
      $this->setErrorMessage('Invalid token type: ' . $strType);
93
      return false;
94
    }
95
    $strToken = bin2hex(openssl_random_pseudo_bytes(32));
96
    $stmt = $this->mysqli->prepare("
97
      INSERT INTO $this->table (token, type, account_id)
98
      VALUES (?, ?, ?)
99
      ");
100
    if ($stmt && $stmt->bind_param('sii', $strToken, $iToken_id, $account_id) && $stmt->execute())
101
      return $strToken;
102
    return $this->sqlError();
103
  }
104
105
 /**
106
   * Delete a used token
107
   * @param token string Token name
108
   * @return bool
109
   **/
110
  public function deleteToken($token) {
111
    $stmt = $this->mysqli->prepare("DELETE FROM $this->table WHERE token = ? LIMIT 1");
112
    if ($stmt && $stmt->bind_param('s', $token) && $stmt->execute())
113
      return true;
114
    return $this->sqlError();
115
  }
116
117
  /**
118
   * Cleanup token table of expired tokens
119
   * @param none
120
   * @return bool
121
   **/
122
  public function cleanupTokens() {
123
    // Get all tokens that have an expiration set
124
    if (!$aTokenTypes = $this->tokentype->getAllExpirations()) {
125
      // Verbose error for crons since this should not happen
126
      $this->setCronMessage('Failed to fetch tokens with expiration times: ' . $this->tokentype->getCronError());
127
      return false;
128
    }
129
130
    $failed = $this->deleted = 0;
0 ignored issues
show
The property deleted does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
131
    foreach ($aTokenTypes as $aTokenType) {
132
      $stmt = $this->mysqli->prepare("DELETE FROM $this->table WHERE (NOW() - time) > ? AND type = ?");
133 View Code Duplication
      if (! ($this->checkStmt($stmt) && $stmt->bind_param('ii', $aTokenType['expiration'], $aTokenType['id']) && $stmt->execute())) {
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...
134
        $failed++;
135
      } else {
136
        $this->deleted += $stmt->affected_rows;
137
      }
138
    }
139 View Code Duplication
    if ($failed > 0) {
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...
140
      $this->setCronMessage('Failed to delete ' . $failed . ' token types from ' . $this->table . ' table');
141
      return false;
142
    }
143
    return true;
144
  }
145
}
146
147
$oToken = new Token();
148
$oToken->setDebug($debug);
149
$oToken->setMysql($mysqli);
150
$oToken->setTokenType($tokentype);
151
$oToken->setErrorCodes($aErrorCodes);
152