Passed
Pull Request — master (#6)
by Tim
01:53
created

PasswordVerify   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 190
Duplicated Lines 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 84
c 4
b 0
f 0
dl 0
loc 190
rs 10
wmc 22

3 Methods

Rating   Name   Duplication   Size   Complexity  
C login() 0 115 13
B extractAttributes() 0 28 7
A __construct() 0 7 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\Module\sqlauth\Auth\Source;
6
7
use Exception;
8
use PDO;
9
use PDOException;
10
use SimpleSAML\Assert\Assert;
11
use SimpleSAML\Error;
12
use SimpleSAML\Logger;
13
use SimpleSAML\Module\sqlauth\Auth\Source\SQL;
14
15
use function array_key_exists;
16
use function array_keys;
17
use function count;
18
use function implode;
19
use function in_array;
20
use function is_null;
21
use function password_verify;
22
use function sprintf;
23
use function strval;
24
25
/**
26
 * Simple SQL authentication source
27
 *
28
 * This class is very much like the SQL class. The major difference is that
29
 * instead of using SHA2 and other functions in the database we use the PHP
30
 * password_verify() function to allow for example PASSWORD_ARGON2ID to be used
31
 * for verification.
32
 *
33
 * While this class has a query parameter as the SQL class does the meaning
34
 * is different. The query for this class should return at least a column
35
 * called passwordhash containing the hashed password which was generated
36
 * for example using
37
 *    password_hash('hello', PASSWORD_ARGON2ID );
38
 *
39
 * Auth only passes if the PHP code below returns true.
40
 *   password_verify($password, row['passwordhash'] );
41
 *
42
 * Unlike the SQL class the username is the only parameter passed to the SQL query,
43
 * the query can not perform password checks, they are performed by the PHP code
44
 * in this class using password_verify().
45
 *
46
 * If there are other columns in the returned data they are assumed to be attributes
47
 * you would like to be returned through SAML.
48
 *
49
 * @package SimpleSAMLphp
50
 */
51
52
class PasswordVerify extends SQL
53
{
54
    /**
55
     * The column in the result set containing the passwordhash.
56
     */
57
    protected string $passwordhashcolumn = 'passwordhash';
58
59
    /**
60
     * Constructor for this authentication source.
61
     *
62
     * @param array $info  Information about this authentication source.
63
     * @param array $config  Configuration.
64
     */
65
    public function __construct(array $info, array $config)
66
    {
67
        // Call the parent constructor first, as required by the interface
68
        parent::__construct($info, $config);
69
70
        if (array_key_exists('passwordhashcolumn', $config)) {
71
            $this->passwordhashcolumn = $config['passwordhashcolumn'];
72
        }
73
    }
74
75
76
    /**
77
     * Extract SQL columns into SAML attribute array
78
     *
79
     * @param array  $data  Associative array from database in the format of PDO fetchAll
80
     * @param array  $forbiddenAttributes An array of attributes to never return
81
     * @return array  Associative array with the users attributes.
82
     */
83
    protected function extractAttributes(array $data, array $forbiddenAttributes = []): array
84
    {
85
        $attributes = [];
86
        foreach ($data as $row) {
87
            foreach ($row as $name => $value) {
88
                if ($value === null) {
89
                    continue;
90
                }
91
                if (in_array($name, $forbiddenAttributes)) {
92
                    continue;
93
                }
94
95
                $value = strval($value);
96
97
                if (!array_key_exists($name, $attributes)) {
98
                    $attributes[$name] = [];
99
                }
100
101
                if (in_array($value, $attributes[$name], true)) {
102
                    // Value already exists in attribute
103
                    continue;
104
                }
105
106
                $attributes[$name][] = $value;
107
            }
108
        }
109
110
        return $attributes;
111
    }
112
113
114
    /**
115
     * Attempt to log in using the given username and password.
116
     *
117
     * On a successful login, this function should return the users attributes. On failure,
118
     * it should throw an exception. If the error was caused by the user entering the wrong
119
     * username or password, a \SimpleSAML\Error\Error('WRONGUSERPASS') should be thrown.
120
     *
121
     * Note that both the username and the password are UTF-8 encoded.
122
     *
123
     * @param string $username  The username the user wrote.
124
     * @param string $password  The password the user wrote.
125
     * @return array  Associative array with the users attributes.
126
     */
127
    protected function login(string $username, string $password): array
128
    {
129
        $db = $this->connect();
130
131
        try {
132
            $sth = $db->prepare($this->query);
133
        } catch (PDOException $e) {
134
            throw new Exception(sprintf(
135
                'sqlauth:%s: - Failed to prepare query: %s',
136
                $this->authId,
137
                $e->getMessage(),
138
            ));
139
        }
140
141
142
        try {
143
            $sth->execute(['username' => $username]);
144
        } catch (PDOException $e) {
145
            throw new Exception(sprintf(
146
                'sqlauth:%s: - Failed to execute sql: %s query: %s',
147
                $this->authId,
148
                $this->query,
149
                $e->getMessage(),
150
            ));
151
        }
152
153
        try {
154
            $data = $sth->fetchAll(PDO::FETCH_ASSOC);
155
        } catch (PDOException $e) {
156
            throw new Exception(sprintf(
157
                'sqlauth:%s: - Failed to fetch result set: %s',
158
                $this->authId,
159
                $e->getMessage(),
160
            ));
161
        }
162
163
        Logger::info(sprintf(
164
            'sqlauth:%s : Got %d rows from database',
165
            $this->authId,
166
            count($data),
167
        ));
168
169
        if (count($data) === 0) {
170
            // No rows returned - invalid username/password
171
            Logger::error(sprintf(
172
                'sqlauth:%s: No rows in result set. Probably wrong username/password.',
173
                $this->authId,
174
            ));
175
            throw new Error\Error('WRONGUSERPASS');
176
        }
177
178
        /**
179
         * Sanity check, passwordhash must be in each resulting tuple and must have
180
         * the same value in every tuple.
181
         *
182
         * Note that $pwhash will contain the passwordhash value after this loop.
183
         */
184
        $pwhash = null;
185
        foreach ($data as $row) {
186
            if (
187
                !array_key_exists($this->passwordhashcolumn, $row)
188
                || is_null($row[$this->passwordhashcolumn])
189
            ) {
190
                Logger::error(sprintf(
191
                    'sqlauth:%s: column %s must be in every result tuple.',
192
                    $this->authId,
193
                    $this->passwordhashcolumn,
194
                ));
195
                throw new Error\Error('WRONGUSERPASS');
196
            }
197
            if ($pwhash) {
198
                if ($pwhash !== $row[$this->passwordhashcolumn]) {
199
                    Logger::error(sprintf(
200
                        'sqlauth:%s: column %s must be THE SAME in every result tuple.',
201
                        $this->authId,
202
                        $this->passwordhashcolumn,
203
                    ));
204
                    throw new Error\Error('WRONGUSERPASS');
205
                }
206
            }
207
            $pwhash = $row[$this->passwordhashcolumn];
208
        }
209
        /**
210
         * This should never happen as the count(data) test above would have already thrown.
211
         * But checking twice doesn't hurt.
212
         */
213
        if (is_null($pwhash)) {
214
            if ($pwhash !== $row[$this->passwordhashcolumn]) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $row seems to be defined by a foreach iteration on line 185. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
215
                Logger::error(sprintf(
216
                    'sqlauth:%s: column %s does not contain a password hash.',
217
                    $this->authId,
218
                    $this->passwordhashcolumn,
219
                ));
220
                throw new Error\Error('WRONGUSERPASS');
221
            }
222
        }
223
224
        /**
225
         * VERIFICATION!
226
         * Now to check if the password the user supplied is actually valid
227
         */
228
        if (!password_verify($password, $pwhash)) {
229
            Logger::error(sprintf('sqlauth:%s: password is incorrect.', $this->authId));
230
            throw new Error\Error('WRONGUSERPASS');
231
        }
232
233
        $attributes = $this->extractAttributes($data, [$this->passwordhashcolumn]);
234
235
        Logger::info(sprintf(
236
            'sqlauth:%s: Attributes: %s',
237
            $this->authId,
238
            implode(',', array_keys($attributes)),
239
        ));
240
241
        return $attributes;
242
    }
243
}
244