Restore

O Operator
Restore

Restore file to captured state

Every captured change carries its SHA-256-addressed content in BLOB_STORE. Restoring writes that content back to the original path — current file gets backed up to <path>.drift_restore_backup_<epoch> before overwrite.

What will change
Preview -- nothing has been written yet.
Target file/var/www/vhosts/3dshawn.com/site1/restore.cgi
SiteDriftSense self-monitor on local
Kindlocal
Captured at2026-07-12 00:02:04
Captured SHA5edc99e614711c5e3afb769f689b8d39a26eb4011b084def485ea9970e69406c
Current state on disk
Live check just now. If SHAs match, the restore is a no-op.
File presentyes
Size16800 bytes
Current SHA2f8b971be093
Same as captured?no -- restore will change it
What restore will change — live diff
Left column shows current on-disk content; right shows what restore will write. +0 additions, -20 deletions, 442 unchanged context lines.
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;
11092}
11193
11294# ---- GET: preview page ---------------------------------------------
11395my ($current_sha, $current_exists, $current_size, $current_content) = _peek_current($row, $monitor);
11496
11597# Live diff: current on-disk vs captured content
11698my @diff_lines;
11799my ($diff_add, $diff_del) = (0, 0);
118100if ($current_exists && $current_sha && $row->{blob_sha} && $current_sha ne $row->{blob_sha}) {
119101 my $captured = _fetch_blob($dbh, $row->{blob_sha}) // '';
120102 @diff_lines = MODS::Diff::html_escape_lines(MODS::Diff::lines($current_content // '', $captured));
121103 for my $L (@diff_lines) {
122104 $diff_add++ if $L->{op} eq 'add';
123105 $diff_del++ if $L->{op} eq 'del';
124106 }
125107}
126108my $tvars = {
127109 id => $id,
128110 target_file => $row->{file_name},
129111 server_name => $row->{server_name} // 'local',
130112 server_kind => $row->{server_kind} // 'local',
131113 scan_name => $monitor->{scan_name} // '',
132114 source_sha => substr($row->{blob_sha} // '', 0, 12),
133115 source_sha_full=> $row->{blob_sha} // '',
134116 captured_h => $row->{date_time} // '',
135117 captured_epoch => int($row->{ts_epoch} || 0),
136118 current_sha => substr($current_sha // '', 0, 12),
137119 current_exists => $current_exists,
138120 current_size => defined($current_size) ? "$current_size bytes" : 'unknown',
139121 same_content => ($current_sha && $current_sha eq ($row->{blob_sha} // '')) ? 1 : 0,
140122 did_restore => 0,
141123 diff_url => "/diff.cgi?kind=file&id=$id",
142124 diff_lines => \@diff_lines,
143125 has_live_diff => scalar(@diff_lines) ? 1 : 0,
144126 diff_add => $diff_add,
145127 diff_del => $diff_del,
146128 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,
149129};
150130
151131print "Content-Type: text/html; charset=utf-8\nCache-Control: no-cache\n\n";
152132my @body = $tpl->template('restore.html', $tvars);
153133MODS::PageWrapper->new->wrapper(
154134 page_title => 'Restore', page_key => '',
155135 body_html => join('', @body), userinfo => { display_name => 'Operator' },
156136);
157137$db->db_disconnect($dbh);
158138exit;
159139
160140#======================================================================
161141sub _load_change_row {
162142 my ($dbh, $id) = @_;
163143 return undef unless $id > 0;
164144 return $db->db_readwrite($dbh, qq~
165145 SELECT fc.file_changes_id AS id,
166146 fc.file_monitor_list_id, fc.server_id,
167147 fc.file_name, fc.blob_sha, fc.status, fc.date_time,
168148 UNIX_TIMESTAMP(fc.date_time) AS ts_epoch,
169149 s.server_name, s.kind AS server_kind,
170150 s.ssh_host, s.ssh_user, s.ssh_port,
171151 s.ssh_key_path, s.ssh_options,
172152 s.ssh_key_blob
173153 FROM FILE_CHANGES fc
174154 LEFT JOIN SERVERS s ON s.server_id = fc.server_id
175155 WHERE fc.file_changes_id = $id
176156 LIMIT 1
177157 ~, __FILE__, __LINE__);
178158}
179159
180160sub _load_monitor {
181161 my ($dbh, $mid) = @_;
182162 return undef unless $mid;
183163 return $db->db_readwrite($dbh, qq~
184164 SELECT file_monitor_list_id, scan_path, scan_name, server_id
185165 FROM FILE_MONITOR_SETTINGS
186166 WHERE file_monitor_list_id = $mid
187167 LIMIT 1
188168 ~, __FILE__, __LINE__);
189169}
190170
191171sub _fetch_blob {
192172 my ($dbh, $sha) = @_;
193173 return undef unless $sha;
194174 my $sth = $dbh->prepare("SELECT content_gz FROM BLOB_STORE WHERE blob_sha = ?");
195175 return undef unless $sth && $sth->execute($sha);
196176 my $r = $sth->fetchrow_arrayref;
197177 $sth->finish;
198178 return undef unless $r && $r->[0];
199179 return eval { uncompress($r->[0]) };
200180}
201181
202182#---------------------------------------------------------------------
203183# _peek_current($row, $monitor) -> ($sha, $exists, $size)
204184# For local: stat + hash the current on-disk content.
205185# For ssh_agent: SSH and sha256sum + wc -c.
206186#---------------------------------------------------------------------
207187sub _peek_current {
208188 my ($row, $monitor) = @_;
209189 my $path = $row->{file_name};
210190 if (($row->{server_kind} // 'local') eq 'local') {
211191 return (undef, 0, undef, undef) unless -e $path;
212192 return (undef, 1, -s $path, undef) unless -r $path;
213193 open(my $fh, '<:raw', $path) or return (undef, 1, -s $path, undef);
214194 local $/; my $c = <$fh>; close $fh;
215195 return (sha256_hex($c), 1, length $c, $c);
216196 }
217197 # SSH agent
218198 my ($rc, $out, $err) = _ssh_run($row, "test -f " . _sh_quote($path) . " && sha256sum " . _sh_quote($path) . " && wc -c < " . _sh_quote($path));
219199 if ($rc != 0) {
220200 return (undef, 0, undef, undef);
221201 }
222202 my @lines = split /\n/, $out;
223203 my $sha;
224204 my $size;
225205 foreach my $l (@lines) {
226206 if ($l =~ /^([0-9a-f]{64})\s/) { $sha = $1; }
227207 elsif ($l =~ /^(\d+)$/) { $size = int($1); }
228208 }
229209 # Fetch content over SSH for the live diff -- capped at 512 KB
230210 my $content;
231211 if ($sha && $size && $size < 512_000) {
232212 my ($rc2, $out2, $err2) = _ssh_run($row, "cat " . _sh_quote($path));
233213 $content = $out2 if $rc2 == 0;
234214 }
235215 return ($sha, 1, $size, $content);
236216}
237217
238218#---------------------------------------------------------------------
239219# _do_restore($dbh, $row, $monitor) -> { status, message, backup_path }
240220#---------------------------------------------------------------------
241221sub _do_restore {
242222 my ($dbh, $row, $monitor) = @_;
243223 my $blob_sha = $row->{blob_sha};
244224 unless ($blob_sha) {
245225 return { status => 'failed', message => 'source change has no blob_sha' };
246226 }
247227 my $content = _fetch_blob($dbh, $blob_sha);
248228 unless (defined $content) {
249229 return { status => 'failed', message => "blob $blob_sha not in BLOB_STORE" };
250230 }
251231
252232 my $stamp = time();
253233 my $backup = "$row->{file_name}.drift_restore_backup_$stamp";
254234
255235 if (($row->{server_kind} // 'local') eq 'local') {
256236 # Local restore -- backup then write
257237 if (-e $row->{file_name}) {
258238 unless (rename($row->{file_name}, $backup)) {
259239 # Fallback: cp to backup, then overwrite in place
260240 open(my $src, '<:raw', $row->{file_name}) or return {
261241 status => 'failed',
262242 message => "cannot read current file: $!"
263243 };
264244 open(my $bak, '>:raw', $backup) or return {
265245 status => 'failed',
266246 message => "cannot write backup: $!"
267247 };
268248 local $/; print {$bak} <$src>;
269249 close $src; close $bak;
270250 }
271251 } else {
272252 $backup = ''; # nothing to back up
273253 }
274254 # Write new content
275255 open(my $out, '>:raw', $row->{file_name}) or return {
276256 status => 'failed',
277257 message => "write failed: $!",
278258 backup_path => $backup,
279259 };
280260 print {$out} $content;
281261 close $out;
282262 # Verify SHA post-write
283263 open(my $v, '<:raw', $row->{file_name});
284264 local $/; my $verify = <$v>; close $v;
285265 my $vsha = sha256_hex($verify);
286266 if ($vsha ne $blob_sha) {
287267 return {
288268 status => 'failed',
289269 message => "post-write SHA mismatch: $vsha vs $blob_sha",
290270 backup_path => $backup,
291271 };
292272 }
293273 return {
294274 status => 'success',
295275 message => "restored " . length($content) . " bytes",
296276 backup_path => $backup,
297277 };
298278 }
299279
300280 # SSH agent restore
301281 # Step 1: cp current to backup (best-effort)
302282 my ($rc, $out, $err) = _ssh_run($row,
303283 "test -f " . _sh_quote($row->{file_name}) .
304284 " && cp -p " . _sh_quote($row->{file_name}) . " " . _sh_quote($backup) .
305285 " ; echo done");
306286 if ($rc != 0) {
307287 $backup = ''; # backup failed but we'll still try the restore
308288 }
309289
310290 # Step 2: write content via SSH stdin
311291 my $ok = _ssh_write($row, $row->{file_name}, $content);
312292 unless ($ok) {
313293 return {
314294 status => 'failed',
315295 message => "ssh write failed",
316296 backup_path => $backup,
317297 };
318298 }
319299
320300 # Step 3: Verify SHA remotely
321301 ($rc, $out, $err) = _ssh_run($row, "sha256sum " . _sh_quote($row->{file_name}));
322302 my $vsha = ($out =~ /^([0-9a-f]{64})\s/) ? $1 : '';
323303 if ($vsha ne $blob_sha) {
324304 return {
325305 status => 'failed',
326306 message => "post-write remote SHA mismatch: $vsha vs $blob_sha",
327307 backup_path => $backup,
328308 };
329309 }
330310 return {
331311 status => 'success',
332312 message => "remote restored " . length($content) . " bytes",
333313 backup_path => $backup,
334314 };
335315}
336316
337317#---------------------------------------------------------------------
338318sub _log_restore {
339319 my ($dbh, $row, $result) = @_;
340320 my $q_file = $dbh->quote($row->{file_name} // '');
341321 my $q_sha = $dbh->quote($row->{blob_sha} // '');
342322 my $q_bak = $dbh->quote($result->{backup_path} // '');
343323 my $q_stat = $dbh->quote($result->{status} // 'failed');
344324 my $q_err = $dbh->quote($result->{status} eq 'success' ? '' : ($result->{message} // ''));
345325 my $sid = int($row->{server_id} || 0);
346326 my $cid = int($row->{id} || 0);
347327 $db->db_readwrite($dbh, qq~
348328 INSERT INTO RESTORE_LOG
349329 (source_change_id, server_id, target_file, source_blob_sha,
350330 backup_path, status, error_message)
351331 VALUES
352332 ($cid, $sid, $q_file, $q_sha, $q_bak, $q_stat, $q_err)
353333 ~, __FILE__, __LINE__);
354334}
355335
356336#---------------------------------------------------------------------
357337# SSH helpers -- resolve key (encrypted blob or on-disk), spawn ssh
358338#---------------------------------------------------------------------
359339sub _ssh_argv {
360340 my ($row) = @_;
361341 my $user = $row->{ssh_user} || 'root';
362342 my $host = $row->{ssh_host};
363343 my $port = $row->{ssh_port} || 22;
364344 my $key_path = $row->{ssh_key_path} || '';
365345 my $tmp_key;
366346
367347 if ($row->{ssh_key_blob}) {
368348 my $pem = eval { MODS::Crypto::decrypt($row->{ssh_key_blob}) };
369349 if ($pem) {
370350 my $t = time();
371351 my $p = "/tmp/.ds_restore_key_${t}_$$_" . int(rand(1_000_000));
372352 if (sysopen(my $fh, $p,
373353 Fcntl::O_WRONLY() | Fcntl::O_CREAT() | Fcntl::O_EXCL(), 0600)) {
374354 print $fh $pem; close $fh;
375355 $key_path = $p;
376356 $tmp_key = $p;
377357 }
378358 }
379359 }
380360
381361 my @argv = ('/usr/bin/ssh',
382362 '-o', 'BatchMode=yes',
383363 '-o', 'StrictHostKeyChecking=no',
384364 '-o', 'UserKnownHostsFile=/dev/null',
385365 '-o', 'LogLevel=ERROR',
386366 '-o', 'ConnectTimeout=8',
387367 '-p', $port);
388368 push @argv, '-i', $key_path if $key_path && -r $key_path;
389369 if ($row->{ssh_options}) {
390370 foreach my $o (split /\s+/, $row->{ssh_options}) {
391371 push @argv, '-o', $o if length $o;
392372 }
393373 }
394374 push @argv, "$user\@$host";
395375 return (\@argv, $tmp_key);
396376}
397377
398378sub _ssh_run {
399379 my ($row, $cmd) = @_;
400380 my ($base, $tmp_key) = _ssh_argv($row);
401381 my @full = (@$base, $cmd);
402382 my ($wtr, $rdr, $err_fh);
403383 $err_fh = gensym;
404384 my $pid = eval { open3($wtr, $rdr, $err_fh, @full) };
405385 if ($@ || !$pid) {
406386 unlink $tmp_key if $tmp_key;
407387 return (-1, '', $@);
408388 }
409389 close $wtr;
410390 my $out = do { local $/; <$rdr> // '' };
411391 my $err = do { local $/; <$err_fh> // '' };
412392 close $rdr; close $err_fh;
413393 waitpid $pid, 0;
414394 my $rc = $? >> 8;
415395 unlink $tmp_key if $tmp_key;
416396 return ($rc, $out, $err);
417397}
418398
419399sub _ssh_write {
420400 my ($row, $path, $content) = @_;
421401 my ($base, $tmp_key) = _ssh_argv($row);
422402 # `cat > $path` on the remote side, content on stdin
423403 my @full = (@$base, "cat > " . _sh_quote($path));
424404 my ($wtr, $rdr, $err_fh);
425405 $err_fh = gensym;
426406 my $pid = eval { open3($wtr, $rdr, $err_fh, @full) };
427407 if ($@ || !$pid) {
428408 unlink $tmp_key if $tmp_key;
429409 return 0;
430410 }
431411 binmode $wtr;
432412 print {$wtr} $content;
433413 close $wtr;
434414 my $out = do { local $/; <$rdr> // '' };
435415 my $err = do { local $/; <$err_fh> // '' };
436416 close $rdr; close $err_fh;
437417 waitpid $pid, 0;
438418 my $rc = $? >> 8;
439419 unlink $tmp_key if $tmp_key;
440420 return $rc == 0 ? 1 : 0;
441421}
442422
443423sub _sh_quote {
444424 my $s = shift; $s //= '';
445425 $s =~ s/'/'\\''/g;
446426 return "'$s'";
447427}
448428
449429sub _render_error {
450430 my ($msg) = @_;
451431 print "Content-Type: text/html; charset=utf-8\nCache-Control: no-cache\n\n";
452432 my @body = $tpl->template('restore.html', {
453433 error_msg => $msg,
454434 has_error => 1,
455435 did_restore => 0,
456436 });
457437 MODS::PageWrapper->new->wrapper(
458438 page_title => 'Restore', page_key => '',
459439 body_html => join('', @body), userinfo => { display_name => 'Operator' },
460440 );
461441 exit;
462442}
Confirm restore
Backs current content to <target>.drift_restore_backup_<epoch>, writes the captured content, verifies SHA post-write.
Cancel Logged to RESTORE_LOG regardless of outcome.