Diff -- /var/www/vhosts/3dshawn.com/site1/restore.cgi

O Operator
Diff

/var/www/vhosts/3dshawn.com/site1/restore.cgi

modified on local at 2026-07-12 00:48:53

Added
+20
lines
Removed
-0
lines
Context
442
unchanged
Blobs
from 5edc99e61471
to 2f8b971be093
Restore this content →
Unified diff
Naive LCS-based line diff. Additions in emerald, deletions in rose. Both sides decompressed live from BLOB_STORE.
11#!/usr/bin/perl
22#======================================================================
33# DriftSense -- /restore.cgi
44#
55# Restore a captured file to its original path. Two flavors:
66# Local (server.kind = local) -> write blob to target path directly
77# Agent (server.kind = ssh_agent) -> pipe blob content over SSH to target
88#
99# Safety:
1010# - GET /restore.cgi?id=N -> preview page (dry-run details)
1111# - POST /restore.cgi id=N confirm=1 -> perform the restore
1212#
1313# * Path must be inside a configured FILE_MONITOR_SETTINGS.scan_path
1414# for that server (prevents restoring blob to /etc/passwd from a
1515# tampered FILE_CHANGES row).
1616# * Current file content is backed up to
1717# $target.drift_restore_backup_$UNIX_TIMESTAMP before overwrite.
1818# * Every attempt (success, failure, dry_run) is logged to RESTORE_LOG.
1919#======================================================================
2020use strict;
2121use warnings;
2222use CGI ();
2323use IPC::Open3;
2424use Symbol 'gensym';
2525use Fcntl ();
2626use POSIX ();
2727use Compress::Zlib qw(uncompress);
2828use Digest::SHA qw(sha256_hex);
2929use MODS::Config;
3030use MODS::DBConnect;
3131use MODS::Template;
3232use MODS::PageWrapper;
3333use MODS::Crypto;
3434use MODS::Diff;
3535
3636my $cgi = CGI->new;
3737my $db = MODS::DBConnect->new;
3838my $tpl = MODS::Template->new;
3939$|=1;
4040
4141my $dbh = $db->db_connect or die "DriftSense: DB connect failed\n";
4242
4343my $method = $ENV{REQUEST_METHOD} || 'GET';
4444my $id = int($cgi->param('id') || 0);
4545
4646# ---- Load the source change row -------------------------------------
4747my $row = _load_change_row($dbh, $id);
4848unless ($row && $row->{id}) {
4949 _render_error("Change #$id not found");
5050}
5151
5252# ---- Path safety: target file must be inside a monitored scan_path --
5353my $monitor = _load_monitor($dbh, $row->{file_monitor_list_id});
5454my $path_ok = 0;
5555if ($monitor && $monitor->{scan_path}) {
5656 my $sp = $monitor->{scan_path};
5757 $sp =~ s!/+$!!;
5858 $path_ok = 1 if index($row->{file_name}, "$sp/") == 0 || $row->{file_name} eq $sp;
5959}
6060unless ($path_ok) {
6161 _render_error("Target path <code>$row->{file_name}</code> is outside its monitor's configured scan_path; refusing to restore.");
6262}
6363
6464# ---- If POST, perform the restore ----------------------------------
6565if ($method eq 'POST' && $cgi->param('confirm')) {
6666 my $result = _do_restore($dbh, $row, $monitor);
6767 _log_restore($dbh, $row, $result);
6868
6969 # Render result page
7070 my $tvars = {
7171 id => $id,
7272 target_file => $row->{file_name},
7373 server_name => $row->{server_name} // 'local',
7474 server_kind => $row->{server_kind} // 'local',
7575 source_sha => substr($row->{blob_sha} // '', 0, 12),
7676 captured_h => $row->{date_time} // '',
7777 captured_epoch => int($row->{ts_epoch} || 0),
7878 result_status => $result->{status},
7979 result_ok => $result->{status} eq 'success' ? 1 : 0,
8080 result_msg => $result->{message} // '',
8181 backup_path => $result->{backup_path} // '',
8282 did_restore => 1,
8383 };
8484 print "Content-Type: text/html; charset=utf-8\nCache-Control: no-cache\n\n";
8585 my @body = $tpl->template('restore.html', $tvars);
8686 MODS::PageWrapper->new->wrapper(
8787 page_title => 'Restore', page_key => '',
8888 body_html => join('', @body), userinfo => { display_name => 'Operator' },
8989 );
9090 $db->db_disconnect($dbh);
9191 exit;
92}
93
94# ---- Recent RESTORE_LOG for this file (Wave 5 F4) ------------------
95my $q_file_esc = $dbh->quote($row->{file_name});
96my @recent_restores_this = $db->db_readwrite_multiple($dbh, qq~
97 SELECT restore_id, status, LEFT(error_message, 80) AS err_short,
98 LEFT(source_blob_sha, 12) AS sha_short,
99 restored_by,
100 UNIX_TIMESTAMP(restored_at) AS restored_epoch,
101 DATE_FORMAT(restored_at, '%b %d %H:%i') AS restored_h
102 FROM RESTORE_LOG
103 WHERE target_file = $q_file_esc
104 ORDER BY restore_id DESC LIMIT 5
105~, __FILE__, __LINE__);
106foreach my $rr (@recent_restores_this) {
107 $rr->{status_pill} = $rr->{status} eq 'success' ? 'pill-ok' :
108 $rr->{status} eq 'failed' ? 'pill-bad' : 'pill-mute';
109 $rr->{restored_epoch} //= 0;
92110}
93111
94112# ---- GET: preview page ---------------------------------------------
95113my ($current_sha, $current_exists, $current_size, $current_content) = _peek_current($row, $monitor);
96114
97115# Live diff: current on-disk vs captured content
98116my @diff_lines;
99117my ($diff_add, $diff_del) = (0, 0);
100118if ($current_exists && $current_sha && $row->{blob_sha} && $current_sha ne $row->{blob_sha}) {
101119 my $captured = _fetch_blob($dbh, $row->{blob_sha}) // '';
102120 @diff_lines = MODS::Diff::html_escape_lines(MODS::Diff::lines($current_content // '', $captured));
103121 for my $L (@diff_lines) {
104122 $diff_add++ if $L->{op} eq 'add';
105123 $diff_del++ if $L->{op} eq 'del';
106124 }
107125}
108126my $tvars = {
109127 id => $id,
110128 target_file => $row->{file_name},
111129 server_name => $row->{server_name} // 'local',
112130 server_kind => $row->{server_kind} // 'local',
113131 scan_name => $monitor->{scan_name} // '',
114132 source_sha => substr($row->{blob_sha} // '', 0, 12),
115133 source_sha_full=> $row->{blob_sha} // '',
116134 captured_h => $row->{date_time} // '',
117135 captured_epoch => int($row->{ts_epoch} || 0),
118136 current_sha => substr($current_sha // '', 0, 12),
119137 current_exists => $current_exists,
120138 current_size => defined($current_size) ? "$current_size bytes" : 'unknown',
121139 same_content => ($current_sha && $current_sha eq ($row->{blob_sha} // '')) ? 1 : 0,
122140 did_restore => 0,
123141 diff_url => "/diff.cgi?kind=file&id=$id",
124142 diff_lines => \@diff_lines,
125143 has_live_diff => scalar(@diff_lines) ? 1 : 0,
126144 diff_add => $diff_add,
127145 diff_del => $diff_del,
128146 diff_ctx => scalar(@diff_lines) - $diff_add - $diff_del,
147 recent_restores_this => \@recent_restores_this,
148 has_recent_restores => scalar(@recent_restores_this) ? 1 : 0,
129149};
130150
131151print "Content-Type: text/html; charset=utf-8\nCache-Control: no-cache\n\n";
132152my @body = $tpl->template('restore.html', $tvars);
133153MODS::PageWrapper->new->wrapper(
134154 page_title => 'Restore', page_key => '',
135155 body_html => join('', @body), userinfo => { display_name => 'Operator' },
136156);
137157$db->db_disconnect($dbh);
138158exit;
139159
140160#======================================================================
141161sub _load_change_row {
142162 my ($dbh, $id) = @_;
143163 return undef unless $id > 0;
144164 return $db->db_readwrite($dbh, qq~
145165 SELECT fc.file_changes_id AS id,
146166 fc.file_monitor_list_id, fc.server_id,
147167 fc.file_name, fc.blob_sha, fc.status, fc.date_time,
148168 UNIX_TIMESTAMP(fc.date_time) AS ts_epoch,
149169 s.server_name, s.kind AS server_kind,
150170 s.ssh_host, s.ssh_user, s.ssh_port,
151171 s.ssh_key_path, s.ssh_options,
152172 s.ssh_key_blob
153173 FROM FILE_CHANGES fc
154174 LEFT JOIN SERVERS s ON s.server_id = fc.server_id
155175 WHERE fc.file_changes_id = $id
156176 LIMIT 1
157177 ~, __FILE__, __LINE__);
158178}
159179
160180sub _load_monitor {
161181 my ($dbh, $mid) = @_;
162182 return undef unless $mid;
163183 return $db->db_readwrite($dbh, qq~
164184 SELECT file_monitor_list_id, scan_path, scan_name, server_id
165185 FROM FILE_MONITOR_SETTINGS
166186 WHERE file_monitor_list_id = $mid
167187 LIMIT 1
168188 ~, __FILE__, __LINE__);
169189}
170190
171191sub _fetch_blob {
172192 my ($dbh, $sha) = @_;
173193 return undef unless $sha;
174194 my $sth = $dbh->prepare("SELECT content_gz FROM BLOB_STORE WHERE blob_sha = ?");
175195 return undef unless $sth && $sth->execute($sha);
176196 my $r = $sth->fetchrow_arrayref;
177197 $sth->finish;
178198 return undef unless $r && $r->[0];
179199 return eval { uncompress($r->[0]) };
180200}
181201
182202#---------------------------------------------------------------------
183203# _peek_current($row, $monitor) -> ($sha, $exists, $size)
184204# For local: stat + hash the current on-disk content.
185205# For ssh_agent: SSH and sha256sum + wc -c.
186206#---------------------------------------------------------------------
187207sub _peek_current {
188208 my ($row, $monitor) = @_;
189209 my $path = $row->{file_name};
190210 if (($row->{server_kind} // 'local') eq 'local') {
191211 return (undef, 0, undef, undef) unless -e $path;
192212 return (undef, 1, -s $path, undef) unless -r $path;
193213 open(my $fh, '<:raw', $path) or return (undef, 1, -s $path, undef);
194214 local $/; my $c = <$fh>; close $fh;
195215 return (sha256_hex($c), 1, length $c, $c);
196216 }
197217 # SSH agent
198218 my ($rc, $out, $err) = _ssh_run($row, "test -f " . _sh_quote($path) . " && sha256sum " . _sh_quote($path) . " && wc -c < " . _sh_quote($path));
199219 if ($rc != 0) {
200220 return (undef, 0, undef, undef);
201221 }
202222 my @lines = split /\n/, $out;
203223 my $sha;
204224 my $size;
205225 foreach my $l (@lines) {
206226 if ($l =~ /^([0-9a-f]{64})\s/) { $sha = $1; }
207227 elsif ($l =~ /^(\d+)$/) { $size = int($1); }
208228 }
209229 # Fetch content over SSH for the live diff -- capped at 512 KB
210230 my $content;
211231 if ($sha && $size && $size < 512_000) {
212232 my ($rc2, $out2, $err2) = _ssh_run($row, "cat " . _sh_quote($path));
213233 $content = $out2 if $rc2 == 0;
214234 }
215235 return ($sha, 1, $size, $content);
216236}
217237
218238#---------------------------------------------------------------------
219239# _do_restore($dbh, $row, $monitor) -> { status, message, backup_path }
220240#---------------------------------------------------------------------
221241sub _do_restore {
222242 my ($dbh, $row, $monitor) = @_;
223243 my $blob_sha = $row->{blob_sha};
224244 unless ($blob_sha) {
225245 return { status => 'failed', message => 'source change has no blob_sha' };
226246 }
227247 my $content = _fetch_blob($dbh, $blob_sha);
228248 unless (defined $content) {
229249 return { status => 'failed', message => "blob $blob_sha not in BLOB_STORE" };
230250 }
231251
232252 my $stamp = time();
233253 my $backup = "$row->{file_name}.drift_restore_backup_$stamp";
234254
235255 if (($row->{server_kind} // 'local') eq 'local') {
236256 # Local restore -- backup then write
237257 if (-e $row->{file_name}) {
238258 unless (rename($row->{file_name}, $backup)) {
239259 # Fallback: cp to backup, then overwrite in place
240260 open(my $src, '<:raw', $row->{file_name}) or return {
241261 status => 'failed',
242262 message => "cannot read current file: $!"
243263 };
244264 open(my $bak, '>:raw', $backup) or return {
245265 status => 'failed',
246266 message => "cannot write backup: $!"
247267 };
248268 local $/; print {$bak} <$src>;
249269 close $src; close $bak;
250270 }
251271 } else {
252272 $backup = ''; # nothing to back up
253273 }
254274 # Write new content
255275 open(my $out, '>:raw', $row->{file_name}) or return {
256276 status => 'failed',
257277 message => "write failed: $!",
258278 backup_path => $backup,
259279 };
260280 print {$out} $content;
261281 close $out;
262282 # Verify SHA post-write
263283 open(my $v, '<:raw', $row->{file_name});
264284 local $/; my $verify = <$v>; close $v;
265285 my $vsha = sha256_hex($verify);
266286 if ($vsha ne $blob_sha) {
267287 return {
268288 status => 'failed',
269289 message => "post-write SHA mismatch: $vsha vs $blob_sha",
270290 backup_path => $backup,
271291 };
272292 }
273293 return {
274294 status => 'success',
275295 message => "restored " . length($content) . " bytes",
276296 backup_path => $backup,
277297 };
278298 }
279299
280300 # SSH agent restore
281301 # Step 1: cp current to backup (best-effort)
282302 my ($rc, $out, $err) = _ssh_run($row,
283303 "test -f " . _sh_quote($row->{file_name}) .
284304 " && cp -p " . _sh_quote($row->{file_name}) . " " . _sh_quote($backup) .
285305 " ; echo done");
286306 if ($rc != 0) {
287307 $backup = ''; # backup failed but we'll still try the restore
288308 }
289309
290310 # Step 2: write content via SSH stdin
291311 my $ok = _ssh_write($row, $row->{file_name}, $content);
292312 unless ($ok) {
293313 return {
294314 status => 'failed',
295315 message => "ssh write failed",
296316 backup_path => $backup,
297317 };
298318 }
299319
300320 # Step 3: Verify SHA remotely
301321 ($rc, $out, $err) = _ssh_run($row, "sha256sum " . _sh_quote($row->{file_name}));
302322 my $vsha = ($out =~ /^([0-9a-f]{64})\s/) ? $1 : '';
303323 if ($vsha ne $blob_sha) {
304324 return {
305325 status => 'failed',
306326 message => "post-write remote SHA mismatch: $vsha vs $blob_sha",
307327 backup_path => $backup,
308328 };
309329 }
310330 return {
311331 status => 'success',
312332 message => "remote restored " . length($content) . " bytes",
313333 backup_path => $backup,
314334 };
315335}
316336
317337#---------------------------------------------------------------------
318338sub _log_restore {
319339 my ($dbh, $row, $result) = @_;
320340 my $q_file = $dbh->quote($row->{file_name} // '');
321341 my $q_sha = $dbh->quote($row->{blob_sha} // '');
322342 my $q_bak = $dbh->quote($result->{backup_path} // '');
323343 my $q_stat = $dbh->quote($result->{status} // 'failed');
324344 my $q_err = $dbh->quote($result->{status} eq 'success' ? '' : ($result->{message} // ''));
325345 my $sid = int($row->{server_id} || 0);
326346 my $cid = int($row->{id} || 0);
327347 $db->db_readwrite($dbh, qq~
328348 INSERT INTO RESTORE_LOG
329349 (source_change_id, server_id, target_file, source_blob_sha,
330350 backup_path, status, error_message)
331351 VALUES
332352 ($cid, $sid, $q_file, $q_sha, $q_bak, $q_stat, $q_err)
333353 ~, __FILE__, __LINE__);
334354}
335355
336356#---------------------------------------------------------------------
337357# SSH helpers -- resolve key (encrypted blob or on-disk), spawn ssh
338358#---------------------------------------------------------------------
339359sub _ssh_argv {
340360 my ($row) = @_;
341361 my $user = $row->{ssh_user} || 'root';
342362 my $host = $row->{ssh_host};
343363 my $port = $row->{ssh_port} || 22;
344364 my $key_path = $row->{ssh_key_path} || '';
345365 my $tmp_key;
346366
347367 if ($row->{ssh_key_blob}) {
348368 my $pem = eval { MODS::Crypto::decrypt($row->{ssh_key_blob}) };
349369 if ($pem) {
350370 my $t = time();
351371 my $p = "/tmp/.ds_restore_key_${t}_$$_" . int(rand(1_000_000));
352372 if (sysopen(my $fh, $p,
353373 Fcntl::O_WRONLY() | Fcntl::O_CREAT() | Fcntl::O_EXCL(), 0600)) {
354374 print $fh $pem; close $fh;
355375 $key_path = $p;
356376 $tmp_key = $p;
357377 }
358378 }
359379 }
360380
361381 my @argv = ('/usr/bin/ssh',
362382 '-o', 'BatchMode=yes',
363383 '-o', 'StrictHostKeyChecking=no',
364384 '-o', 'UserKnownHostsFile=/dev/null',
365385 '-o', 'LogLevel=ERROR',
366386 '-o', 'ConnectTimeout=8',
367387 '-p', $port);
368388 push @argv, '-i', $key_path if $key_path && -r $key_path;
369389 if ($row->{ssh_options}) {
370390 foreach my $o (split /\s+/, $row->{ssh_options}) {
371391 push @argv, '-o', $o if length $o;
372392 }
373393 }
374394 push @argv, "$user\@$host";
375395 return (\@argv, $tmp_key);
376396}
377397
378398sub _ssh_run {
379399 my ($row, $cmd) = @_;
380400 my ($base, $tmp_key) = _ssh_argv($row);
381401 my @full = (@$base, $cmd);
382402 my ($wtr, $rdr, $err_fh);
383403 $err_fh = gensym;
384404 my $pid = eval { open3($wtr, $rdr, $err_fh, @full) };
385405 if ($@ || !$pid) {
386406 unlink $tmp_key if $tmp_key;
387407 return (-1, '', $@);
388408 }
389409 close $wtr;
390410 my $out = do { local $/; <$rdr> // '' };
391411 my $err = do { local $/; <$err_fh> // '' };
392412 close $rdr; close $err_fh;
393413 waitpid $pid, 0;
394414 my $rc = $? >> 8;
395415 unlink $tmp_key if $tmp_key;
396416 return ($rc, $out, $err);
397417}
398418
399419sub _ssh_write {
400420 my ($row, $path, $content) = @_;
401421 my ($base, $tmp_key) = _ssh_argv($row);
402422 # `cat > $path` on the remote side, content on stdin
403423 my @full = (@$base, "cat > " . _sh_quote($path));
404424 my ($wtr, $rdr, $err_fh);
405425 $err_fh = gensym;
406426 my $pid = eval { open3($wtr, $rdr, $err_fh, @full) };
407427 if ($@ || !$pid) {
408428 unlink $tmp_key if $tmp_key;
409429 return 0;
410430 }
411431 binmode $wtr;
412432 print {$wtr} $content;
413433 close $wtr;
414434 my $out = do { local $/; <$rdr> // '' };
415435 my $err = do { local $/; <$err_fh> // '' };
416436 close $rdr; close $err_fh;
417437 waitpid $pid, 0;
418438 my $rc = $? >> 8;
419439 unlink $tmp_key if $tmp_key;
420440 return $rc == 0 ? 1 : 0;
421441}
422442
423443sub _sh_quote {
424444 my $s = shift; $s //= '';
425445 $s =~ s/'/'\\''/g;
426446 return "'$s'";
427447}
428448
429449sub _render_error {
430450 my ($msg) = @_;
431451 print "Content-Type: text/html; charset=utf-8\nCache-Control: no-cache\n\n";
432452 my @body = $tpl->template('restore.html', {
433453 error_msg => $msg,
434454 has_error => 1,
435455 did_restore => 0,
436456 });
437457 MODS::PageWrapper->new->wrapper(
438458 page_title => 'Restore', page_key => '',
439459 body_html => join('', @body), userinfo => { display_name => 'Operator' },
440460 );
441461 exit;
442462}