date('c'), "files" => [] ]; foreach ($root as $file) { if ($file === "backup.poniesbackup" || $file === "backup.ponieskey" || $file === "encrypted" || str_ends_with($file, ".poniesbackup")) continue; if (is_dir("data/$file")) { foreach (array_filter(scandir("data/$file"), function ($i) { return !str_starts_with($i, "."); }) as $dirfile) { if ($dirfile === "backup.poniesbackup" || $dirfile === "backup.ponieskey" || $dirfile === "encrypted" || str_ends_with($dirfile, ".poniesbackup")) continue; $files[] = [ "dir" => $file, "file" => $dirfile ]; } } else { $files[] = [ "dir" => "", "file" => $file ]; } } foreach ($files as $file) { $file["mime"] = mime_content_type("data/$file[dir]/$file[file]"); $file["checksum"] = [ sha1_file("data/$file[dir]/$file[file]"), md5_file("data/$file[dir]/$file[file]") ]; $file["content"] = base64_encode(file_get_contents("data/$file[dir]/$file[file]")); $data["files"][] = $file; } function pkcs7_pad($data, $size) { $length = $size - strlen($data) % $size; return $data . str_repeat(chr($length), $length); } if (!file_exists("./data/backup.ponieskey")) { $key = openssl_random_pseudo_bytes(512); $iv = openssl_random_pseudo_bytes(16); file_put_contents("./data/backup.ponieskey", base64_encode(json_encode([ "iv" => bin2hex($iv), "key" => bin2hex($key) ]))); } else { $key_raw = json_decode(base64_decode(file_get_contents("./data/backup.ponieskey")), true); $key = hex2bin($key_raw["key"]); $iv = hex2bin($key_raw["iv"]); } $payload = json_encode($data); $encrypted = openssl_encrypt(pkcs7_pad($payload, 16), 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv); file_put_contents("./data/backup.poniesbackup", $encrypted); @mkdir("./data/encrypted"); $id = str_replace(":", "-", date('c')); copy("./data/backup.poniesbackup", "./data/encrypted/" . $id . ".poniesbackup"); exec("scp ./data/encrypted/" . $id . ".poniesbackup fedora@bridlewood.equestria.dev:/opt/ponies"); exec('ssh fedora@bridlewood.equestria.dev bash -c "cd /opt/ponies; ls -tp | grep -v \'/$\' | tail -n +20 | xargs -I {} rm -- {}"'); exec("scp ./data/encrypted/" . $id . ".poniesbackup root@canterlot.equestria.dev:/opt/ponies"); exec('ssh root@canterlot.equestria.dev bash -c "cd /opt/ponies; ls -tp | grep -v \'/$\' | tail -n +20 | xargs -I {} rm -- {}"'); copy("./data/encrypted/" . $id . ".poniesbackup", "/opt/ponies/" . $id . ".poniesbackup"); exec('bash -c "cd /opt/ponies; ls -tp | grep -v \'/$\' | tail -n +20 | xargs -I {} rm -- {}"'); unlink("./data/encrypted/" . $id . ".poniesbackup");