remote.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. <?php
  2. declare(strict_types=1);
  3. // Extra backup destinations besides the manage server: s3, sftp and custom.
  4. //
  5. // There is no "managed" target type: uploading to the manage server is built
  6. // in (manageBackupUpload) and configured through MANAGE_SERVER_URL /
  7. // MANAGE_INSTANCE / MANAGE_TOKEN instead of a target entry.
  8. function manageRemoteTargets(): array
  9. {
  10. return is_array(MANAGE_BACKUP_REMOTE_TARGETS) ? MANAGE_BACKUP_REMOTE_TARGETS : [];
  11. }
  12. function manageRemoteTargetLabel(array $target, int $index): string
  13. {
  14. $name = trim((string) ($target["name"] ?? ""));
  15. if ($name !== "") {
  16. return $name;
  17. }
  18. $type = trim((string) ($target["type"] ?? "target"));
  19. return $type . "-" . ($index + 1);
  20. }
  21. // Whitelist of non-secret keys, so a failure can be logged with useful context
  22. // without ever writing an access key or password to disk.
  23. function manageRemoteSafeContext(array $target): array
  24. {
  25. $safe = [];
  26. $allowedKeys = [
  27. "name", "type", "url", "bucket", "region", "prefix", "endpoint",
  28. "host", "port", "username", "path", "file", "callback", "timeout",
  29. ];
  30. foreach ($allowedKeys as $key) {
  31. if (array_key_exists($key, $target)) {
  32. $safe[$key] = is_scalar($target[$key]) ? (string) $target[$key] : gettype($target[$key]);
  33. }
  34. }
  35. return $safe;
  36. }
  37. function manageRemoteResponseExcerpt($response): string
  38. {
  39. if (!is_string($response) || $response === "") {
  40. return "";
  41. }
  42. $response = preg_replace('/\s+/', " ", trim($response));
  43. return is_string($response) ? substr($response, 0, 500) : "";
  44. }
  45. function manageRemoteLastPhpError(): string
  46. {
  47. $error = error_get_last();
  48. if (!is_array($error)) {
  49. return "";
  50. }
  51. return substr(trim((string) ($error["message"] ?? "")), 0, 500);
  52. }
  53. // Reports which target types this installation can actually use, so the GUI can
  54. // warn about a configured target that will always fail.
  55. function manageRemoteCapabilities(): array
  56. {
  57. $types = [];
  58. foreach (manageRemoteTargets() as $target) {
  59. if (is_array($target)) {
  60. $type = trim((string) ($target["type"] ?? ""));
  61. if ($type !== "") {
  62. $types[$type] = true;
  63. }
  64. }
  65. }
  66. return [
  67. "s3" => [
  68. "configured" => !empty($types["s3"]),
  69. "available" => function_exists("hash_hmac"),
  70. ],
  71. "sftp" => [
  72. "configured" => !empty($types["sftp"]),
  73. "available" => function_exists("ssh2_connect") && function_exists("ssh2_sftp"),
  74. ],
  75. "custom" => [
  76. "configured" => !empty($types["custom"]),
  77. "available" => true,
  78. ],
  79. ];
  80. }
  81. function manageRemoteUploadToS3(string $archivePath, array $metadata, array $target): array
  82. {
  83. $bucket = trim((string) ($target["bucket"] ?? ""));
  84. $region = trim((string) ($target["region"] ?? ""));
  85. $accessKey = trim((string) ($target["access_key"] ?? ""));
  86. $secretKey = (string) ($target["secret_key"] ?? "");
  87. $prefix = trim((string) ($target["prefix"] ?? ""), "/");
  88. $endpoint = rtrim(trim((string) ($target["endpoint"] ?? "")), "/");
  89. if ($bucket === "" || $region === "" || $accessKey === "" || $secretKey === "") {
  90. throw new RuntimeException("S3-Ziel ist unvollständig konfiguriert.");
  91. }
  92. $filename = basename($archivePath);
  93. $key = ($prefix !== "" ? $prefix . "/" : "") . $filename;
  94. $host = $endpoint !== ""
  95. ? parse_url($endpoint, PHP_URL_HOST)
  96. : $bucket . ".s3." . $region . ".amazonaws.com";
  97. if (!is_string($host) || $host === "") {
  98. throw new RuntimeException("S3-Endpunkt ist ungültig.");
  99. }
  100. $url = $endpoint !== ""
  101. ? $endpoint . "/" . rawurlencode($bucket) . "/" . str_replace("%2F", "/", rawurlencode($key))
  102. : "https://" . $host . "/" . str_replace("%2F", "/", rawurlencode($key));
  103. // The payload must be hashed as a whole for SigV4, so a backup larger than
  104. // memory_limit cannot use this target.
  105. $payload = file_get_contents($archivePath);
  106. if ($payload === false) {
  107. throw new RuntimeException("Backup-ZIP konnte für S3 nicht gelesen werden.");
  108. }
  109. $now = gmdate("Ymd\THis\Z");
  110. $date = substr($now, 0, 8);
  111. $payloadHash = hash("sha256", $payload);
  112. $canonicalUri = parse_url($url, PHP_URL_PATH);
  113. $canonicalUri = is_string($canonicalUri) && $canonicalUri !== "" ? $canonicalUri : "/";
  114. $signedHeaders = "content-type;host;x-amz-content-sha256;x-amz-date";
  115. $canonicalHeaders =
  116. "content-type:application/zip\n" .
  117. "host:" . $host . "\n" .
  118. "x-amz-content-sha256:" . $payloadHash . "\n" .
  119. "x-amz-date:" . $now . "\n";
  120. $canonicalRequest =
  121. "PUT\n" . $canonicalUri . "\n\n" . $canonicalHeaders . "\n" . $signedHeaders . "\n" . $payloadHash;
  122. $scope = $date . "/" . $region . "/s3/aws4_request";
  123. $stringToSign =
  124. "AWS4-HMAC-SHA256\n" . $now . "\n" . $scope . "\n" . hash("sha256", $canonicalRequest);
  125. $kDate = hash_hmac("sha256", $date, "AWS4" . $secretKey, true);
  126. $kRegion = hash_hmac("sha256", $region, $kDate, true);
  127. $kService = hash_hmac("sha256", "s3", $kRegion, true);
  128. $kSigning = hash_hmac("sha256", "aws4_request", $kService, true);
  129. $signature = hash_hmac("sha256", $stringToSign, $kSigning);
  130. $authorization =
  131. "AWS4-HMAC-SHA256 Credential=" . $accessKey . "/" . $scope .
  132. ", SignedHeaders=" . $signedHeaders . ", Signature=" . $signature;
  133. $context = stream_context_create([
  134. "http" => [
  135. "method" => "PUT",
  136. "timeout" => (int) ($target["timeout"] ?? 120),
  137. "ignore_errors" => true,
  138. "follow_location" => 0,
  139. "header" =>
  140. "Content-Type: application/zip\r\n" .
  141. "Content-Length: " . strlen($payload) . "\r\n" .
  142. "Host: " . $host . "\r\n" .
  143. "X-Amz-Date: " . $now . "\r\n" .
  144. "X-Amz-Content-Sha256: " . $payloadHash . "\r\n" .
  145. "Authorization: " . $authorization . "\r\n" .
  146. "User-Agent: " . manageClientUserAgent() . "\r\n",
  147. "content" => $payload,
  148. ],
  149. ]);
  150. $response = @file_get_contents($url, false, $context);
  151. $phpError = $response === false ? manageRemoteLastPhpError() : "";
  152. $headers = manageClientResponseHeaders($http_response_header ?? null);
  153. $status = manageClientStatusFromHeaders($headers);
  154. if ($response === false || $status < 200 || $status >= 300) {
  155. throw new ManageRemoteUploadException(
  156. "S3-Upload fehlgeschlagen" . ($status > 0 ? " (HTTP " . $status . ")" : "") . ".",
  157. [
  158. "http_status" => $status,
  159. "response_excerpt" => manageRemoteResponseExcerpt($response),
  160. "php_error" => $phpError,
  161. "bucket" => $bucket,
  162. "region" => $region,
  163. "key" => $key,
  164. "endpoint" => $endpoint,
  165. ],
  166. );
  167. }
  168. return ["remote_path" => "s3://" . $bucket . "/" . $key];
  169. }
  170. function manageRemoteUploadToSftp(string $archivePath, array $metadata, array $target): array
  171. {
  172. if (!function_exists("ssh2_connect") || !function_exists("ssh2_sftp")) {
  173. throw new RuntimeException("Die PHP-SSH2-Erweiterung ist nicht verfügbar.");
  174. }
  175. $host = trim((string) ($target["host"] ?? ""));
  176. $username = trim((string) ($target["username"] ?? ""));
  177. $password = (string) ($target["password"] ?? "");
  178. $remoteDir = rtrim((string) ($target["path"] ?? ""), "/");
  179. $port = (int) ($target["port"] ?? 22);
  180. if ($host === "" || $username === "" || $remoteDir === "") {
  181. throw new RuntimeException("SFTP-Ziel ist unvollständig konfiguriert.");
  182. }
  183. $connection = @ssh2_connect($host, $port > 0 ? $port : 22);
  184. if ($connection === false) {
  185. throw new RuntimeException("SFTP-Verbindung konnte nicht hergestellt werden.");
  186. }
  187. $authenticated = false;
  188. $privateKey = trim((string) ($target["private_key"] ?? ""));
  189. $publicKey = trim((string) ($target["public_key"] ?? ""));
  190. if ($privateKey !== "" && $publicKey !== "" && function_exists("ssh2_auth_pubkey_file")) {
  191. $authenticated = @ssh2_auth_pubkey_file(
  192. $connection,
  193. $username,
  194. $publicKey,
  195. $privateKey,
  196. $password !== "" ? $password : null,
  197. );
  198. } elseif (function_exists("ssh2_auth_password")) {
  199. $authenticated = @ssh2_auth_password($connection, $username, $password);
  200. }
  201. if (!$authenticated) {
  202. throw new RuntimeException("SFTP-Anmeldung fehlgeschlagen.");
  203. }
  204. $sftp = @ssh2_sftp($connection);
  205. if ($sftp === false) {
  206. throw new RuntimeException("SFTP-Subsystem konnte nicht gestartet werden.");
  207. }
  208. $remotePath = $remoteDir . "/" . basename($archivePath);
  209. $targetStream = @fopen("ssh2.sftp://" . intval($sftp) . $remotePath, "wb");
  210. if ($targetStream === false) {
  211. throw new RuntimeException("SFTP-Zieldatei konnte nicht geöffnet werden. Existiert das Verzeichnis?");
  212. }
  213. $source = fopen($archivePath, "rb");
  214. if ($source === false) {
  215. fclose($targetStream);
  216. throw new RuntimeException("Backup-ZIP konnte für SFTP nicht gelesen werden.");
  217. }
  218. $copied = stream_copy_to_stream($source, $targetStream);
  219. fclose($source);
  220. fclose($targetStream);
  221. if ($copied === false) {
  222. throw new RuntimeException("SFTP-Upload fehlgeschlagen.");
  223. }
  224. return ["remote_path" => "sftp://" . $host . $remotePath];
  225. }
  226. function manageRemoteUploadToCustom(string $archivePath, array $metadata, array $target): array
  227. {
  228. $file = trim((string) ($target["file"] ?? ""));
  229. $callback = $target["callback"] ?? null;
  230. if ($file !== "") {
  231. if (!is_file($file)) {
  232. throw new RuntimeException("Custom-Uploader-Datei wurde nicht gefunden: " . $file);
  233. }
  234. require_once $file;
  235. }
  236. if (!is_callable($callback)) {
  237. throw new RuntimeException("Custom-Uploader ist nicht aufrufbar.");
  238. }
  239. $result = call_user_func($callback, $archivePath, $metadata, $target);
  240. if ($result === true) {
  241. return [];
  242. }
  243. if (is_array($result) && ($result["success"] ?? true) !== false) {
  244. return $result;
  245. }
  246. if (is_array($result)) {
  247. throw new RuntimeException(trim((string) ($result["error"] ?? "Custom-Uploader meldet einen Fehler.")));
  248. }
  249. throw new RuntimeException("Custom-Uploader meldet einen Fehler.");
  250. }
  251. /**
  252. * Runs every configured extra target. Each is attempted independently and a
  253. * failure never invalidates the local backup: the error is recorded in the
  254. * backup index and logged.
  255. */
  256. function manageRemoteUploadAll(string $archivePath, array $metadata): array
  257. {
  258. $results = [];
  259. foreach (manageRemoteTargets() as $index => $target) {
  260. if (!is_array($target)) {
  261. continue;
  262. }
  263. $type = trim((string) ($target["type"] ?? ""));
  264. $label = manageRemoteTargetLabel($target, (int) $index);
  265. $startedAt = date(DATE_ATOM);
  266. try {
  267. if ($type === "s3") {
  268. $extra = manageRemoteUploadToS3($archivePath, $metadata, $target);
  269. } elseif ($type === "sftp") {
  270. $extra = manageRemoteUploadToSftp($archivePath, $metadata, $target);
  271. } elseif ($type === "custom") {
  272. $extra = manageRemoteUploadToCustom($archivePath, $metadata, $target);
  273. } else {
  274. throw new RuntimeException("Unbekannter Backup-Zieltyp: " . ($type !== "" ? $type : "(leer)"));
  275. }
  276. $results[] = array_merge([
  277. "target" => $label,
  278. "type" => $type,
  279. "success" => true,
  280. "started_at" => $startedAt,
  281. "uploaded_at" => date(DATE_ATOM),
  282. ], $extra);
  283. manageClientLog("INFO", "Remote upload succeeded", [
  284. "target" => $label,
  285. "type" => $type,
  286. "filename" => $metadata["filename"] ?? basename($archivePath),
  287. ]);
  288. } catch (Throwable $exception) {
  289. $debugContext = $exception instanceof ManageRemoteUploadException
  290. ? $exception->getDebugContext()
  291. : [];
  292. $result = [
  293. "target" => $label,
  294. "type" => $type !== "" ? $type : "unknown",
  295. "success" => false,
  296. "started_at" => $startedAt,
  297. "error" => $exception->getMessage(),
  298. ];
  299. if ($debugContext !== []) {
  300. $result["debug"] = $debugContext;
  301. }
  302. $results[] = $result;
  303. manageClientLog("ERROR", "Remote upload failed", [
  304. "target" => $label,
  305. "type" => $type !== "" ? $type : "unknown",
  306. "target_config" => manageRemoteSafeContext($target),
  307. "filename" => $metadata["filename"] ?? basename($archivePath),
  308. "error" => $exception->getMessage(),
  309. "debug" => $debugContext,
  310. ]);
  311. }
  312. }
  313. return $results;
  314. }