Passed
Pull Request — release_2_0 (#156)
by
unknown
06:21
created

ProfileSilverbullet::getUserExpiryDate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * Contributions to this work were made on behalf of the GÉANT project, a 
5
 * project that has received funding from the European Union’s Horizon 2020 
6
 * research and innovation programme under Grant Agreement No. 731122 (GN4-2).
7
 * 
8
 * On behalf of the GÉANT project, GEANT Association is the sole owner of the 
9
 * copyright in all material which was developed by a member of the GÉANT 
10
 * project. GÉANT Vereniging (Association) is registered with the Chamber of 
11
 * Commerce in Amsterdam with registration number 40535155 and operates in the
12
 * UK as a branch of GÉANT Vereniging. 
13
 * 
14
 * Registered office: Hoekenrode 3, 1102BR Amsterdam, The Netherlands. 
15
 * UK branch address: City House, 126-130 Hills Road, Cambridge CB2 1PQ, UK
16
 * 
17
 * License: see the web/copyright.inc.php file in the file structure or
18
 *          <base_url>/copyright.php after deploying the software
19
 */
20
21
/**
22
 * This file contains the ProfileSilverbullet class.
23
 *
24
 * @author Stefan Winter <[email protected]>
25
 * @author Tomasz Wolniewicz <[email protected]>
26
 *
27
 * @package Developer
28
 *
29
 */
30
31
namespace core;
32
33
use \Exception;
34
35
/**
36
 * Silverbullet (marketed as "Managed IdP") is a RADIUS profile which 
37
 * corresponds directly to a built-in RADIUS server and CA. 
38
 * It provides all functions needed for a admin-side web interface where users
39
 * can be added and removed, and new devices be enabled.
40
 * 
41
 * When downloading a Silverbullet based profile, the profile includes per-user
42
 * per-device client certificates which can be immediately used to log into 
43
 * eduroam.
44
 *
45
 * @author Stefan Winter <[email protected]>
46
 * @author Tomasz Wolniewicz <[email protected]>
47
 *
48
 * @license see LICENSE file in root directory
49
 *
50
 * @package Developer
51
 */
52
class ProfileSilverbullet extends AbstractProfile {
53
54
    const SB_ACKNOWLEDGEMENT_REQUIRED_DAYS = 365;
55
56
    public $termsAndConditions;
0 ignored issues
show
Coding Style Documentation introduced by
Missing member variable doc comment
Loading history...
57
58
    /*
59
     * 
60
     */
61
62
    const PRODUCTNAME = "Managed IdP";
63
64
    /**
65
     * Class constructor for existing profiles (use IdP::newProfile() to actually create one). Retrieves all attributes and 
66
     * supported EAP types from the DB and stores them in the priv_ arrays.
67
     * 
68
     * @param int $profileId identifier of the profile in the DB
69
     * @param IdP $idpObject optionally, the institution to which this Profile belongs. Saves the construction of the IdP instance. If omitted, an extra query and instantiation is executed to find out.
70
     */
71
    public function __construct($profileId, $idpObject = NULL) {
72
        parent::__construct($profileId, $idpObject);
73
74
        $this->entityOptionTable = "profile_option";
75
        $this->entityIdColumn = "profile_id";
76
        $this->attributes = [];
77
78
        $tempMaxUsers = 200; // abolutely last resort fallback if no per-fed and no config option
79
// set to global config value
80
81
        if (isset(CONFIG_CONFASSISTANT['SILVERBULLET']['default_maxusers'])) {
82
            $tempMaxUsers = CONFIG_CONFASSISTANT['SILVERBULLET']['default_maxusers'];
83
        }
84
        $myInst = new IdP($this->institution);
85
        $myFed = new Federation($myInst->federation);
86
        $fedMaxusers = $myFed->getAttributes("fed:silverbullet-maxusers");
87
        if (isset($fedMaxusers[0])) {
88
            $tempMaxUsers = $fedMaxusers[0]['value'];
89
        }
90
91
// realm is automatically calculated, then stored in DB
92
93
        $this->realm = "opaquehash@$myInst->identifier-$this->identifier." . strtolower($myInst->federation) . CONFIG_CONFASSISTANT['SILVERBULLET']['realm_suffix'];
94
        $localValueIfAny = "";
95
96
// but there's some common internal attributes populated directly
97
        $internalAttributes = [
98
            "internal:profile_count" => $this->idpNumberOfProfiles,
99
            "internal:realm" => preg_replace('/^.*@/', '', $this->realm),
100
            "internal:use_anon_outer" => FALSE,
101
            "internal:checkuser_outer" => TRUE,
102
            "internal:checkuser_value" => "anonymous",
103
            "internal:anon_local_value" => $localValueIfAny,
104
            "internal:silverbullet_maxusers" => $tempMaxUsers,
105
            "profile:production" => "on",
106
        ];
107
108
        // and we need to populate eap:server_name and eap:ca_file with the NRO-specific EAP information
109
        $silverbulletAttributes = [
110
            "eap:server_name" => "auth." . strtolower($myFed->tld) . CONFIG_CONFASSISTANT['SILVERBULLET']['server_suffix'],
111
        ];
112
        $temp = array_merge($this->addInternalAttributes($internalAttributes), $this->addInternalAttributes($silverbulletAttributes));
113
        $x509 = new \core\common\X509();
114
        $caHandle = fopen(dirname(__FILE__) . "/../config/SilverbulletServerCerts/" . strtoupper($myFed->tld) . "/root.pem", "r");
115
        if ($caHandle !== FALSE) {
116
            $cAFile = fread($caHandle, 16000000);
117
            foreach ($x509->splitCertificate($cAFile) as $oneCa) {
118
                $temp = array_merge($temp, $this->addInternalAttributes(['eap:ca_file' => $oneCa]));
119
            }
120
        }
121
122
        $tempArrayProfLevel = array_merge($this->addDatabaseAttributes(), $temp);
123
124
// now, fetch and merge IdP-wide attributes
125
126
        $this->attributes = $this->levelPrecedenceAttributeJoin($tempArrayProfLevel, $this->idpAttributes, "IdP");
127
128
        $this->privEaptypes = $this->fetchEAPMethods();
129
130
        $this->name = ProfileSilverbullet::PRODUCTNAME;
131
132
        $this->loggerInstance->debug(3, "--- END Constructing new Profile object ... ---\n");
133
134
        $this->termsAndConditions = "<h2>Product Definition</h2>
135
        <p>" . \core\ProfileSilverbullet::PRODUCTNAME . " outsources the technical setup of " . CONFIG_CONFASSISTANT['CONSORTIUM']['display_name'] . " " . CONFIG_CONFASSISTANT['CONSORTIUM']['nomenclature_institution'] . " functions to the " . CONFIG_CONFASSISTANT['CONSORTIUM']['display_name'] . " Operations Team. The system includes</p>
136
            <ul>
137
                <li>a web-based user management interface where user accounts and access credentials can be created and revoked (there is a limit to the number of active users)</li>
138
                <li>a technical infrastructure ('CA') which issues and revokes credentials</li>
139
                <li>a technical infrastructure ('RADIUS') which verifies access credentials and subsequently grants access to " . CONFIG_CONFASSISTANT['CONSORTIUM']['display_name'] . "</li>           
140
            </ul>
141
        <h2>User Account Liability</h2>
142
        <p>As an " . CONFIG_CONFASSISTANT['CONSORTIUM']['display_name'] . " " . CONFIG_CONFASSISTANT['CONSORTIUM']['nomenclature_institution'] . " administrator using this system, you are authorized to create user accounts according to your local " . CONFIG_CONFASSISTANT['CONSORTIUM']['nomenclature_institution'] . " policy. You are fully responsible for the accounts you issue and are the data controller for all user information you deposit in this system; the system is a data processor.</p>";
143
        $this->termsAndConditions .= "<p>Your responsibilities include that you</p>
144
        <ul>
145
            <li>only issue accounts to members of your " . CONFIG_CONFASSISTANT['CONSORTIUM']['nomenclature_institution'] . ", as defined by your local policy.</li>
146
            <li>must make sure that all accounts that you issue can be linked by you to actual human end users</li>
147
            <li>have to immediately revoke accounts of users when they leave or otherwise stop being a member of your " . CONFIG_CONFASSISTANT['CONSORTIUM']['nomenclature_institution'] . "</li>
148
            <li>will act upon notifications about possible network abuse by your users and will appropriately sanction them</li>
149
        </ul>
150
        <p>";
151
        $this->termsAndConditions .= "Failure to comply with these requirements may make your " . CONFIG_CONFASSISTANT['CONSORTIUM']['nomenclature_federation'] . " act on your behalf, which you authorise, and will ultimately lead to the deletion of your " . CONFIG_CONFASSISTANT['CONSORTIUM']['nomenclature_institution'] . " (and all the users you create inside) in this system.";
152
        $this->termsAndConditions .= "</p>
153
        <h2>Privacy</h2>
154
        <p>With " . \core\ProfileSilverbullet::PRODUCTNAME . ", we are necessarily storing personally identifiable information about the end users you create. While the actual human is only identifiable with your help, we consider all the user data as relevant in terms of privacy jurisdiction. Please note that</p>
155
        <ul>
156
            <li>You are the only one who needs to be able to make a link to the human behind the usernames you create. The usernames you create in the system have to be rich enough to allow you to make that identification step. Also consider situations when you are unavailable or leave the organisation and someone else needs to perform the matching to an individual.</li>
157
            <li>The identifiers we create in the credentials are not linked to the usernames you add to the system; they are randomly generated pseudonyms.</li>
158
            <li>Each access credential carries a different pseudonym, even if it pertains to the same username.</li>
159
            <li>If you choose to deposit users' email addresses in the system, you authorise the system to send emails on your behalf regarding operationally relevant events to the users in question (e.g. notification of nearing expiry dates of credentials, notification of access revocation).
160
        </ul>";
161
    }
162
163
    /**
164
     * Updates database with new installer location; NOOP because we do not
165
     * cache anything in Silverbullet
166
     * 
167
     * @param string $device         the device identifier string
168
     * @param string $path           the path where the new installer can be found
169
     * @param string $mime           the mime type of the new installer
170
     * @param int    $integerEapType the inter-representation of the EAP type that is configured in this installer
171
     * @return void
172
     */
0 ignored issues
show
Coding Style Documentation introduced by
Missing @throws tag in function comment
Loading history...
173
    public function updateCache($device, $path, $mime, $integerEapType) {
174
        // caching is not supported in SB (private key in installers)
175
        // the following merely makes the "unused parameter" warnings go away
176
        // the FALSE in condition one makes sure it never gets executed
177
        if (FALSE || $device == "Macbeth" || $path == "heath" || $mime == "application/witchcraft" || $integerEapType == 0) {
178
            throw new Exception("FALSE is TRUE, and TRUE is FALSE! Hover through the browser and filthy code!");
179
        }
180
    }
181
182
    /**
183
     * register new supported EAP method for this profile
184
     *
185
     * @param \core\common\EAP $type       The EAP Type, as defined in class EAP
186
     * @param int              $preference preference of this EAP Type. If a preference value is re-used, the order of EAP types of the same preference level is undefined.
187
     * @return void
188
     */
0 ignored issues
show
Coding Style Documentation introduced by
Missing @throws tag in function comment
Loading history...
189
    public function addSupportedEapMethod(\core\common\EAP $type, $preference) {
190
        // the parameters really should only list SB and with prio 1 - otherwise,
191
        // something fishy is going on
192
        if ($type->getIntegerRep() != \core\common\EAP::INTEGER_SILVERBULLET || $preference != 1) {
193
            throw new Exception("Silverbullet::addSupportedEapMethod was called for a non-SP EAP type or unexpected priority!");
194
        }
195
        parent::addSupportedEapMethod($type, 1);
196
    }
197
198
    /**
199
     * It's EAP-TLS and there is no point in anonymity
200
     * @param boolean $shallwe always FALSE
201
     * @return void
202
     */
0 ignored issues
show
Coding Style Documentation introduced by
Missing @throws tag in function comment
Loading history...
203
    public function setAnonymousIDSupport($shallwe) {
204
        // we don't do anonymous outer IDs in SB
205
        if ($shallwe === TRUE) {
206
            throw new Exception("Silverbullet: attempt to add anonymous outer ID support to a SB profile!");
207
        }
208
        $this->databaseHandle->exec("UPDATE profile SET use_anon_outer = 0 WHERE profile_id = $this->identifier");
209
    }
210
211
    /**
212
     * find out about the status of a given SB user; retrieves the info regarding all his tokens (and thus all his certificates)
213
     * @param int $userId the userid
214
     * @return array of invitationObjects
215
     */
216
    public function userStatus($userId) {
217
        $retval = [];
218
        $userrows = $this->databaseHandle->exec("SELECT `token` FROM `silverbullet_invitation` WHERE `silverbullet_user_id` = ? AND `profile_id` = ? ", "ii", $userId, $this->identifier);
219
        // SELECT -> resource, not boolean
220
        while ($returnedData = mysqli_fetch_object(/** @scrutinizer ignore-type */ $userrows)) {
221
            $retval[] = new SilverbulletInvitation($returnedData->token);
222
        }
223
        return $retval;
224
    }
225
226
    /**
227
     * finds out the expiry date of a given user
228
     * @param int $userId the numerical user ID of the user in question
229
     * @return string
230
     */
231
    public function getUserExpiryDate($userId) {
232
        $query = $this->databaseHandle->exec("SELECT expiry FROM silverbullet_user WHERE id = ? AND profile_id = ? ", "ii", $userId, $this->identifier);
233
        // SELECT -> resource, not boolean
234
        while ($returnedData = mysqli_fetch_object(/** @scrutinizer ignore-type */ $query)) {
235
            return $returnedData->expiry;
236
        }
237
    }
238
239
    /**
240
     * retrieves the authentication records from the RADIUS servers 
241
     * 
242
     * @param int $userId the numerical user ID of the user in question
243
     * @return array
244
     */
245
    public function getUserAuthRecords($userId) {
246
        // find out all certificate CNs belonging to the user, including expired and revoked ones
247
        $userData = $this->userStatus($userId);
248
        $certNames = [];
249
        foreach ($userData as $oneSlice) {
250
            foreach ($oneSlice->associatedCertificates as $oneCert) {
251
                $certNames[] = $oneCert->username;
252
            }
253
        }
254
        if (empty($certNames)) {
255
            return [];
256
        }
257
        $namesCondensed = "'" . implode("' OR username = '", $certNames) . "'";
258
        $serverHandles = DBConnection::handle("RADIUS");
259
        $returnarray = [];
260
        foreach ($serverHandles as $oneDbServer) {
261
            $query = $oneDbServer->exec("SELECT username, authdate, reply, callingid, operatorname FROM eduroamauth WHERE $namesCondensed ORDER BY authdate DESC");
262
            // SELECT -> resource, not boolean
263
            while ($returnedData = mysqli_fetch_object(/** @scrutinizer ignore-type */ $query)) {
264
                $returnarray[] = ["CN" => $returnedData->username, "TIMESTAMP" => $returnedData->authdate, "RESULT" => $returnedData->reply, "MAC" => $returnedData->callingid, "OPERATOR" => $returnedData->operatorname];
265
            }
266
        }
267
        usort($returnarray, function($one, $another) {
268
            return $one['TIMESTAMP'] < $another['TIMESTAMP'];
269
        });
270
271
        return $returnarray;
272
    }
273
274
    /**
275
     * sets the expiry date of a user to a new date of choice
276
     * @param int       $userId the username
277
     * @param \DateTime $date   the expiry date
278
     * @return void
279
     */
280
    public function setUserExpiryDate($userId, $date) {
281
        $query = "UPDATE silverbullet_user SET expiry = ? WHERE profile_id = ? AND id = ?";
282
        $theDate = $date->format("Y-m-d H:i:s");
283
        $this->databaseHandle->exec($query, "sii", $theDate, $this->identifier, $userId);
284
    }
285
286
    /**
287
     * lists all users of this SB profile
288
     * @return array
289
     */
290
    public function listAllUsers() {
291
        $userArray = [];
292
        $users = $this->databaseHandle->exec("SELECT `id`, `username` FROM `silverbullet_user` WHERE `profile_id` = ? ", "i", $this->identifier);
293
        // SELECT -> resource, not boolean
294
        while ($res = mysqli_fetch_object(/** @scrutinizer ignore-type */ $users)) {
295
            $userArray[$res->id] = $res->username;
296
        }
297
        return $userArray;
298
    }
299
300
    /**
301
     * get the user of this SB profile identified by ID
302
     * @param int $userId the user id
303
     * @return array
304
     */
305
    public function getUserById($userId) {
306
        $users = $this->databaseHandle->exec("SELECT `id`, `username` FROM `silverbullet_user` WHERE `profile_id` = ? AND `id` = ? ", "ii", $this->identifier, $userId);
307
        // SELECT -> resource, not boolean
308
        while ($res = mysqli_fetch_object(/** @scrutinizer ignore-type */ $users)) {
309
            return [$res->id => $res->username];
310
        }
311
        return [];
312
    }
313
314
    /**
315
     * get the user of this SB profile identified by Username
316
     * @param string $userName the username
317
     * @return array
318
     */
319
    public function getUserByName($userName) {
320
        $users = $this->databaseHandle->exec("SELECT `id`, `username` FROM `silverbullet_user` WHERE `profile_id` = ? AND `username` = ? ", "is", $this->identifier, $userName);
321
        // SELECT -> resource, not boolean
322
        while ($res = mysqli_fetch_object(/** @scrutinizer ignore-type */ $users)) {
323
            return [$res->id => $res->username];
324
        }
325
        return [];
326
    }
327
328
    /**
329
     * lists all users which are currently active (i.e. have pending invitations and/or valid certs)
330
     * @return array
331
     */
332
    public function listActiveUsers() {
333
        // users are active if they have a non-expired invitation OR a non-expired, non-revoked certificate
334
        $userCount = [];
335
        $users = $this->databaseHandle->exec("SELECT DISTINCT u.id AS usercount FROM silverbullet_user u, silverbullet_invitation i, silverbullet_certificate c "
336
                . "WHERE u.profile_id = ? "
337
                . "AND ( "
338
                . "( u.id = i.silverbullet_user_id AND i.expiry >= NOW() )"
339
                . "     OR"
340
                . "  ( u.id = c.silverbullet_user_id AND c.expiry >= NOW() AND c.revocation_status != 'REVOKED' ) "
341
                . ")", "i", $this->identifier);
342
        // SELECT -> resource, not boolean
343
        while ($res = mysqli_fetch_object(/** @scrutinizer ignore-type */ $users)) {
344
            $userCount[$res->usercount] = "ACTIVE";
345
        }
346
        return $userCount;
347
    }
348
349
    /**
350
     * adds a new user to the profile
351
     * 
352
     * @param string    $username the username
353
     * @param \DateTime $expiry   the expiry date
354
     * @return int row ID of the new user in the database
355
     */
356
    public function addUser($username, \DateTime $expiry) {
357
        $query = "INSERT INTO silverbullet_user (profile_id, username, expiry) VALUES(?,?,?)";
358
        $date = $expiry->format("Y-m-d H:i:s");
359
        $this->databaseHandle->exec($query, "iss", $this->identifier, $username, $date);
360
        return $this->databaseHandle->lastID();
361
    }
362
363
    /**
364
     * revoke all active certificates and pending invitations of a user
365
     * @param int $userId the username
366
     * @return boolean was the user found and deactivated?
367
     */
0 ignored issues
show
Coding Style Documentation introduced by
Missing @throws tag in function comment
Loading history...
368
    public function deactivateUser($userId) {
369
        // does the user exist and is active, anyway?
370
        $queryExisting = "SELECT id FROM silverbullet_user WHERE profile_id = $this->identifier AND id = ? AND expiry >= NOW()";
371
        $execExisting = $this->databaseHandle->exec($queryExisting, "i", $userId);
372
        // this is a SELECT, and won't return TRUE
373
        if (mysqli_num_rows(/** @scrutinizer ignore-type */ $execExisting) < 1) {
374
            return FALSE;
375
        }
376
        // set the expiry date of any still valid invitations to NOW()
377
        $query = "SELECT token FROM silverbullet_invitation WHERE profile_id = $this->identifier AND silverbullet_user_id = ? AND expiry >= NOW()";
378
        $exec = $this->databaseHandle->exec($query, "i", $userId);
379
        // SELECT -> resource, not boolean
380
        while ($result = mysqli_fetch_object(/** @scrutinizer ignore-type */ $exec)) {
381
            $invitation = new SilverbulletInvitation($result->token);
382
            $invitation->revokeInvitation();
383
        }
384
        // and revoke all certificates
385
        $query2 = "SELECT serial_number, ca_type FROM silverbullet_certificate WHERE profile_id = $this->identifier AND silverbullet_user_id = ? AND expiry >= NOW() AND revocation_status = 'NOT_REVOKED'";
386
        $exec2 = $this->databaseHandle->exec($query2, "i", $userId);
387
        // SELECT -> resource, not boolean
388
        while ($result = mysqli_fetch_object(/** @scrutinizer ignore-type */ $exec2)) {
389
            $certObject = new SilverbulletCertificate($result->serial_number, $result->ca_type);
390
            $certObject->revokeCertificate();
391
        }
392
        // and finally set the user expiry date to NOW(), too
393
        $query3 = "UPDATE silverbullet_user SET expiry = NOW() WHERE profile_id = $this->identifier AND id = ?";
394
        $ret = $this->databaseHandle->exec($query3, "i", $userId);
395
        // this is an UPDATE, and always returns TRUE. Need to tell Scrutinizer all about it.
396
        if ($ret === TRUE) {
397
            return TRUE;
398
        } else {
399
            throw new Exception("The UPDATE statement could not be executed successfully.");
400
        }
401
    }
402
403
    /**
404
     * delete the user in question, including all expired and revoked certificates
405
     * @param int $userId the username
406
     * @return boolean was the user deleted?
407
     */
408
    public function deleteUser($userId) {
409
        // do we really not have any auth records that may need to be tied to this user?
410
        if (count($this->getUserAuthRecords($userId)) > 0) {
411
            return false;
412
        }
413
        // find and delete all certificates
414
        $certQuery = "DELETE FROM silverbullet_certificate WHERE profile_id = $this->identifier AND silverbullet_user_id = ?";
415
        $this->databaseHandle->exec($certQuery, "i", $userId);
416
        // find and delete obsolete invitation token track record
417
        $tokenQuery = "DELETE FROM silverbullet_invitation WHERE profile_id = $this->identifier AND silverbullet_user_id = ?";
418
        $this->databaseHandle->exec($tokenQuery, "i", $userId);
419
        // delete user record itself
420
        $userQuery = "DELETE FROM silverbullet_user WHERE profile_id = $this->identifier AND id = ?";
421
        $this->databaseHandle->exec($userQuery, "i", $userId);
422
    }
423
424
    /**
425
     * updates the last_ack for all users (invoked when the admin claims to have re-verified continued eligibility of all users)
426
     * 
427
     * @return void
428
     */
429
    public function refreshEligibility() {
430
        $query = "UPDATE silverbullet_user SET last_ack = NOW() WHERE profile_id = ?";
431
        $this->databaseHandle->exec($query, "i", $this->identifier);
432
    }
433
434
}
435