aboutsummaryrefslogtreecommitdiffstats
path: root/HTPasswdSync.module
blob: 61ad54d3353435f5f2603ca20727f95687ecb8f5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
<?php
// $Id$
/*
 * $Log$
 * Revision 1.1.2.3  2009/06/27 07:22:52  mfu
 * Fixed #503718 by m.fu : htpassword corruption when enabling/disabling user
 * Fixed #437904 by fasdalf@fasdalf.ru : group file not generated properly,
 *                                       now happen on after_update
 * Fixed #437844 by fasdalf@fasdalf.ru : error when deleting one user
 * Fixed #503726 by m.fu: group file no longer contain disabled users
 * Added #503720 by m.fu : option to overwrite htpasswd
 * Fixed #503724 by m.fu : validation of username, must be htpasswd compatible
 *
 * Revision 1.1.2.2  2009/03/26 22:15:29  mfu
 * Added #408798 by fasdalf@fasdalf.ru : request for windows support
 *   windows does not support crypt password hash
 *   added support for SHA-1 password hash which is supported by windows.
 * Fixed : group file not allways updated.
 *
 * Revision 1.1.2.1  2009/03/25 19:24:10  mfu
 * Fixed #409406 by fasdalf@fasdalf.ru : remove comma in htgroup file
 *
 * 
 */  
 

/* @file
 * Synchronize users password and htpasswd file
 * 
 * HTPasswd Sync module duplicates all users changes in the configured htpasswd
 * file. Password a hashed with the crypt function. The htgroup file contains 
 * roles as groups. 
 */     
 
 /**
  * return htpasswd file name
  *     
  * @return
  *   full filname of the htpasswd
  */
 function _htpasswdsync_passfilename() {
    return variable_get('htpasswdsync_htpasswd', "/etc/httpd/htpasswd");
 }
 
 /**
  * return htgroup file name
  *     
  * @return
  *   full filname of the htgroup file
  */
 function _htpasswdsync_grpfilename() {
    return variable_get('htpasswdsync_htgroup', "/etc/httpd/htgroup");
 }
 
 /**
  * return role to put in htgroup
  * 
  * return the roles selectionned in the admin page to put into
  * the htgroup file.
  *       
  * @return
  *   array of role id
  */
 function _htpasswdsync_roles() {
    return variable_get('htpasswdsync_roles', array());
 }


 /**
  * return array of available hashes
  * 
  * return an array of possible hashes
  *       
  * @return
  *   array
  */
 function _htpasswdsync_hashes() {
    return array ('crypt', 'SHA-1');
 }
  
 /**
  * return hash algorithm name
  * 
  * return the name of the hash algorithm to use for password
  * hashing  
  *       
  * @return
  *   string ('crypt', 'SHA-1')
  */
 function _htpasswdsync_hash() {
    return variable_get('htpasswdsync_hash', 0);
 }

 /**
  * return overwrite_htpasswd status
  * 
  * returns if the htpasswd file shall be overwritten by drupal of not
  * overwritting will erase all manual entered users.
  * manual make the htpasswd grow and contain renamed users. 
  * it will do the same for the htgroup     
  *       
  * @return
  *   array of role id
  */
 function _htpasswdsync_overwrite() {
    return variable_get('htpasswdsync_overwrite', true);
 }


 /**
  * crypt password
  * 
  * return the password hashed according to users preferences
  *       
  * @param $password
  *   the password, as a string,  to encrypt     
  * @return
  *   encrpyted password (actually hashed)
  */
 function _htpasswdsync_crypt($password) {
  $hashes = _htpasswdsync_hashes();
  switch ($hashes[_htpasswdsync_hash()]) {
    case 'crypt':
      return crypt($password, chr(rand(65, 122)) . chr(rand(65, 122)));
    break;
    case 'SHA-1':
      return '{SHA}' . base64_encode(sha1($password, TRUE));
    break;
  }
  return _htpasswdsync_hash();
}
 
/**
 * read an htfile
 *     
 * read an htfile, format is key: value, one key per row
 * 
 * @param &$arr
 *   array to read to
 * @param $file
 *   file to read
 * @return
 *   none 
 */

 function _htpasswdsync_read_htfile(&$arr, $file) {
   $f = fopen($file, "r");
   while ($l = fgets($f)) {
     list($u, $p) = split(":", rtrim($l), 2);
     if ($u != "") {
       $arr[$u] = $p;
     }
   }
   fclose($f);
 }
 
 /**
 * write an htfile
 *     
 * write an array to an htfile, format is key: value, one key per row
 * 
 * @param &$arr
 *   array to write
 * @param $file
 *   file to write to
 * @return
 *   none 
 */
 function _htpasswdsync_write_htfile(&$arr, $file) {
  $f = fopen($file, "w");
  foreach ($arr as $u => $p) {
    if ($u != "" && $p != "") {
      fputs($f, $u .":". $p ."\n");
    }
  }
  fclose($f);
 }
 
/* generate the htgroup content
 *
 * for each role configured (htpasswdsync_roles array), list users
 * and update the htgroup accordingly
 * 
 * @param
 * @return   
 */    
 function _htpasswdsync_updategroup() {
  
  $file = _htpasswdsync_grpfilename();
  $groups = array();

  // if we overwrite, then why botter reading the previous file
  if (! _htpasswdsync_overwrite()) {
    _htpasswdsync_read_htfile($groups, $file);
  }
  
  foreach (_htpasswdsync_roles() as $rid) {
    // get role name
    $res = db_fetch_object(db_query('SELECT name FROM {role} WHERE rid = %d', $rid));
    $name = $res->name;
    
    //empty group
    $groups[$name] = "";
    
    // add members to the group
    $res = db_query('SELECT name FROM {users} u, {users_roles} ur WHERE ur.rid = %d AND ur.uid = u.uid AND status = 1', $rid);
    while ($r = db_fetch_object($res)) {
      $groups[$name] .= " ". $r->name;
    }

  } _htpasswdsync_write_htfile($groups, $file);
 }

/* generate the htpasswd content from the database
 *
 * update the htpasswd file from the table htpasswdsync_passwd
 * 
 * @param
 * @return   
 */    
 function _htpasswdsync_updatepasswd() {
  
  $file = _htpasswdsync_passfilename();
  $passwords = array();
  
  // if we overwrite, then why botter reading the previous file
  if (! _htpasswdsync_overwrite()) {
    _htpasswdsync_read_htfile($passwords, $file);
  }
  //get all users  
  $res = db_query('SELECT username, passwd FROM {htpasswdsync_passwd}, {users} WHERE name=username and status = 1');
  while ($r = db_fetch_object($res)) {
    firep($r, "htpaswdsync_updatepasswd -- user/pass");
    if ($r->passwd == "****DELETED") {
      unset($passwords[$r->username]);
    }
    else {
      $passwords[$r->username] = $r->passwd; 
    }
  }
  _htpasswdsync_write_htfile($passwords, $file);
 }

 
/* update htpassword table with the new password of the user
 *
 * @param $edit
 *   fields that have been edited  
 * @param $account
 *   account of the user to update 
 * @return   
 */    
 function _htpasswdsync_update($edit, $account) {

  if (isset($edit["pass"])) {
   // update with the $account information received
   // password crypted with the standard crypt (not MD5) function
   $user = $account->name;
    $pass = _htpasswdsync_crypt($edit['pass']);
    $passwds[$user] = $pass;
  
    //update table
    db_query("DELETE FROM {htpasswdsync_passwd} WHERE username = '%s'", $user);
    db_query("INSERT INTO {htpasswdsync_passwd} (username, passwd) VALUES('%s', '%s')", $user, $pass);
    _htpasswdsync_updatepasswd();
    _htpasswdsync_updategroup();
  }
}

/* update htpassword file with the new password of the user
 *
 * @param $account
 *   account of the user to update 
 * @return   
 */    
function _htpasswdsync_commit_to_htpasswd() {
  // update passwd file with new status  
  _htpasswdsync_updatepasswd();
  _htpasswdsync_updategroup();
}

/* remove the one user for the htpassword file
 *
 * @param $username
 *   username of account to delete 
 * @return   
 */    
function _htpasswdsync_delete_user($username) {
  firep ($username, "_htpasswdsync_delete_user(username)");
  db_query("DELETE FROM {htpasswdsync_passwd} WHERE username = '%s'", $username);
  db_query("INSERT INTO {htpasswdsync_passwd} (username, passwd) VALUES('%s', '%s')", $username, "****DELETED");
}

 
/* remove the user for the htpassword file
 *
 * @param $account
 *   array of account to delete 
 * @return   
 */    
function _htpasswdsync_delete($account) {
  firep ($account, "_htpasswdsync_delete(account)");

  if (isset($account['accounts'])) {
    foreach ($account['accounts'] as $a) {
      $r = db_query("SELECT name FROM {users} WHERE uid = %d", $a);
      $user = db_fetch_object($r);
      _htpasswdsync_delete_user($user->name);
    }
  }
  elseif (isset($account['_account'])) {
     _htpasswdsync_delete_user($user->name);
  }
  _htpasswdsync_updatepasswd();
  _htpasswdsync_updategroup();
 }

 /**
* Validate user form input
*   here we refuse username with characters that are not supported
*   in htpasswd files
* @param $edit field submited
* @return none
*/
function _htpasswdsync_validate($edit) {
  if (isset($edit['name'])) {
    if (ereg('[ :\t]', $edit['name'])) {
      form_set_error('htpasswdsync', 
          t('The username contains an illegal character, like &lt;space&gt;, :'));
    }
  }
} // htpasswdsync_validate

 /**
* Display help and module information
* @param path which path of the site we're displaying help
* @param arg array that holds the current path as would be returned from arg() function
* @return help text for the path
*/
function htpasswdsync_help($path, $arg) {
  $output = '';  //declare your output variable
  switch ($path) {
    case "admin/help#htpasswdsync":
      $output = '<p>'.  t("synchronize password with a htpasswd file") .'</p>';
      break;
  }
  return $output;
} // function htpasswdsync_help

/**
* Valid permissions for this module
* @return array An array of valid permissions for the htpasswdsync module
*/
function htpasswdsync_perm() {
  return array('administer htpasswdsync');
} // function htpasswdsync_perm()

/*
 * Implementation of hook_user()
 */  
function htpasswdsync_user($op, &$edit, &$account, $category = NULL) {
  firep($op, "htpaswdsync_user hook -- op");
  firep($edit, "htpaswdsync_user hook -- edit");
  firep($account, "htpaswdsync_user hook -- account");
  #firep($_htpasswdsync_debugfile);
  ## drupal_set_message('<pre>' . $op . '<br>' . print_r($edit, TRUE) . '<br>' . print_r($account, TRUE) . '</pre>');
  ##drupal_set_message('<b>' . $op . '<b>');
  ##db_query("INSERT INTO log (a) VALUES('%s')", $op);

  switch ($op) {
    case "delete": 
      _htpasswdsync_delete($edit);
    break;
    case "insert": 
      _htpasswdsync_update($edit, $account);
    break;
    case "update": 
      _htpasswdsync_update($edit, $account);
    break;
    case "after_update": 
      _htpasswdsync_commit_to_htpasswd();
    break;
    case "validate": 
      _htpasswdsync_validate($edit);
    break;
  }
} // function htpasswdsync_user()


function htpasswdsync_admin() {

  $form['htpasswdsync_htpasswd'] = array(
    '#type' => 'textfield',
    '#title' => t('htpasswd file'),
    '#default_value' => _htpasswdsync_passfilename(),
    '#size' => 100,
    '#maxlength' => 200,
    '#description' => t("Where is stored the !file file we want to synchronize with.",
          array('!file' => 'htpasswd')),
    '#required' => TRUE,
  );
  $form['htpasswdsync_htgroup'] = array(
    '#type' => 'textfield',
    '#title' => t('htgroup file'),
    '#default_value' => _htpasswdsync_grpfilename(),
    '#size' => 100,
    '#maxlength' => 200,
    '#description' => t("Where is stored the !file file we want to synchronize with.",
          array('!file' => 'htgroup')),
    '#required' => TRUE,
  );
  $form['htpasswdsync_hash'] = array(
    '#type' => 'radios',
    '#title' => t('password hashing algorythm'),
    '#description' => t("How shall the password be hashed (crypt for unix, SHA1 for all)"),
    '#options' => _htpasswdsync_hashes(),    
    '#default_value' => _htpasswdsync_hash(),
  );
   $form['htpasswdsync_roles'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Roles to be exported in htgroup'),
    '#default_value' => _htpasswdsync_roles(),
    '#options' => user_roles(TRUE),
  );
  $form['htpasswdsync_overwrite'] = array(
    '#type' => 'checkbox',
    '#title' => t('is htpasswd file only managed by this module'),
    '#default_value' => _htpasswdsync_overwrite(),
  );
 
  return system_settings_form($form);
}


/* Test if a file exist and is writable
 *
 * @param $filename
 *   name of the file
 * @return
 *   return false on success, otherwise an error message
 */
function _htpasswdsync_check_file($file) {
  $f = @fopen($file, "r");
  if (!$f) {
    return t("File '!file' does not exists, you should create it.",
      array('!file' => $file));
  }
  else {
    fclose($f);
    $f = @fopen($file, "a");
    if (!$f) {
      return t("cannot write to file '!file'.", array('!file' => $file));
    }
    else {
      fclose($f);
    }
  } 
  return FALSE;
}

function htpasswdsync_admin_validate($form, &$form_state) {

  $file = $form_state['values']['htpasswdsync_htpasswd'];
  if ($msg = _htpasswdsync_check_file($file)) {
    form_set_error('htpasswdsync_htpasswd', $msg);
  }

  $file = $form_state['values']['htpasswdsync_htgroup'];
  if ($msg = _htpasswdsync_check_file($file)) {
    form_set_error('htpasswdsync_htpasswd', $msg);
  }
}

function htpasswdsync_menu() {

  $items = array();

  $items['admin/user/htpasswdsync'] = array(
    'title' => 'HTPassword Sync',
    'description' => 'Preferences for the HTPasswd Sync module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('htpasswdsync_admin'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
   );

  return $items;
}

function htpasswdsync_requirements($phase) {

  $requirements = array();

  // if not runtime query, exit
  if ($phase != 'runtime') {
    return $requirements;
  }
  
  $htpasswd_status_msg = _htpasswdsync_check_file(_htpasswdsync_passfilename());
  $htpasswd_status_val = REQUIREMENT_ERROR;
  if (!$htpasswd_status_msg) {
    $htpasswd_status_msg = t('!file file is available', array('!file' => 'htpasswd'));
    $htpasswd_status_val = REQUIREMENT_OK;
  }

  $htgroup_status_msg = _htpasswdsync_check_file(_htpasswdsync_grpfilename());
  $htgroup_status_val = REQUIREMENT_ERROR;
  if (!$htgroup_status_msg) {
    $htgroup_status_msg = t('!file file is available', array('!file' => 'htgroup'));
    $htgroup_status_val = REQUIREMENT_OK;
  }
  
  $status = $htpasswd_status_val > $htgroup_status_val ?
    $htpasswd_status_val : $htgroup_status_val;

  $requirements['htpasswdsync_status'] = array(
    'title'       => t('HTPasswd Sync Status'),
    'value'       => $htpasswd_status_msg ."<br>". 
                     $htgroup_status_msg ."<br>".
                     t('last update !time ago.', array(
                        '!time' => format_interval(time()-variable_get('htpasswdsync_cron_time', 0)))),
    'severity'    => $status,
    );
  if ($status != REQUIREMENT_OK) {
    $requirements['htpasswdsync_status']['description'] =
      t('Cannot access files, please <a href="!url">check configuration</a>.',
         array('!url' => url('admin/user/htpasswdsync')));
  }

  return $requirements;
}

function htpasswdsync_cron() {
  $time = variable_get('htpasswdsync_cron_time', 0);
  _htpasswdsync_updatepasswd();
  _htpasswdsync_updategroup();
  variable_set('htpasswdsync_cron_time', time());
}

© 2014-2024 Faster IT GmbH | imprint | privacy policy