scripts/handleLXCAppArmorProfiles.php

111 lines
2.8 KiB
PHP

<?php
function deny($code, $reason) {
switch($code) {
case 401:
$header = '401 Unauthorized';
header('WWW-Authenticate: Basic realm="handleLXCAppArmorProfiles"');
break;
case 403:
$header = '403 Forbidden';
break;
case 503:
$header = '503 Service Unavailable';
break;
}
header('HTTP/1.0 ' . $header);
print "$code $reason";
exit(1);
}
function cleanup() {
# Do intelligent cleanup!
foreach($_FILES as $fieldName => $key) {
if ('tmp_name' === $key) {
if (is_countable($_FILES[$fieldName][$key])) {
foreach($_FILES[$fieldName][$key] as $fileName) {
@unlink($fileName);
}
} else {
@unlink($_FILES[$fieldName][$key]);
}
}
}
}
# Check if SAPI is cli
if ('cli' === php_sapi_name()) {
if ('hash' === @$argv[1] && !empty($argv[2])) {
# We going to hash a password and return the result
# and write to file
$pw = password_hash($argv[2], PASSWORD_DEFAULT);
echo $pw;
file_put_contents('.htpasswd', "tar.lxc-apparmor-profiles-user:$pw");
} else {
print "Nothing to do here! Exiting...";
exit(0);
}
} else {
if (!file_exists('.htpasswd')) {
header('HTTP/1.0 503 Service Unavailable');
print '503 Service Unavailable';
exit(1);
}
$auth_creds = file_get_contents('.htpasswd');
$auth_creds = explode(':', $auth_creds);
if (!isset($_SERVER['PHP_AUTH_USER'])) {
deny(401, 'No authorize headers sent!');
} else {
$user = $_SERVER['PHP_AUTH_USER'];
$result = password_verify($_SERVER['PHP_AUTH_PW'], $auth_creds[1]);
if (true === $result && $auth_creds[0] === $user) {
if ('ProcessUpload' === $_SERVER['HTTP_X_APPARMOR_STATE']) {
# Process upload.
$uploadedFileTmp = $_FILES['apparmor-profiles']['tmp_name'];
# Check if multiple files where uploaded!
if (is_countable($_FILES['apparmor-profiles']['tmp_name'])) {
cleanup();
deny(403, 'Multiple Uploads not supported!');
}
# Check file mime type is accepted
$finfo = new finfo(FILEINFO_MIME);
$mime = $finfo->file($uploadedFileTmp);
if ('application/x-gzip; charset=binary' !== $mime) {
# Clean up tmp file
cleanup();
deny(403, 'Forbidden mime-type: ' . $mime);
}
# Check if the hash matches what we were given
$uploadedHash = hash_file('sha256', $uploadedFileTmp);
if ($_SERVER['HTTP_X_TAR_HASH'] !== $uploadedHash) {
cleanup();
deny(403, 'File hash doesn\'t match!');
}
$dest = dirname(__FILE__) . '/apparmor/' . $_FILES['apparmor-profiles']['name'];
$result = @move_uploaded_file($uploadedFileTmp, $dest);
if (false === $result) {
cleanup();
deny(503, 'Error processing upload');
} else {
file_put_contents("$dest.sha256", hash_file('sha256', $dest));
cleanup();
echo '200 OK';
}
}
} else {
cleanup();
deny(401, 'Unauthorized');
}
}
}