• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

NathanGibbs3 / BASE / 624

pending completion
624

push

travis-ci-com

NathanGibbs3
Merge branch 'devel'

562 of 562 new or added lines in 28 files covered. (100.0%)

3145 of 17504 relevant lines covered (17.97%)

23.22 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

62.93
/includes/base_auth.inc.php
1
<?php
2
// Basic Analysis and Security Engine (BASE)
3
// Copyright (C) 2019-2023 Nathan Gibbs
4
// Copyright (C) 2004 BASE Project Team
5
// Copyright (C) 2000 Carnegie Mellon University
6
//
7
//   For license info: See the file 'base_main.php'
8
//
9
//       Project Lead: Nathan Gibbs
10
// Built upon work by: Kevin Johnson & the BASE Project Team
11
//                     Roman Danyliw <rdd@cert.org>, <roman@danyliw.com>
12
//
13
//            Purpose: User manangement object.
14
//                     Role management object.
15
//                     Access Authoriztion routines.
16
//                     If the variable $Use_Auth_System = 0 (zero), Access
17
//                     authorization checks always pass.
18
//
19
//          Author(s): Nathan Gibbs
20
//                     Kevin Johnson
21
// Ensure the conf file has been loaded. Prevent direct access to this file.
22
defined( '_BASE_INC' ) or die( 'Accessing this file directly is not allowed.' );
23

24
class BaseUser {
25
        var $db;
26

27
        function __construct() { // PHP 5+ constructor Shim.
28
                // Class/Method agnostic shim code.
29
                $SCname = get_class();
260✔
30
                if ( method_exists($this, $SCname) ) {
260✔
31
                        $SCargs = func_get_args();
260✔
32
                        call_user_func_array(array($this, $SCname), $SCargs);
260✔
33
                }else{
78✔
34
                        // @codeCoverageIgnoreStart
35
                        // Should never execute.
36
                        trigger_error( // Will need to add this message to the TD.
37
                                "Class: $SCname No Legacy Constructor.\n",
38
                                E_USER_ERROR
39
                        );
40
                        // @codeCoverageIgnoreEnd
41
                }
42
        }
182✔
43
        function BaseUser() { // PHP 4x constructor.
44
                GLOBAL $DBlib_path, $DBtype, $db_connect_method, $alert_dbname,
182✔
45
                $alert_host, $alert_port, $alert_user, $alert_password;
104✔
46
                $db = NewBASEDBConnection($DBlib_path, $DBtype);
260✔
47
                $db->baseDBConnect(
260✔
48
                        $db_connect_method, $alert_dbname, $alert_host, $alert_port,
182✔
49
                        $alert_user, $alert_password, 1
182✔
50
                );
78✔
51
                $db->DB->SetFetchMode(ADODB_FETCH_BOTH);
260✔
52
                $this->db = $db;
260✔
53
        }
182✔
54
        // Core Authentication System.
55
        // Accepts a username and password.
56
        // Returns:
57
        //        0 if the username and pwd are correct.
58
        //        1 if the password is wrong.
59
        //        2 if the user is disabled.
60
        //        3 if the username doesn't exist
61
        function AuthenticateCore( $user = '', $pwd = '' ){
62
                GLOBAL $debug_mode, $et;
80✔
63
                $Ret = -1;
110✔
64
                if ( !LoadedString($user) ){ // Input Validation
110✔
65
                        $Ret = 3; // Needs User Name, default to nonexistent user.
22✔
66
                }else{
8✔
67
                        $db = $this->db;
88✔
68
                        $user = filterSql($user,1,$db); // Input sanitazation.
88✔
69
                        $pwd  = filterSql($pwd,1,$db);
88✔
70
                        $sql = "SELECT * from base_users where base_users.usr_login ='" . $user ."';";
88✔
71
                        $rs = $db->baseExecute($sql);
88✔
72
                        if (
73
                                $rs != false
40✔
74
                                && $db->baseErrorMessage() == ''
88✔
75
                                && $rs->baseRecordCount() > 0
88✔
76
                        ){ // Error Check
32✔
77
                                $result = $rs->baseFetchRow();
66✔
78
                                if ( $result['usr_enabled'] == 0 ){
66✔
79
                                        $Ret = 2; // User Account Disabled.
22✔
80
                                }else{
8✔
81
                                        if ( $result['usr_pwd'] == $this->cryptpassword($pwd) ){
44✔
82
                                                $Ret = 0; // Password OK
22✔
83
                                        }else{
8✔
84
                                                $Ret = 1; // Password Wrong
22✔
85
                                        }
86
                                }
87
                                $rs->baseFreeRows();
66✔
88
                        }else{
24✔
89
                                $Ret = 3;
22✔
90
                        }
91
                }
92
                if ( isset($et) && is_object($et) ){ // Need to TD this in Issue #11 branch.
110✔
93
                        $et->Mark('Authentication Check.');
×
94
                }
95
                return $Ret;
110✔
96
        }
97
        // Same inputs/returns as AuthenticateCore.
98
        // Sets the role cookie on success.
99
        function Authenticate( $user = '', $pwd = '' ){
100
                $EMPfx = __FUNCTION__ . ': ';
×
101
                $Ret = $this->AuthenticateCore( $user, $pwd );
×
102
                if ( $Ret == 0 ){
×
103
                        KML($EMPfx . 'Pass', 2);
×
104
                        $this->setRoleCookie($this->cryptpassword($pwd), $user);
×
105
                }
106
                return $Ret;
×
107
        }
108
        // Same inputs as AuthenticateCore.
109
        // returns "Failed" on failure or role_id on success.
110
        function AuthenticateNoCookie( $user = '', $pwd = '' ) {
111
                $Ret = $this->AuthenticateCore( $user, $pwd );
×
112
                if ( $Ret == 0 ){ // Get RoleID
×
113
                        $db = $this->db;
×
114
                        $user = filterSql($user,1,$db); // Input sanitazation.
×
115
                        $pwd  = filterSql($pwd,1,$db);
×
116
                        $sql = "SELECT role_id FROM base_users where usr_login='" . $user
117
                        . "' AND usr_pwd='".$this->cryptpassword($pwd)."';";
×
118
                        $rs = $db->baseExecute($sql);
×
119
                        if (
120
                                $rs != false
121
                                && $db->baseErrorMessage() == ''
×
122
                                && $rs->baseRecordCount() > 0
×
123
                        ){ // Error Check
124
                                $Ret = $rs->baseFetchRow();
×
125
                                $rs->baseFreeRows();
×
126
                                if ( isset($Ret[0]) ){
×
127
                                        $Ret = intval($Ret[0]);
×
128
                                }
129
                        }else{
130
                                $Ret = 'Failed';
×
131
                        }
132
                }else{
133
                        $Ret = 'Failed';
×
134
                }
135
                return $Ret;
×
136
        }
137
        // Accepts a username.
138
        // Returns true if user account is enabled, false otherwise.
139
        function isActive( $user = '' ){
140
                $Ret = false;
128✔
141
                if ( LoadedString($user) ){ // Input Validation
128✔
142
                        $db = $this->db;
106✔
143
                        $user = filterSql($user,1,$db); // Input sanitazation.
106✔
144
                        $sql = "SELECT usr_enabled FROM base_users WHERE usr_login ='"
20✔
145
                        .$user."';";
76✔
146
                        $rs = $db->baseExecute($sql);
106✔
147
                        if (
148
                                $rs != false
50✔
149
                                && $db->baseErrorMessage() == ''
106✔
150
                                && $rs->baseRecordCount() > 0
106✔
151
                        ){ // Error Check
36✔
152
                                $Active = $rs->baseFetchRow();
84✔
153
                                $rs->baseFreeRows();
84✔
154
                                if ( isset($Active[0]) ){
84✔
155
                                        if ( intval($Active[0]) == 1 ){
84✔
156
                                                $Ret = true;
62✔
157
                                        }
20✔
158
                                }
28✔
159
                        }
28✔
160
                }
36✔
161
                return $Ret;
128✔
162
        }
163
    function hasRole($roleNeeded)
164
    {
165
        // Checks which role the user has
166
        $role = $this->readRoleCookie();
40✔
167
        if (($role > $roleNeeded) || $role == 0)
40✔
168
        {
12✔
169
            // returns unauthorized
170
            return 0;
×
171
        }
172
        
173
        return 1;
40✔
174
        
175
    }
176
    
177
    function addUser($user, $role, $password, $name)
178
    {
179
        //adds user
180
        $db = $this->db;
×
181
        $sql = "SELECT * FROM base_users WHERE usr_login = '" . $user . "'";
×
182
        $exists = $db->baseExecute($sql);
×
183
        if ( $exists->baseRecordCount() > 0)
×
184
        {
185
            return "User Already Exists";
×
186
        }
187
        $cryptpassword = $this->cryptpassword($password);
×
188
        $sql = "SELECT MAX(usr_id) FROM base_users;";
×
189
        $usercount = $db->baseExecute($sql);
×
190
        $usercnt = $usercount->baseFetchRow();
×
191
        $userid = $usercnt[0] + 1;
×
192
        $sql = "INSERT INTO base_users (usr_id, usr_login, usr_pwd, role_id, usr_name, usr_enabled)";
×
193
        $sql .= "VALUES (".$userid .", '".$user."','".$cryptpassword."',".$role.",'".$name."', 1);";
×
194
        $db->baseExecute($sql, -1, -1, false);
×
195
        return _ADDEDSF;
×
196
    }
197
    
198
    function disableUser($user)
199
    {
200
        //disables user
201
        $db = $this->db;
×
202
        $sql = "UPDATE base_users SET usr_enabled = '0' WHERE usr_id = '" . $user . "';";
×
203
        $disabled = $db->baseExecute($sql);
×
204
        return;
×
205
    }
206
    
207
    function deleteUser($user)
208
    {
209
        //deletes the user
210
        $db = $this->db;
×
211
        $sql = "DELETE FROM base_users WHERE usr_id = '" . $user . "';";
×
212
        $deleted = $db->baseExecute($sql);
×
213
        return;
×
214
    }
215

216
    function enableUser($user)
217
    {
218
        //enables user
219
        $db = $this->db;
×
220
        $sql = "UPDATE base_users SET usr_enabled = '1' WHERE usr_id = '" . $user . "';";
×
221
        $enabled = $db->baseExecute($sql);
×
222
        return;
×
223
    }
224
    
225
    function updateUser($userarray)
226
    {
227
        /* This function accepts an array in the following format
228
          $userarray[0] = $userid
229
          $userarray[1] = $fullname
230
          $userarray[2] = $roleid
231
        */
232
        $db = $this->db;
×
233
        $sql = "UPDATE base_users SET usr_name = '". $userarray[1] ."', role_id = '" . $userarray[2] . "' ";
×
234
        $sql = $sql . "WHERE usr_id = '" . $userarray[0] . "'";
×
235
        $enabled = $db->baseExecute($sql);
×
236
        return;
×
237
    }
238
    
239
    function changePassword($user, $oldpassword, $newpassword)
240
    {
241
        // Changes the user's password
242
        $db = $this->db;
×
243
        $sql = "SELECT usr_pwd from base_users where usr_login = '" . $user ."';";
×
244
        $userRS = $db->baseExecute($sql);
×
245
        if ( $db->baseErrorMessage() != "" )
×
246
        {
247
            // Generic SQL error
248
            $error = returnErrorMessage(_NOPWDCHANGE . $db->baseErrorMessage());
×
249
            return $error;
×
250
        } elseif ($userRS->baseRecordCount() == 0)
×
251
        {
252
            // User doesn't exist... Someone is playing with their cookie
253
            $error = returnErrorMessage(_NOUSER);
×
254
            return $error;
×
255
        }
256
        $row = $userRS->baseFetchRow();
×
257
        $cryptoldpasswd = $this->cryptpassword($oldpassword);
×
258
        if ($cryptoldpasswd != $row[0])
×
259
        {
260
            // Old password doesn't match record
261
            $error = returnErrorMessage(_OLDPWD);
×
262
            return $error;
×
263
        }
264
        // Finally... lets change the password
265
        $sql = "UPDATE base_users SET usr_pwd='" . $this->cryptpassword($newpassword);
×
266
        $sql = $sql . "' WHERE usr_login='". $user . "';";
×
267
        $chngpwd = $db->baseExecute($sql);
×
268
        if ( $db->baseErrorMessage() != "" )
×
269
        {
270
            // Generic SQL error
271
            $error = returnErrorMessage(_PWDCANT. $db->baseErrorMessage());
×
272
            return $error;
×
273
        }
274
        
275
        return _PWDDONE;
×
276
    }
277
        function returnUser(){ // returns user login from role cookie
278
                $user = '';
84✔
279
                if ( isset($_COOKIE['BASERole']) ){
84✔
280
                        $cookievalue = $_COOKIE['BASERole'];
62✔
281
                        $cookiearr = explode('|', $cookievalue);
62✔
282
                        $user = $cookiearr[1];
62✔
283
                }
20✔
284
                return $user;
84✔
285
        }
286
        function returnUserID($user){ // Returns uid of user, false on Error.
287
                $Ret = false;
154✔
288
                if ( LoadedString($user) ){ // Input Validation
154✔
289
                        $db = $this->db;
132✔
290
                        $sql = "SELECT usr_id FROM base_users WHERE usr_login = '" . $user . "';";
132✔
291
                        $rs = $db->baseExecute($sql);
132✔
292
                        if (
293
                                $rs != false
60✔
294
                                && $db->baseErrorMessage() == ''
132✔
295
                                && $rs->baseRecordCount() > 0
132✔
296
                        ){ // Error Check
48✔
297
                                $usrid = $rs->baseFetchRow();
110✔
298
                                $rs->baseFreeRows();
110✔
299
                                if ( isset($usrid[0]) ){
110✔
300
                                        $Ret = intval($usrid[0]);
110✔
301
                                }
40✔
302
                        }
40✔
303
                }
48✔
304
                return $Ret;
154✔
305
        }
306
        function returnUsers(){
307
        /* returns an array of all users info
308
         * each array item is formatted as
309
         * array[] = usr_id|usr_login|role_id|usr_name|usr_enabled
310
        */
311
        $userarray = NULL;
×
312
        $db = $this->db;
×
313
        $sql = "SELECT usr_id, usr_login, role_id, usr_name, usr_enabled ";
×
314
        $sql = $sql . "FROM base_users ORDER BY usr_id;";
×
315
        $result = $db->baseExecute($sql);
×
316
        
317
        $i = 0;
×
318
        while ( ($myrow = $result->baseFetchRow()) && ($i < $result->baseRecordCount()) )
×
319
        {
320
            $userarray[$i] = $myrow[0] . "|" . $myrow[1] . "|" . $myrow[2] . "|" . $myrow[3] . "|" . $myrow[4];
×
321
            ++$i;
×
322
        }
323
        $result->baseFreeRows();
×
324
        return $userarray;
×
325
    }
326
        function returnEditUser( $userid, $XSS = 1 ){
327
                // Returns an array of user's info.
328
                // Each array item is formatted as:
329
                // array[0] = usr_id|usr_login|role_id|usr_name|usr_enabled
330
                // Returns false on Error.
331
                $Ret = false;
132✔
332
                $userid = intval($userid); // Input Validation
132✔
333
                if ( $userid > 0 ){
132✔
334
                        if ( !is_numeric($XSS) ){
110✔
335
                                $XSS = 1;
22✔
336
                        }
8✔
337
                        $db = $this->db;
110✔
338
                        $sql = "SELECT usr_id, usr_login, role_id, usr_name, usr_enabled ";
110✔
339
                        $sql .= "FROM base_users WHERE usr_id = '" . $userid . "';";
110✔
340
                        $result = $db->baseExecute($sql);
110✔
341
                        if ( $result != false ){ // Error Check
110✔
342
                                $myrow = $result->baseFetchRow();
110✔
343
                                $result->baseFreeRows();
110✔
344
                                if ( $XSS > 0 ){ // Anti XSS Output Data
110✔
345
                                        $myrow = XSSPrintSafe($myrow);
88✔
346
                                }
32✔
347
                                $Ret = $myrow;
110✔
348
                        }
40✔
349
                }
40✔
350
                return $Ret;
132✔
351
        }
352
        function roleName( $roleID, $XSS = 1 ){
353
        // Returns name of roleID, false on Error.
354
                $Ret = false;
132✔
355
                $roleID = intval($roleID); // Input Validation
132✔
356
                if ( $roleID > 0 ){
132✔
357
                        if ( !is_numeric($XSS) ){
110✔
358
                                $XSS = 1;
22✔
359
                        }
8✔
360
                        $db = $this->db;
110✔
361
                        $sql = "SELECT role_name FROM base_roles WHERE role_id = '" . $roleID . "';";
110✔
362
                        $result = $db->baseExecute($sql);
110✔
363
                        if ( $result != false ){ // Error Check
110✔
364
                                $rolename = $result->baseFetchRow();
110✔
365
                                $result->baseFreeRows();
110✔
366
                                if ( isset($rolename[0]) ){
110✔
367
                                        $Ret = $rolename[0];
88✔
368
                                }
32✔
369
                                if ( $XSS > 0 ){ // Anti XSS Output Data
110✔
370
                                        $Ret = XSSPrintSafe($Ret);
88✔
371
                                }
32✔
372
                        }
40✔
373
                }
40✔
374
                return $Ret;
132✔
375
        }
376
        function returnRoleNamesDropDown($roleid){
377
                // Returns an HTML drop down list with all of the role names.
378
                // The passed $roleid will be selected if it exists.
379
                $db = $this->db;
110✔
380
                $sql = "SELECT role_id, role_name FROM base_roles;";
110✔
381
                $result = $db->baseExecute($sql);
110✔
382
                $tmpHTML = NLI("<select name='roleID'>",7);
110✔
383
                $i = 0;
110✔
384
                while (
385
                        ($myrow = $result->baseFetchRow())
110✔
386
                        && ($i < $result->baseRecordCount())
110✔
387
                ){
40✔
388
                        $tmp = "<option value='".$myrow[0]."'";
110✔
389
                        $tmp .= chk_select($roleid,$myrow[0]);
110✔
390
                        $tmp .= '>'.XSSPrintSafe($myrow[1]).'</option>';
110✔
391
                        $tmpHTML .= NLI($tmp,8);
110✔
392
                        ++$i;
110✔
393
                }
40✔
394
                $result->baseFreeRows();
110✔
395
                $tmpHTML .= NLI('</select>',7);
110✔
396
                return $tmpHTML;
110✔
397
        }
398

399
        function setRoleCookie( $passwd, $user ){
400
                //Sets cookie with the md5 summed passwd embedded.
401
        $hash = md5($passwd . $user . "BASEUserRole");
×
402
        $cookievalue = $passwd . "|" . $user . "|";
×
403
                BCS('BASERole', $cookievalue);
×
404
        }
405

406
        function readRoleCookie(){ // Reads the roleCookie and returns the role id.
407
                $Ret = 0;
194✔
408
                if ( isset($_COOKIE['BASERole']) ){ // Check cookie sanity
194✔
409
                        $cookievalue = $_COOKIE['BASERole'];
150✔
410
                        $cookiearr = explode('|', $cookievalue);
150✔
411
                        $user = '';
150✔
412
                        $pwd = '';
150✔
413
                        if ( isset($cookiearr[0]) ){
150✔
414
                                $pwd = $cookiearr[0];
150✔
415
                        }
52✔
416
                        if ( isset($cookiearr[1]) ){
150✔
417
                                $user = $cookiearr[1];
128✔
418
                        }
44✔
419
                        $db = $this->db;
150✔
420
                        $user = filterSql($user,1,$db); // Input sanitazation.
150✔
421
                        $pwd  = filterSql($pwd,1,$db);
150✔
422
                        $sql = "SELECT role_id FROM base_users where usr_login='".$user
98✔
423
                        ."' AND usr_pwd='".$pwd."';";
108✔
424
                        $result = $this->db->baseExecute($sql);
150✔
425
                        // Error Check
426
                        if ( $result != false && is_array($result->row->fields) ){
150✔
427
                                $Ret = $result->row->fields['role_id'];
62✔
428
                        }
20✔
429
                }
52✔
430
                return $Ret;
194✔
431
        }
432
        // @codeCoverageIgnoreStart
433
        // Why write a unit test for a builtin function wrapper.
434
        function cryptpassword( $password ){
435
                // Returns the md5 hash of supplied password.
436
                // Security wise this is a bad idea.
437
                // Opened Issue #79 to track this.
438
                // https://github.com/NathanGibbs3/BASE/issues/79
439
                $cryptpwd = md5($password);
440
                return $cryptpwd;
441
        }
442
        // @codeCoverageIgnoreEnd
443
}
444

445
class BaseRole {
446
        var $db;
447

448
        function __construct() { // PHP 5+ constructor Shim.
449
                // Class/Method agnostic shim code.
450
                $SCname = get_class();
×
451
                if ( method_exists($this, $SCname) ) {
×
452
                        $SCargs = func_get_args();
×
453
                        call_user_func_array(array($this, $SCname), $SCargs);
×
454
                }else{
455
                        // @codeCoverageIgnoreStart
456
                        // Should never execute.
457
                        trigger_error( // Will need to add this message to the TD.
458
                                "Class: $SCname No Legacy Constructor.\n",
459
                                E_USER_ERROR
460
                        );
461
                        // @codeCoverageIgnoreEnd
462
                }
463
        }
464
        function BaseRole() { // PHP 4x constructor.
465
                GLOBAL $DBlib_path, $DBtype, $db_connect_method, $alert_dbname,
466
                $alert_host, $alert_port, $alert_user, $alert_password;
467
                $db = NewBASEDBConnection($DBlib_path, $DBtype);
×
468
                $db->baseDBConnect(
×
469
                        $db_connect_method, $alert_dbname, $alert_host, $alert_port,
470
                        $alert_user, $alert_password, 1
471
                );
472
                $this->db = $db;
×
473
        }
474
    function addRole($roleid, $rolename, $desc)
475
    {
476
        //adds role
477
        $db = $this->db;
×
478
        $sql = "SELECT * FROM base_roles WHERE role_name = '" . $rolename . "'";
×
479
        $exists = $db->baseExecute($sql);
×
480
        if ( $exists->baseRecordCount() > 0)
×
481
        {
482
            return _ROLEEXIST;
×
483
        }
484
        $sql = "SELECT * FROM base_roles WHERE role_id = '" . $roleid . "'";
×
485
        $exists = $db->baseExecute($sql);
×
486
        if ( $exists->baseRecordCount() > 0)
×
487
        {
488
            return _ROLEIDEXIST;
×
489
        }
490
        $sql ="INSERT INTO base_roles (role_id, role_name, role_desc)";
×
491
        $sql = $sql . "VALUES (".$roleid .", '".$rolename ."','".$desc."');";
×
492
        $db->baseExecute($sql, -1, -1, false);
×
493
        return _ROLEADDED;
×
494
    }
495
        function returnEditRole( $roleid, $XSS = 1 ){
496
                // Returns an array of Role's info.
497
                // Each array item is formatted as:
498
                // array[0] = role_id|role_name|role_desc
499
                $Ret = false;
132✔
500
                $roleid = intval($roleid); // Input Validation
132✔
501
                if ( $roleid > 0 ){
132✔
502
                        if ( !is_numeric($XSS) ){
110✔
503
                                $XSS = 1;
22✔
504
                        }
8✔
505
                        $db = $this->db;
110✔
506
                        $sql = "SELECT role_id, role_name, role_desc ";
110✔
507
                        $sql .= "FROM base_roles WHERE role_id = '" . $roleid . "';";
110✔
508
                        $result = $db->baseExecute($sql);
110✔
509
                        if ( $result != false ){ // Error Check
110✔
510
                                $myrow = $result->baseFetchRow();
110✔
511
                                $result->baseFreeRows();
110✔
512
                                if ( $XSS == 1 ){ // Anti XSS Output Data
110✔
513
                                        $myrow = XSSPrintSafe($myrow);
88✔
514
                                }
32✔
515
                                $Ret = $myrow;
110✔
516
                        }
40✔
517
                }
40✔
518
                return $Ret;
132✔
519
        }
520
    function updateRole($rolearray)
521
    {
522
        /* This function accepts an array in the following format
523
          $rolearray[0] = $roleid
524
          $rolearray[1] = $role_name
525
          $rolearray[2] = $role_desc
526
        */
527
        $db = $this->db;
×
528
        $sql = "UPDATE base_roles SET role_name = '". $rolearray[1] ."', role_desc = '" . $rolearray[2] . "' ";
×
529
        $sql = $sql . "WHERE role_id = '" . $rolearray[0] . "'";
×
530
        $updated = $db->baseExecute($sql);
×
531
        return;
×
532
    }
533
    
534
    function deleteRole($role)
535
    {
536
        //deletes the role
537
        $db = $this->db;
×
538
        $sql = "DELETE FROM base_roles WHERE role_id = '" . $role . "';";
×
539
        $deleted = $db->baseExecute($sql);
×
540
        return;
×
541
    }
542
    
543
    function returnRoles()
544
    {
545
        /* returns an array of all Roles info
546
         * each array item is formatted as
547
         * array[] = role_id|role_name|role_desc
548
        */
549
        
550
        $db = $this->db;
×
551
        $sql = "SELECT role_id, role_name, role_desc ";
×
552
        $sql = $sql . "FROM base_roles ORDER BY role_id;";
×
553
        $result = $db->baseExecute($sql);
×
554
        
555
        $i = 0;
×
556
        while ( ($myrow = $result->baseFetchRow()) && ($i < $result->baseRecordCount()) )
×
557
        {
558
            $rolearray[$i] = $myrow[0] . "|" . $myrow[1] . "|" . $myrow[2];
×
559
            ++$i;
×
560
        }
561
        $result->baseFreeRows();
×
562
        return $rolearray;
×
563
    }
564
}
565

566
// Returns true if the role of current user is authorized.
567
// Redirect if valid header is given.
568
function AuthorizedRole ( $roleneeded = 1, $header = '' ){
569
        GLOBAL $BASE_urlpath, $Use_Auth_System, $et;
156✔
570
        $EMPfx = 'BASE Security Alert ' . __FUNCTION__ . ': ';
216✔
571
        $Ret = false;
216✔
572
        if ( $Use_Auth_System != 1 ){ // Auth system off, always pass.
216✔
573
                $Ret = true;
22✔
574
        }else{ // Check role and possibly redirect.
8✔
575
                $BUser = new BaseUser();
194✔
576
                $user = $BUser->returnUser(); // User
194✔
577
                $UAE = $BUser->isActive($user); // User Account Enabled.
194✔
578
                $URN = $BUser->hasRole($roleneeded); // User role needed.
194✔
579
                if ( $URN == 0 || $UAE == false ){ // Not Authorized
194✔
580
                        $msg = ' user access';
132✔
581
                        if ( $user == '' ){
132✔
582
                                $msg = "Unauthenticated$msg";
44✔
583
                        }else{
16✔
584
                                $msg = "Unauthorized$msg: $user";
88✔
585
                        }
586
                        error_log($EMPfx . $msg);
132✔
587
                        if ( $roleneeded >= 10000 ){ // Lock redirect :-)
132✔
588
                                error_log('Redirect Lock Engaged');
22✔
589
                                $header = 'base_denied';
22✔
590
                        }
8✔
591
                        if ( $header != '' ){
132✔
592
                                $ReqRE = "(base_(denied|main)|index)";
22✔
593
                                if ( preg_match("/^" . $ReqRE ."$/", $header) ){
22✔
594
                                        // Redirect to allowed locations only.
595
                                        error_log('Attempt Redirect');
22✔
596
                                        HTTP_header("Location: $BASE_urlpath/$header.php");
22✔
597
                                        error_log('Redirect failed');
92✔
598
                                }
8✔
599
                        }
8✔
600
                }else{
48✔
601
                        $Ret = true;
62✔
602
                }
603
        }
604
        if ( is_object($et) ){ // Need to TD this in Issue #11 branch.
216✔
605
                $et->Mark('Authorization Check.');
20✔
606
        }
6✔
607
        return $Ret;
216✔
608
}
609

610
// Returns true if the passed value is part of the running script name.
611
function AuthorizedPage ( $page = '' ){
612
        GLOBAL $BASE_urlpath;
158✔
613
        $Ret = false;
224✔
614
        $ReqRE = preg_quote("$BASE_urlpath/",'/')."$page\.php";
224✔
615
        if ( preg_match("/^" . $ReqRE ."$/", $_SERVER['SCRIPT_NAME']) ){
224✔
616
                $Ret = true;
22✔
617
        }
8✔
618
        return $Ret;
224✔
619
}
620

621
// Returns true if URI is set & matches URL path & running script name.
622
function AuthorizedURI (){
623
        GLOBAL $BASE_urlpath;
48✔
624
        $Ret = false;
66✔
625
        if (isset($_SERVER["REQUEST_URI"])){
66✔
626
                $URI = $_SERVER["REQUEST_URI"];
44✔
627
                $ReqRE = preg_quote($BASE_urlpath.$_SERVER['SCRIPT_NAME'],'/');
44✔
628
                if ( preg_match("/^" . $ReqRE ."/", $URI) ){
44✔
629
                        $Ret = true;
22✔
630
                }
8✔
631
        }
16✔
632
        return $Ret;
66✔
633
}
634

635
// Returns true if Client Host is allowed to connect.
636
function AuthorizedClient (){
637
        GLOBAL $AllowedClients;
96✔
638
        $Ret = true; // Fail Open for configs where this isn't set.
132✔
639
        if( LoadedString($AllowedClients) ){
132✔
640
                $IpTmp = $AllowedClients;
110✔
641
                $Ret = false; // Lock the gate.
110✔
642
                $IPF = 0;
110✔
643
                $IPL = 0;
110✔
644
                $IPC = 0;
110✔
645
                $IPV = 0;
110✔
646
                $Snm = netmask ($IpTmp);
110✔
647
                if ( $Snm > 0 ){
110✔
648
                        $MaskRE = '\/' . $Snm;
110✔
649
                        $IpTmp = preg_replace( '/'. $MaskRE .'$/', '', $IpTmp );
110✔
650
                        if( is_ip4 ($IpTmp) ){
110✔
651
                                if( $Snm > 32 ){ // Invalid IPv4 Netmask
66✔
652
                                        $Snm = 32;
22✔
653
                                }
8✔
654
                                $IPC = NMHC($Snm);
66✔
655
                        }elseif( is_ip6 ($IpTmp) ){
68✔
656
                                $IPC = NMHC($Snm, true);
44✔
657
                        }
16✔
658
                }
40✔
659
                $IPF = ipconvert($IpTmp);
110✔
660
                $IPL = $IPF;
110✔
661
                if( is_ip4 ($IpTmp) ){
110✔
662
                        $IPV = 4;
66✔
663
                        if( $Snm > 0 ){
66✔
664
                                $IPL = $IPL + $IPC;
66✔
665
                        }
24✔
666
                }elseif( is_ip6 ($IpTmp) ){
68✔
667
                        $IPV = 6;
44✔
668
                        if( $Snm > 0 && defined('GMP_VERSION') ){
44✔
669
                                $IPL = gmp_strval(gmp_add($IPF, $IPC));
44✔
670
                        }
16✔
671
                }
16✔
672
                if( $IPV != 0 && is_key('REMOTE_ADDR', $_SERVER) ){
110✔
673
                        $ipcli = $_SERVER['REMOTE_ADDR'];
110✔
674
                        $ipcT = ipconvert($ipcli);
110✔
675
                        if( $IPV == 4 && is_ip4 ($ipcli) ){
110✔
676
                                if( $ipcT >= $IPF && $ipcT <= $IPL ){
66✔
677
                                        $Ret = true;
58✔
678
                                }
16✔
679
                        }elseif( $IPV == 6 && is_ip6 ($ipcli) && defined('GMP_VERSION') ){
68✔
680
                                if(
681
                                        gmp_cmp($ipcT, $IPF) > -1 && gmp_cmp($ipcT, $IPL) < 1
44✔
682
                                ){
16✔
683
                                        $Ret = true;
22✔
684
                                }
8✔
685
                        }
16✔
686
                }
40✔
687
        }
40✔
688
        return $Ret;
132✔
689
}
690

691
?>
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc