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-11 23:34:31
Captured SHA1ea1f8830b275797740802e09411a83598e57d628198bc37ff99658177e255cc
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. +7 additions, -51 deletions, 411 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;
34use MODS::Diff;
3534
3635my $cgi = CGI->new;
3736my $db = MODS::DBConnect->new;
3837my $tpl = MODS::Template->new;
3938$|=1;
4039
4140my $dbh = $db->db_connect or die "DriftSense: DB connect failed\n";
4241
4342my $method = $ENV{REQUEST_METHOD} || 'GET';
4443my $id = int($cgi->param('id') || 0);
4544
4645# ---- Load the source change row -------------------------------------
4746my $row = _load_change_row($dbh, $id);
4847unless ($row && $row->{id}) {
4948 _render_error("Change #$id not found");
5049}
5150
5251# ---- Path safety: target file must be inside a monitored scan_path --
5352my $monitor = _load_monitor($dbh, $row->{file_monitor_list_id});
5453my $path_ok = 0;
5554if ($monitor && $monitor->{scan_path}) {
5655 my $sp = $monitor->{scan_path};
5756 $sp =~ s!/+$!!;
5857 $path_ok = 1 if index($row->{file_name}, "$sp/") == 0 || $row->{file_name} eq $sp;
5958}
6059unless ($path_ok) {
6160 _render_error("Target path <code>$row->{file_name}</code> is outside its monitor's configured scan_path; refusing to restore.");
6261}
6362
6463# ---- If POST, perform the restore ----------------------------------
6564if ($method eq 'POST' && $cgi->param('confirm')) {
6665 my $result = _do_restore($dbh, $row, $monitor);
6766 _log_restore($dbh, $row, $result);
6867
6968 # Render result page
7069 my $tvars = {
7170 id => $id,
7271 target_file => $row->{file_name},
7372 server_name => $row->{server_name} // 'local',
7473 server_kind => $row->{server_kind} // 'local',
7574 source_sha => substr($row->{blob_sha} // '', 0, 12),
7675 captured_h => $row->{date_time} // '',
7776 captured_epoch => int($row->{ts_epoch} || 0),
7877 result_status => $result->{status},
7978 result_ok => $result->{status} eq 'success' ? 1 : 0,
8079 result_msg => $result->{message} // '',
8180 backup_path => $result->{backup_path} // '',
8281 did_restore => 1,
8382 };
8483 print "Content-Type: text/html; charset=utf-8\nCache-Control: no-cache\n\n";
8584 my @body = $tpl->template('restore.html', $tvars);
8685 MODS::PageWrapper->new->wrapper(
8786 page_title => 'Restore', page_key => '',
8887 body_html => join('', @body), userinfo => { display_name => 'Operator' },
8988 );
9089 $db->db_disconnect($dbh);
9190 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;
11091}
11192
11293# ---- GET: preview page ---------------------------------------------
113my ($current_sha, $current_exists, $current_size, $current_content) = _peek_current($row, $monitor);
114
115# Live diff: current on-disk vs captured content
116my @diff_lines;
117my ($diff_add, $diff_del) = (0, 0);
118if ($current_exists && $current_sha && $row->{blob_sha} && $current_sha ne $row->{blob_sha}) {
119 my $captured = _fetch_blob($dbh, $row->{blob_sha}) // '';
120 @diff_lines = MODS::Diff::html_escape_lines(MODS::Diff::lines($current_content // '', $captured));
121 for my $L (@diff_lines) {
122 $diff_add++ if $L->{op} eq 'add';
123 $diff_del++ if $L->{op} eq 'del';
124 }
125}
94my ($current_sha, $current_exists, $current_size) = _peek_current($row, $monitor);
12695my $tvars = {
12796 id => $id,
12897 target_file => $row->{file_name},
12998 server_name => $row->{server_name} // 'local',
13099 server_kind => $row->{server_kind} // 'local',
131100 scan_name => $monitor->{scan_name} // '',
132101 source_sha => substr($row->{blob_sha} // '', 0, 12),
133102 source_sha_full=> $row->{blob_sha} // '',
134103 captured_h => $row->{date_time} // '',
135104 captured_epoch => int($row->{ts_epoch} || 0),
136105 current_sha => substr($current_sha // '', 0, 12),
137106 current_exists => $current_exists,
138107 current_size => defined($current_size) ? "$current_size bytes" : 'unknown',
139108 same_content => ($current_sha && $current_sha eq ($row->{blob_sha} // '')) ? 1 : 0,
140109 did_restore => 0,
141110 diff_url => "/diff.cgi?kind=file&id=$id",
142 diff_lines => \@diff_lines,
143 has_live_diff => scalar(@diff_lines) ? 1 : 0,
144 diff_add => $diff_add,
145 diff_del => $diff_del,
146 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,
149111};
150112
151113print "Content-Type: text/html; charset=utf-8\nCache-Control: no-cache\n\n";
152114my @body = $tpl->template('restore.html', $tvars);
153115MODS::PageWrapper->new->wrapper(
154116 page_title => 'Restore', page_key => '',
155117 body_html => join('', @body), userinfo => { display_name => 'Operator' },
156118);
157119$db->db_disconnect($dbh);
158120exit;
159121
160122#======================================================================
161123sub _load_change_row {
162124 my ($dbh, $id) = @_;
163125 return undef unless $id > 0;
164126 return $db->db_readwrite($dbh, qq~
165127 SELECT fc.file_changes_id AS id,
166128 fc.file_monitor_list_id, fc.server_id,
167129 fc.file_name, fc.blob_sha, fc.status, fc.date_time,
168130 UNIX_TIMESTAMP(fc.date_time) AS ts_epoch,
169131 s.server_name, s.kind AS server_kind,
170132 s.ssh_host, s.ssh_user, s.ssh_port,
171133 s.ssh_key_path, s.ssh_options,
172134 s.ssh_key_blob
173135 FROM FILE_CHANGES fc
174136 LEFT JOIN SERVERS s ON s.server_id = fc.server_id
175137 WHERE fc.file_changes_id = $id
176138 LIMIT 1
177139 ~, __FILE__, __LINE__);
178140}
179141
180142sub _load_monitor {
181143 my ($dbh, $mid) = @_;
182144 return undef unless $mid;
183145 return $db->db_readwrite($dbh, qq~
184146 SELECT file_monitor_list_id, scan_path, scan_name, server_id
185147 FROM FILE_MONITOR_SETTINGS
186148 WHERE file_monitor_list_id = $mid
187149 LIMIT 1
188150 ~, __FILE__, __LINE__);
189151}
190152
191153sub _fetch_blob {
192154 my ($dbh, $sha) = @_;
193155 return undef unless $sha;
194156 my $sth = $dbh->prepare("SELECT content_gz FROM BLOB_STORE WHERE blob_sha = ?");
195157 return undef unless $sth && $sth->execute($sha);
196158 my $r = $sth->fetchrow_arrayref;
197159 $sth->finish;
198160 return undef unless $r && $r->[0];
199161 return eval { uncompress($r->[0]) };
200162}
201163
202164#---------------------------------------------------------------------
203165# _peek_current($row, $monitor) -> ($sha, $exists, $size)
204166# For local: stat + hash the current on-disk content.
205167# For ssh_agent: SSH and sha256sum + wc -c.
206168#---------------------------------------------------------------------
207169sub _peek_current {
208170 my ($row, $monitor) = @_;
209171 my $path = $row->{file_name};
210172 if (($row->{server_kind} // 'local') eq 'local') {
211 return (undef, 0, undef, undef) unless -e $path;
212 return (undef, 1, -s $path, undef) unless -r $path;
213 open(my $fh, '<:raw', $path) or return (undef, 1, -s $path, undef);
173 return (undef, 0, undef) unless -e $path;
174 return (undef, 1, -s $path) unless -r $path;
175 open(my $fh, '<:raw', $path) or return (undef, 1, -s $path);
214176 local $/; my $c = <$fh>; close $fh;
215 return (sha256_hex($c), 1, length $c, $c);
177 return (sha256_hex($c), 1, length $c);
216178 }
217179 # SSH agent
218180 my ($rc, $out, $err) = _ssh_run($row, "test -f " . _sh_quote($path) . " && sha256sum " . _sh_quote($path) . " && wc -c < " . _sh_quote($path));
219181 if ($rc != 0) {
220 return (undef, 0, undef, undef);
182 return (undef, 0, undef);
221183 }
222184 my @lines = split /\n/, $out;
223185 my $sha;
224186 my $size;
225187 foreach my $l (@lines) {
226188 if ($l =~ /^([0-9a-f]{64})\s/) { $sha = $1; }
227189 elsif ($l =~ /^(\d+)$/) { $size = int($1); }
228 }
229 # Fetch content over SSH for the live diff -- capped at 512 KB
230 my $content;
231 if ($sha && $size && $size < 512_000) {
232 my ($rc2, $out2, $err2) = _ssh_run($row, "cat " . _sh_quote($path));
233 $content = $out2 if $rc2 == 0;
234190 }
235 return ($sha, 1, $size, $content);
191 return ($sha, 1, $size);
236192}
237193
238194#---------------------------------------------------------------------
239195# _do_restore($dbh, $row, $monitor) -> { status, message, backup_path }
240196#---------------------------------------------------------------------
241197sub _do_restore {
242198 my ($dbh, $row, $monitor) = @_;
243199 my $blob_sha = $row->{blob_sha};
244200 unless ($blob_sha) {
245201 return { status => 'failed', message => 'source change has no blob_sha' };
246202 }
247203 my $content = _fetch_blob($dbh, $blob_sha);
248204 unless (defined $content) {
249205 return { status => 'failed', message => "blob $blob_sha not in BLOB_STORE" };
250206 }
251207
252208 my $stamp = time();
253209 my $backup = "$row->{file_name}.drift_restore_backup_$stamp";
254210
255211 if (($row->{server_kind} // 'local') eq 'local') {
256212 # Local restore -- backup then write
257213 if (-e $row->{file_name}) {
258214 unless (rename($row->{file_name}, $backup)) {
259215 # Fallback: cp to backup, then overwrite in place
260216 open(my $src, '<:raw', $row->{file_name}) or return {
261217 status => 'failed',
262218 message => "cannot read current file: $!"
263219 };
264220 open(my $bak, '>:raw', $backup) or return {
265221 status => 'failed',
266222 message => "cannot write backup: $!"
267223 };
268224 local $/; print {$bak} <$src>;
269225 close $src; close $bak;
270226 }
271227 } else {
272228 $backup = ''; # nothing to back up
273229 }
274230 # Write new content
275231 open(my $out, '>:raw', $row->{file_name}) or return {
276232 status => 'failed',
277233 message => "write failed: $!",
278234 backup_path => $backup,
279235 };
280236 print {$out} $content;
281237 close $out;
282238 # Verify SHA post-write
283239 open(my $v, '<:raw', $row->{file_name});
284240 local $/; my $verify = <$v>; close $v;
285241 my $vsha = sha256_hex($verify);
286242 if ($vsha ne $blob_sha) {
287243 return {
288244 status => 'failed',
289245 message => "post-write SHA mismatch: $vsha vs $blob_sha",
290246 backup_path => $backup,
291247 };
292248 }
293249 return {
294250 status => 'success',
295251 message => "restored " . length($content) . " bytes",
296252 backup_path => $backup,
297253 };
298254 }
299255
300256 # SSH agent restore
301257 # Step 1: cp current to backup (best-effort)
302258 my ($rc, $out, $err) = _ssh_run($row,
303259 "test -f " . _sh_quote($row->{file_name}) .
304260 " && cp -p " . _sh_quote($row->{file_name}) . " " . _sh_quote($backup) .
305261 " ; echo done");
306262 if ($rc != 0) {
307263 $backup = ''; # backup failed but we'll still try the restore
308264 }
309265
310266 # Step 2: write content via SSH stdin
311267 my $ok = _ssh_write($row, $row->{file_name}, $content);
312268 unless ($ok) {
313269 return {
314270 status => 'failed',
315271 message => "ssh write failed",
316272 backup_path => $backup,
317273 };
318274 }
319275
320276 # Step 3: Verify SHA remotely
321277 ($rc, $out, $err) = _ssh_run($row, "sha256sum " . _sh_quote($row->{file_name}));
322278 my $vsha = ($out =~ /^([0-9a-f]{64})\s/) ? $1 : '';
323279 if ($vsha ne $blob_sha) {
324280 return {
325281 status => 'failed',
326282 message => "post-write remote SHA mismatch: $vsha vs $blob_sha",
327283 backup_path => $backup,
328284 };
329285 }
330286 return {
331287 status => 'success',
332288 message => "remote restored " . length($content) . " bytes",
333289 backup_path => $backup,
334290 };
335291}
336292
337293#---------------------------------------------------------------------
338294sub _log_restore {
339295 my ($dbh, $row, $result) = @_;
340296 my $q_file = $dbh->quote($row->{file_name} // '');
341297 my $q_sha = $dbh->quote($row->{blob_sha} // '');
342298 my $q_bak = $dbh->quote($result->{backup_path} // '');
343299 my $q_stat = $dbh->quote($result->{status} // 'failed');
344300 my $q_err = $dbh->quote($result->{status} eq 'success' ? '' : ($result->{message} // ''));
345301 my $sid = int($row->{server_id} || 0);
346302 my $cid = int($row->{id} || 0);
347303 $db->db_readwrite($dbh, qq~
348304 INSERT INTO RESTORE_LOG
349305 (source_change_id, server_id, target_file, source_blob_sha,
350306 backup_path, status, error_message)
351307 VALUES
352308 ($cid, $sid, $q_file, $q_sha, $q_bak, $q_stat, $q_err)
353309 ~, __FILE__, __LINE__);
354310}
355311
356312#---------------------------------------------------------------------
357313# SSH helpers -- resolve key (encrypted blob or on-disk), spawn ssh
358314#---------------------------------------------------------------------
359315sub _ssh_argv {
360316 my ($row) = @_;
361317 my $user = $row->{ssh_user} || 'root';
362318 my $host = $row->{ssh_host};
363319 my $port = $row->{ssh_port} || 22;
364320 my $key_path = $row->{ssh_key_path} || '';
365321 my $tmp_key;
366322
367323 if ($row->{ssh_key_blob}) {
368324 my $pem = eval { MODS::Crypto::decrypt($row->{ssh_key_blob}) };
369325 if ($pem) {
370326 my $t = time();
371327 my $p = "/tmp/.ds_restore_key_${t}_$$_" . int(rand(1_000_000));
372328 if (sysopen(my $fh, $p,
373329 Fcntl::O_WRONLY() | Fcntl::O_CREAT() | Fcntl::O_EXCL(), 0600)) {
374330 print $fh $pem; close $fh;
375331 $key_path = $p;
376332 $tmp_key = $p;
377333 }
378334 }
379335 }
380336
381337 my @argv = ('/usr/bin/ssh',
382338 '-o', 'BatchMode=yes',
383339 '-o', 'StrictHostKeyChecking=no',
384340 '-o', 'UserKnownHostsFile=/dev/null',
385341 '-o', 'LogLevel=ERROR',
386342 '-o', 'ConnectTimeout=8',
387343 '-p', $port);
388344 push @argv, '-i', $key_path if $key_path && -r $key_path;
389345 if ($row->{ssh_options}) {
390346 foreach my $o (split /\s+/, $row->{ssh_options}) {
391347 push @argv, '-o', $o if length $o;
392348 }
393349 }
394350 push @argv, "$user\@$host";
395351 return (\@argv, $tmp_key);
396352}
397353
398354sub _ssh_run {
399355 my ($row, $cmd) = @_;
400356 my ($base, $tmp_key) = _ssh_argv($row);
401357 my @full = (@$base, $cmd);
402358 my ($wtr, $rdr, $err_fh);
403359 $err_fh = gensym;
404360 my $pid = eval { open3($wtr, $rdr, $err_fh, @full) };
405361 if ($@ || !$pid) {
406362 unlink $tmp_key if $tmp_key;
407363 return (-1, '', $@);
408364 }
409365 close $wtr;
410366 my $out = do { local $/; <$rdr> // '' };
411367 my $err = do { local $/; <$err_fh> // '' };
412368 close $rdr; close $err_fh;
413369 waitpid $pid, 0;
414370 my $rc = $? >> 8;
415371 unlink $tmp_key if $tmp_key;
416372 return ($rc, $out, $err);
417373}
418374
419375sub _ssh_write {
420376 my ($row, $path, $content) = @_;
421377 my ($base, $tmp_key) = _ssh_argv($row);
422378 # `cat > $path` on the remote side, content on stdin
423379 my @full = (@$base, "cat > " . _sh_quote($path));
424380 my ($wtr, $rdr, $err_fh);
425381 $err_fh = gensym;
426382 my $pid = eval { open3($wtr, $rdr, $err_fh, @full) };
427383 if ($@ || !$pid) {
428384 unlink $tmp_key if $tmp_key;
429385 return 0;
430386 }
431387 binmode $wtr;
432388 print {$wtr} $content;
433389 close $wtr;
434390 my $out = do { local $/; <$rdr> // '' };
435391 my $err = do { local $/; <$err_fh> // '' };
436392 close $rdr; close $err_fh;
437393 waitpid $pid, 0;
438394 my $rc = $? >> 8;
439395 unlink $tmp_key if $tmp_key;
440396 return $rc == 0 ? 1 : 0;
441397}
442398
443399sub _sh_quote {
444400 my $s = shift; $s //= '';
445401 $s =~ s/'/'\\''/g;
446402 return "'$s'";
447403}
448404
449405sub _render_error {
450406 my ($msg) = @_;
451407 print "Content-Type: text/html; charset=utf-8\nCache-Control: no-cache\n\n";
452408 my @body = $tpl->template('restore.html', {
453409 error_msg => $msg,
454410 has_error => 1,
455411 did_restore => 0,
456412 });
457413 MODS::PageWrapper->new->wrapper(
458414 page_title => 'Restore', page_key => '',
459415 body_html => join('', @body), userinfo => { display_name => 'Operator' },
460416 );
461417 exit;
462418}
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.