[pmwiki-users] making brute force attacks more difficult #2

ThomasP pmwikidev at sigproc.de
Wed Aug 22 00:27:22 CDT 2007


On Wed, August 22, 2007 06:50, ThomasP wrote:
> ...
>
> I would propose a rule like "not more than 100 login attempts per any 30
> days period from one IP", with both the limit and the duration adjustable.
> (Even though the code for this would be slower I guess it is worth it.)
>
> Besides, I think to prevent distributed attacks effectively, it will also
> be useful to raise (additionally) a similar fence on a "per-username"
> basis, i.e. "not more than ... for one login username".
>

Code sketch:

function registerLoginAttempt($username, $ip) {
  // Returns true if login attempt might proceed, false if limit is reached

  $LimitPerUser = 100;
  $LimitPerIp   = 100;
  $DurPerUser   = 30*86400; // in secs
  $DurPerIp     = 30*86400;

  if (!file_exists('login_attempts')) {
    mkdirp('login_attempts');
    copy('local/.htaccess', 'login_attempts/.htaccess'); //etc.
  }
  $mayPass = true;
  $now = time();
  if (!registerLoginAttempt_wrk('login_attempts/_'.sha1($username), $now,
$LimitPerUser, $DurPerUser))
    $mayPass = false;
  if (!registerLoginAttempt_wrk('login_attempts/_'.sha1($ip), $now,
$LimitPerIp, $DurPerIp))
    $mayPass = false;
  return $mayPass;
}

function registerLoginAttempts_wrk($filename, $now, $limit, $duration) {
  // Returns true if attempt yet accepted, false if limit is reached.
  // Writes time stamp of the current login attempt to file.
  $line = trim(file_get_contents($filename));
  $arr = explode(" ", $line);
  $i = 0;
  $buf = '';
  $mayPass = true;
  foreach($arr as $stamp) {
    $buf .= "$stamp ";
    if ($i >= $limit) { $mayPass = false; break; }
    if ($stamp < $now - $duration) break;
  }
  file_put_contents($filename, "$now $buf");
    // This retains the stamps of the last login attempts within the
specified time frame,
    // but not more than $limit stamp. (Stamps are ordered in descending
order.)
  return $mayPass;
}

if (!function_exists(file_put_contents)) {
  function file_put_contents() { ... }
}





More information about the pmwiki-users mailing list