Skip to content

Instantly share code, notes, and snippets.

@TimWolla
Last active March 8, 2022 18:04
Show Gist options
  • Save TimWolla/5615337 to your computer and use it in GitHub Desktop.
Save TimWolla/5615337 to your computer and use it in GitHub Desktop.
Read htaccess auth in PHP
<?php if ($user != '') { ?>
Eingeloggt als <?php echo $user; ?>. <a href="https://logout:false@example.com/logout.php">Abmelden</a>
<?php } else { ?>
Nicht eingeloggt. <a href="login.php">Einloggen</a>
<?php } ?>
<?php if ($user != '') { ?>
<a href="secret/">Secret folder</a>
<?php } ?>
auth.backend = "htpasswd"
auth.backend.htpasswd.userfile = "/path/to/passwd.inc"
auth.require = (
"/secret" => (
"method" => "basic",
"realm" => "MY REALM",
"require" => "valid-user"
),
"/login.php" => (
"method" => "basic",
"realm" => "MY REALM",
"require" => "valid-user"
)
)
<?php
header('Location: /');
<?php
require('pw.php');
if ($user === '') {
header('Location: /');
exit;
}
header('WWW-Authenticate: Basic realm="MY REALM"');
header('HTTP/1.0 401 Unauthorized');
echo '<meta http-equiv="refresh" content="0; URL=/">';
<?php
function pw($plainpasswd, $hash) {
preg_match('~^\$apr1\$(.{8})\$~', $hash, $matches);
$salt = $matches[1];
$len = strlen($plainpasswd);
$text = $plainpasswd.'$apr1$'.$salt;
$bin = pack("H32", md5($plainpasswd.$salt.$plainpasswd));
for($i = $len; $i > 0; $i -= 16) { $text .= substr($bin, 0, min(16, $i)); }
for($i = $len; $i > 0; $i >>= 1) { $text .= ($i & 1) ? chr(0) : $plainpasswd{0}; }
$bin = pack("H32", md5($text));
for($i = 0; $i < 1000; $i++) {
$new = ($i & 1) ? $plainpasswd : $bin;
if ($i % 3) $new .= $salt;
if ($i % 7) $new .= $plainpasswd;
$new .= ($i & 1) ? $bin : $plainpasswd;
$bin = pack("H32", md5($new));
}
$tmp = '';
for ($i = 0; $i < 5; $i++) {
$k = $i + 6;
$j = $i + 12;
if ($j == 16) $j = 5;
$tmp = $bin[$i].$bin[$k].$bin[$j].$tmp;
}
$tmp = chr(0).chr(0).$bin[11].$tmp;
$tmp = strtr(strrev(substr(base64_encode($tmp), 2)),
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
return "$"."apr1"."$".$salt."$".$tmp;
}
$user = '';
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
$accounts = file('passwd.inc');
foreach ($accounts as $account) {
list($username, $password) = explode(':', trim($account), 2);
if ($username != $_SERVER['PHP_AUTH_USER']) continue;
if ($password == pw($_SERVER['PHP_AUTH_PW'], $password)) {
$user = $username;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment