Passed
Push — release_2_0 ( 6d1b87...835e2d )
by Stefan
09:07
created

ProfileSilverbullet::deactivateUser()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 32
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 20
nc 9
nop 1
dl 0
loc 32
rs 9.2888
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
        $x509 = new \core\common\X509();
113
        $caHandle = fopen(dirname(__FILE__) . "/../config/SilverbulletServerCerts/" . strtoupper($myFed->tld) . "/root.pem", "r");
114
        if ($caHandle !== FALSE) {
115
            $cAFile = fread($caHandle, 16000000);
116
            $silverbulletAttributes["eap:ca_file"] = $x509->der2pem(($x509->pem2der($cAFile)));
117
        }
118
119
        $temp = array_merge($this->addInternalAttributes($internalAttributes), $this->addInternalAttributes($silverbulletAttributes));
120
        $tempArrayProfLevel = array_merge($this->addDatabaseAttributes(), $temp);
121
122
// now, fetch and merge IdP-wide attributes
123
124
        $this->attributes = $this->levelPrecedenceAttributeJoin($tempArrayProfLevel, $this->idpAttributes, "IdP");
125
126
        $this->privEaptypes = $this->fetchEAPMethods();
127
128
        $this->name = ProfileSilverbullet::PRODUCTNAME;
129
130
        $this->loggerInstance->debug(3, "--- END Constructing new Profile object ... ---\n");
131
132
        $this->termsAndConditions = "<h2>Product Definition</h2>
133
        <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>
134
            <ul>
135
                <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>
136
                <li>a technical infrastructure ('CA') which issues and revokes credentials</li>
137
                <li>a technical infrastructure ('RADIUS') which verifies access credentials and subsequently grants access to " . CONFIG_CONFASSISTANT['CONSORTIUM']['display_name'] . "</li>           
138
            </ul>
139
        <h2>User Account Liability</h2>
140
        <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>";
141
        $this->termsAndConditions .= "<p>Your responsibilities include that you</p>
142
        <ul>
143
            <li>only issue accounts to members of your " . CONFIG_CONFASSISTANT['CONSORTIUM']['nomenclature_institution'] . ", as defined by your local policy.</li>
144
            <li>must make sure that all accounts that you issue can be linked by you to actual human end users</li>
145
            <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>
146
            <li>will act upon notifications about possible network abuse by your users and will appropriately sanction them</li>
147
        </ul>
148
        <p>";
149
        $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.";
150
        $this->termsAndConditions .= "</p>
151
        <h2>Privacy</h2>
152
        <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>
153
        <ul>
154
            <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>
155
            <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>
156
            <li>Each access credential carries a different pseudonym, even if it pertains to the same username.</li>
157
            <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).
158
        </ul>";
159
    }
160
161
    /**
162
     * Updates database with new installer location; NOOP because we do not
163
     * cache anything in Silverbullet
164
     * 
165
     * @param string $device         the device identifier string
166
     * @param string $path           the path where the new installer can be found
167
     * @param string $mime           the mime type of the new installer
168
     * @param int    $integerEapType the inter-representation of the EAP type that is configured in this installer
169
     * @return void
170
     */
0 ignored issues
show
Coding Style Documentation introduced by
Missing @throws tag in function comment
Loading history...
171
    public function updateCache($device, $path, $mime, $integerEapType) {
172
        // caching is not supported in SB (private key in installers)
173
        // the following merely makes the "unused parameter" warnings go away
174
        // the FALSE in condition one makes sure it never gets executed
175
        if (FALSE || $device == "Macbeth" || $path == "heath" || $mime == "application/witchcraft" || $integerEapType == 0) {
176
            throw new Exception("FALSE is TRUE, and TRUE is FALSE! Hover through the browser and filthy code!");
177
        }
178
    }
179
180
    /**
181
     * register new supported EAP method for this profile
182
     *
183
     * @param \core\common\EAP $type       The EAP Type, as defined in class EAP
184
     * @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.
185
     * @return void
186
     */
0 ignored issues
show
Coding Style Documentation introduced by
Missing @throws tag in function comment
Loading history...
187
    public function addSupportedEapMethod(\core\common\EAP $type, $preference) {
188
        // the parameters really should only list SB and with prio 1 - otherwise,
189
        // something fishy is going on
190
        if ($type->getIntegerRep() != \core\common\EAP::INTEGER_SILVERBULLET || $preference != 1) {
191
            throw new Exception("Silverbullet::addSupportedEapMethod was called for a non-SP EAP type or unexpected priority!");
192
        }
193
        parent::addSupportedEapMethod($type, 1);
194
    }
195
196
    /**
197
     * It's EAP-TLS and there is no point in anonymity
198
     * @param boolean $shallwe always FALSE
199
     * @return void
200
     */
0 ignored issues
show
Coding Style Documentation introduced by
Missing @throws tag in function comment
Loading history...
201
    public function setAnonymousIDSupport($shallwe) {
202
        // we don't do anonymous outer IDs in SB
203
        if ($shallwe === TRUE) {
204
            throw new Exception("Silverbullet: attempt to add anonymous outer ID support to a SB profile!");
205
        }
206
        $this->databaseHandle->exec("UPDATE profile SET use_anon_outer = 0 WHERE profile_id = $this->identifier");
207
    }
208
209
    /**
210
     * find out about the status of a given SB user; retrieves the info regarding all his tokens (and thus all his certificates)
211
     * @param int $userId the userid
212
     * @return array of invitationObjects
213
     */
214
    public function userStatus($userId) {
215
        $retval = [];
216
        $userrows = $this->databaseHandle->exec("SELECT `token` FROM `silverbullet_invitation` WHERE `silverbullet_user_id` = ? AND `profile_id` = ? ", "ii", $userId, $this->identifier);
217
        // SELECT -> resource, not boolean
218
        while ($returnedData = mysqli_fetch_object(/** @scrutinizer ignore-type */ $userrows)) {
219
            $retval[] = new SilverbulletInvitation($returnedData->token);
220
        }
221
        return $retval;
222
    }
223
224
    /**
225
     * finds out the expiry date of a given user
226
     * @param int $userId the numerical user ID of the user in question
227
     * @return string
228
     */
229
    public function getUserExpiryDate($userId) {
230
        $query = $this->databaseHandle->exec("SELECT expiry FROM silverbullet_user WHERE id = ? AND profile_id = ? ", "ii", $userId, $this->identifier);
231
        // SELECT -> resource, not boolean
232
        while ($returnedData = mysqli_fetch_object(/** @scrutinizer ignore-type */ $query)) {
233
            return $returnedData->expiry;
234
        }
235
    }
236
237
    /**
238
     * retrieves the authentication records from the RADIUS servers 
239
     * 
240
     * @param int $userId the numerical user ID of the user in question
241
     * @return array
242
     */
243
    public function getUserAuthRecords($userId) {
244
        // find out all certificate CNs belonging to the user, including expired and revoked ones
245
        $userData = $this->userStatus($userId);
246
        $certNames = [];
247
        foreach ($userData as $oneSlice) {
248
            foreach ($oneSlice->associatedCertificates as $oneCert) {
249
                $certNames[] = $oneCert->username;
250
            }
251
        }
252
        if (empty($certNames)) {
253
            return [];
254
        }
255
        $namesCondensed = "'" . implode("' OR username = '", $certNames) . "'";
256
        $serverHandles = DBConnection::handle("RADIUS");
257
        $returnarray = [];
258
        foreach ($serverHandles as $oneDbServer) {
259
            $query = $oneDbServer->exec("SELECT username, authdate, reply, callingid, operatorname FROM eduroamauth WHERE $namesCondensed ORDER BY authdate DESC");
260
            // SELECT -> resource, not boolean
261
            while ($returnedData = mysqli_fetch_object(/** @scrutinizer ignore-type */ $query)) {
262
                $returnarray[] = ["CN" => $returnedData->username, "TIMESTAMP" => $returnedData->authdate, "RESULT" => $returnedData->reply, "MAC" => $returnedData->callingid, "OPERATOR" => $returnedData->operatorname];
263
            }
264
        }
265
        usort($returnarray, function($one, $another) {
266
            return $one['TIMESTAMP'] < $another['TIMESTAMP'];
267
        });
268
269
        return $returnarray;
270
    }
271
272
    /**
273
     * sets the expiry date of a user to a new date of choice
274
     * @param int       $userId the username
275
     * @param \DateTime $date   the expiry date
276
     * @return void
277
     */
278
    public function setUserExpiryDate($userId, $date) {
279
        $query = "UPDATE silverbullet_user SET expiry = ? WHERE profile_id = ? AND id = ?";
280
        $theDate = $date->format("Y-m-d H:i:s");
281
        $this->databaseHandle->exec($query, "sii", $theDate, $this->identifier, $userId);
282
    }
283
284
    /**
285
     * lists all users of this SB profile
286
     * @return array
287
     */
288
    public function listAllUsers() {
289
        $userArray = [];
290
        $users = $this->databaseHandle->exec("SELECT `id`, `username` FROM `silverbullet_user` WHERE `profile_id` = ? ", "i", $this->identifier);
291
        // SELECT -> resource, not boolean
292
        while ($res = mysqli_fetch_object(/** @scrutinizer ignore-type */ $users)) {
293
            $userArray[$res->id] = $res->username;
294
        }
295
        return $userArray;
296
    }
297
298
    /**
299
     * lists all users which are currently active (i.e. have pending invitations and/or valid certs)
300
     * @return array
301
     */
302
    public function listActiveUsers() {
303
        // users are active if they have a non-expired invitation OR a non-expired, non-revoked certificate
304
        $userCount = [];
305
        $users = $this->databaseHandle->exec("SELECT DISTINCT u.id AS usercount FROM silverbullet_user u, silverbullet_invitation i, silverbullet_certificate c "
306
                . "WHERE u.profile_id = ? "
307
                . "AND ( "
308
                . "( u.id = i.silverbullet_user_id AND i.expiry >= NOW() )"
309
                . "     OR"
310
                . "  ( u.id = c.silverbullet_user_id AND c.expiry >= NOW() AND c.revocation_status != 'REVOKED' ) "
311
                . ")", "i", $this->identifier);
312
        // SELECT -> resource, not boolean
313
        while ($res = mysqli_fetch_object(/** @scrutinizer ignore-type */ $users)) {
314
            $userCount[$res->usercount] = "ACTIVE";
315
        }
316
        return $userCount;
317
    }
318
319
    /**
320
     * adds a new user to the profile
321
     * 
322
     * @param string    $username the username
323
     * @param \DateTime $expiry   the expiry date
324
     * @return int row ID of the new user in the database
325
     */
326
    public function addUser($username, \DateTime $expiry) {
327
        $query = "INSERT INTO silverbullet_user (profile_id, username, expiry) VALUES(?,?,?)";
328
        $date = $expiry->format("Y-m-d H:i:s");
329
        $this->databaseHandle->exec($query, "iss", $this->identifier, $username, $date);
330
        return $this->databaseHandle->lastID();
331
    }
332
333
    /**
334
     * revoke all active certificates and pending invitations of a user
335
     * @param int $userId the username
336
     * @return boolean was the user found and deactivated?
337
     */
0 ignored issues
show
Coding Style Documentation introduced by
Missing @throws tag in function comment
Loading history...
338
    public function deactivateUser($userId) {
339
        // does the user exist and is active, anyway?
340
        $queryExisting = "SELECT id FROM silverbullet_user WHERE profile_id = $this->identifier AND id = ? AND expiry >= NOW()";
341
        $execExisting = $this->databaseHandle->exec($queryExisting, "i", $userId);
342
        // this is a SELECT, and won't return TRUE
343
        if (mysqli_num_rows(/** @scrutinizer ignore-type */ $execExisting) < 1) {
344
            return FALSE;
345
        }
346
        // set the expiry date of any still valid invitations to NOW()
347
        $query = "SELECT token FROM silverbullet_invitation WHERE profile_id = $this->identifier AND silverbullet_user_id = ? AND expiry >= NOW()";
348
        $exec = $this->databaseHandle->exec($query, "i", $userId);
349
        // SELECT -> resource, not boolean
350
        while ($result = mysqli_fetch_object(/** @scrutinizer ignore-type */ $exec)) {
351
            $invitation = new SilverbulletInvitation($result->token);
352
            $invitation->revokeInvitation();
353
        }
354
        // and revoke all certificates
355
        $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'";
356
        $exec2 = $this->databaseHandle->exec($query2, "i", $userId);
357
        // SELECT -> resource, not boolean
358
        while ($result = mysqli_fetch_object(/** @scrutinizer ignore-type */ $exec2)) {
359
            $certObject = new SilverbulletCertificate($result->serial_number, $result->ca_type);
360
            $certObject->revokeCertificate();
361
        }
362
        // and finally set the user expiry date to NOW(), too
363
        $query3 = "UPDATE silverbullet_user SET expiry = NOW() WHERE profile_id = $this->identifier AND id = ?";
364
        $ret = $this->databaseHandle->exec($query3, "i", $userId);
365
        // this is an UPDATE, and always returns TRUE. Need to tell Scrutinizer all about it.
366
        if ($ret === TRUE) {
367
            return TRUE;
368
        } else {
369
            throw new Exception("The UPDATE statement could not be executed successfully.");
370
        }
371
    }
372
373
    /**
374
     * delete the user in question, including all expired and revoked certificates
375
     * @param int $userId the username
376
     * @return boolean was the user deleted?
377
     */
378
    public function deleteUser($userId) {
379
        // do we really not have any auth records that may need to be tied to this user?
380
        if (count($this->getUserAuthRecords($userId)) > 0) {
381
            return false;
382
        }
383
        // find and delete all certificates
384
        $certQuery = "DELETE FROM silverbullet_certificate WHERE profile_id = $this->identifier AND silverbullet_user_id = ?";
385
        $this->databaseHandle->exec($certQuery, "i", $userId);
386
        // find and delete obsolete invitation token track record
387
        $tokenQuery = "DELETE FROM silverbullet_invitation WHERE profile_id = $this->identifier AND silverbullet_user_id = ?";
388
        $this->databaseHandle->exec($tokenQuery, "i", $userId);
389
        // delete user record itself
390
        $userQuery = "DELETE FROM silverbullet_user WHERE profile_id = $this->identifier AND id = ?";
391
        $this->databaseHandle->exec($userQuery, "i", $userId);
392
        
393
    }
394
    /**
395
     * updates the last_ack for all users (invoked when the admin claims to have re-verified continued eligibility of all users)
396
     * 
397
     * @return void
398
     */
399
    public function refreshEligibility() {
400
        $query = "UPDATE silverbullet_user SET last_ack = NOW() WHERE profile_id = ?";
401
        $this->databaseHandle->exec($query, "i", $this->identifier);
402
    }
403
404
}
405