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:02:04

Added
+31
lines
Removed
-7
lines
Context
411
unchanged
Blobs
from 1ea1f8830b27
to 5edc99e61471
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;
34use MODS::Diff;
3435
3536my $cgi = CGI->new;
3637my $db = MODS::DBConnect->new;
3738my $tpl = MODS::Template->new;
3839$|=1;
3940
4041my $dbh = $db->db_connect or die "DriftSense: DB connect failed\n";
4142
4243my $method = $ENV{REQUEST_METHOD} || 'GET';
4344my $id = int($cgi->param('id') || 0);
4445
4546# ---- Load the source change row -------------------------------------
4647my $row = _load_change_row($dbh, $id);
4748unless ($row && $row->{id}) {
4849 _render_error("Change #$id not found");
4950}
5051
5152# ---- Path safety: target file must be inside a monitored scan_path --
5253my $monitor = _load_monitor($dbh, $row->{file_monitor_list_id});
5354my $path_ok = 0;
5455if ($monitor && $monitor->{scan_path}) {
5556 my $sp = $monitor->{scan_path};
5657 $sp =~ s!/+$!!;
5758 $path_ok = 1 if index($row->{file_name}, "$sp/") == 0 || $row->{file_name} eq $sp;
5859}
5960unless ($path_ok) {
6061 _render_error("Target path <code>$row->{file_name}</code> is outside its monitor's configured scan_path; refusing to restore.");
6162}
6263
6364# ---- If POST, perform the restore ----------------------------------
6465if ($method eq 'POST' && $cgi->param('confirm')) {
6566 my $result = _do_restore($dbh, $row, $monitor);
6667 _log_restore($dbh, $row, $result);
6768
6869 # Render result page
6970 my $tvars = {
7071 id => $id,
7172 target_file => $row->{file_name},
7273 server_name => $row->{server_name} // 'local',
7374 server_kind => $row->{server_kind} // 'local',
7475 source_sha => substr($row->{blob_sha} // '', 0, 12),
7576 captured_h => $row->{date_time} // '',
7677 captured_epoch => int($row->{ts_epoch} || 0),
7778 result_status => $result->{status},
7879 result_ok => $result->{status} eq 'success' ? 1 : 0,
7980 result_msg => $result->{message} // '',
8081 backup_path => $result->{backup_path} // '',
8182 did_restore => 1,
8283 };
8384 print "Content-Type: text/html; charset=utf-8\nCache-Control: no-cache\n\n";
8485 my @body = $tpl->template('restore.html', $tvars);
8586 MODS::PageWrapper->new->wrapper(
8687 page_title => 'Restore', page_key => '',
8788 body_html => join('', @body), userinfo => { display_name => 'Operator' },
8889 );
8990 $db->db_disconnect($dbh);
9091 exit;
9192}
9293
9394# ---- GET: preview page ---------------------------------------------
94my ($current_sha, $current_exists, $current_size) = _peek_current($row, $monitor);
95my ($current_sha, $current_exists, $current_size, $current_content) = _peek_current($row, $monitor);
96
97# Live diff: current on-disk vs captured content
98my @diff_lines;
99my ($diff_add, $diff_del) = (0, 0);
100if ($current_exists && $current_sha && $row->{blob_sha} && $current_sha ne $row->{blob_sha}) {
101 my $captured = _fetch_blob($dbh, $row->{blob_sha}) // '';
102 @diff_lines = MODS::Diff::html_escape_lines(MODS::Diff::lines($current_content // '', $captured));
103 for my $L (@diff_lines) {
104 $diff_add++ if $L->{op} eq 'add';
105 $diff_del++ if $L->{op} eq 'del';
106 }
107}
95108my $tvars = {
96109 id => $id,
97110 target_file => $row->{file_name},
98111 server_name => $row->{server_name} // 'local',
99112 server_kind => $row->{server_kind} // 'local',
100113 scan_name => $monitor->{scan_name} // '',
101114 source_sha => substr($row->{blob_sha} // '', 0, 12),
102115 source_sha_full=> $row->{blob_sha} // '',
103116 captured_h => $row->{date_time} // '',
104117 captured_epoch => int($row->{ts_epoch} || 0),
105118 current_sha => substr($current_sha // '', 0, 12),
106119 current_exists => $current_exists,
107120 current_size => defined($current_size) ? "$current_size bytes" : 'unknown',
108121 same_content => ($current_sha && $current_sha eq ($row->{blob_sha} // '')) ? 1 : 0,
109122 did_restore => 0,
110123 diff_url => "/diff.cgi?kind=file&id=$id",
124 diff_lines => \@diff_lines,
125 has_live_diff => scalar(@diff_lines) ? 1 : 0,
126 diff_add => $diff_add,
127 diff_del => $diff_del,
128 diff_ctx => scalar(@diff_lines) - $diff_add - $diff_del,
111129};
112130
113131print "Content-Type: text/html; charset=utf-8\nCache-Control: no-cache\n\n";
114132my @body = $tpl->template('restore.html', $tvars);
115133MODS::PageWrapper->new->wrapper(
116134 page_title => 'Restore', page_key => '',
117135 body_html => join('', @body), userinfo => { display_name => 'Operator' },
118136);
119137$db->db_disconnect($dbh);
120138exit;
121139
122140#======================================================================
123141sub _load_change_row {
124142 my ($dbh, $id) = @_;
125143 return undef unless $id > 0;
126144 return $db->db_readwrite($dbh, qq~
127145 SELECT fc.file_changes_id AS id,
128146 fc.file_monitor_list_id, fc.server_id,
129147 fc.file_name, fc.blob_sha, fc.status, fc.date_time,
130148 UNIX_TIMESTAMP(fc.date_time) AS ts_epoch,
131149 s.server_name, s.kind AS server_kind,
132150 s.ssh_host, s.ssh_user, s.ssh_port,
133151 s.ssh_key_path, s.ssh_options,
134152 s.ssh_key_blob
135153 FROM FILE_CHANGES fc
136154 LEFT JOIN SERVERS s ON s.server_id = fc.server_id
137155 WHERE fc.file_changes_id = $id
138156 LIMIT 1
139157 ~, __FILE__, __LINE__);
140158}
141159
142160sub _load_monitor {
143161 my ($dbh, $mid) = @_;
144162 return undef unless $mid;
145163 return $db->db_readwrite($dbh, qq~
146164 SELECT file_monitor_list_id, scan_path, scan_name, server_id
147165 FROM FILE_MONITOR_SETTINGS
148166 WHERE file_monitor_list_id = $mid
149167 LIMIT 1
150168 ~, __FILE__, __LINE__);
151169}
152170
153171sub _fetch_blob {
154172 my ($dbh, $sha) = @_;
155173 return undef unless $sha;
156174 my $sth = $dbh->prepare("SELECT content_gz FROM BLOB_STORE WHERE blob_sha = ?");
157175 return undef unless $sth && $sth->execute($sha);
158176 my $r = $sth->fetchrow_arrayref;
159177 $sth->finish;
160178 return undef unless $r && $r->[0];
161179 return eval { uncompress($r->[0]) };
162180}
163181
164182#---------------------------------------------------------------------
165183# _peek_current($row, $monitor) -> ($sha, $exists, $size)
166184# For local: stat + hash the current on-disk content.
167185# For ssh_agent: SSH and sha256sum + wc -c.
168186#---------------------------------------------------------------------
169187sub _peek_current {
170188 my ($row, $monitor) = @_;
171189 my $path = $row->{file_name};
172190 if (($row->{server_kind} // 'local') eq 'local') {
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);
191 return (undef, 0, undef, undef) unless -e $path;
192 return (undef, 1, -s $path, undef) unless -r $path;
193 open(my $fh, '<:raw', $path) or return (undef, 1, -s $path, undef);
176194 local $/; my $c = <$fh>; close $fh;
177 return (sha256_hex($c), 1, length $c);
195 return (sha256_hex($c), 1, length $c, $c);
178196 }
179197 # SSH agent
180198 my ($rc, $out, $err) = _ssh_run($row, "test -f " . _sh_quote($path) . " && sha256sum " . _sh_quote($path) . " && wc -c < " . _sh_quote($path));
181199 if ($rc != 0) {
182 return (undef, 0, undef);
200 return (undef, 0, undef, undef);
183201 }
184202 my @lines = split /\n/, $out;
185203 my $sha;
186204 my $size;
187205 foreach my $l (@lines) {
188206 if ($l =~ /^([0-9a-f]{64})\s/) { $sha = $1; }
189207 elsif ($l =~ /^(\d+)$/) { $size = int($1); }
190208 }
191 return ($sha, 1, $size);
209 # Fetch content over SSH for the live diff -- capped at 512 KB
210 my $content;
211 if ($sha && $size && $size < 512_000) {
212 my ($rc2, $out2, $err2) = _ssh_run($row, "cat " . _sh_quote($path));
213 $content = $out2 if $rc2 == 0;
214 }
215 return ($sha, 1, $size, $content);
192216}
193217
194218#---------------------------------------------------------------------
195219# _do_restore($dbh, $row, $monitor) -> { status, message, backup_path }
196220#---------------------------------------------------------------------
197221sub _do_restore {
198222 my ($dbh, $row, $monitor) = @_;
199223 my $blob_sha = $row->{blob_sha};
200224 unless ($blob_sha) {
201225 return { status => 'failed', message => 'source change has no blob_sha' };
202226 }
203227 my $content = _fetch_blob($dbh, $blob_sha);
204228 unless (defined $content) {
205229 return { status => 'failed', message => "blob $blob_sha not in BLOB_STORE" };
206230 }
207231
208232 my $stamp = time();
209233 my $backup = "$row->{file_name}.drift_restore_backup_$stamp";
210234
211235 if (($row->{server_kind} // 'local') eq 'local') {
212236 # Local restore -- backup then write
213237 if (-e $row->{file_name}) {
214238 unless (rename($row->{file_name}, $backup)) {
215239 # Fallback: cp to backup, then overwrite in place
216240 open(my $src, '<:raw', $row->{file_name}) or return {
217241 status => 'failed',
218242 message => "cannot read current file: $!"
219243 };
220244 open(my $bak, '>:raw', $backup) or return {
221245 status => 'failed',
222246 message => "cannot write backup: $!"
223247 };
224248 local $/; print {$bak} <$src>;
225249 close $src; close $bak;
226250 }
227251 } else {
228252 $backup = ''; # nothing to back up
229253 }
230254 # Write new content
231255 open(my $out, '>:raw', $row->{file_name}) or return {
232256 status => 'failed',
233257 message => "write failed: $!",
234258 backup_path => $backup,
235259 };
236260 print {$out} $content;
237261 close $out;
238262 # Verify SHA post-write
239263 open(my $v, '<:raw', $row->{file_name});
240264 local $/; my $verify = <$v>; close $v;
241265 my $vsha = sha256_hex($verify);
242266 if ($vsha ne $blob_sha) {
243267 return {
244268 status => 'failed',
245269 message => "post-write SHA mismatch: $vsha vs $blob_sha",
246270 backup_path => $backup,
247271 };
248272 }
249273 return {
250274 status => 'success',
251275 message => "restored " . length($content) . " bytes",
252276 backup_path => $backup,
253277 };
254278 }
255279
256280 # SSH agent restore
257281 # Step 1: cp current to backup (best-effort)
258282 my ($rc, $out, $err) = _ssh_run($row,
259283 "test -f " . _sh_quote($row->{file_name}) .
260284 " && cp -p " . _sh_quote($row->{file_name}) . " " . _sh_quote($backup) .
261285 " ; echo done");
262286 if ($rc != 0) {
263287 $backup = ''; # backup failed but we'll still try the restore
264288 }
265289
266290 # Step 2: write content via SSH stdin
267291 my $ok = _ssh_write($row, $row->{file_name}, $content);
268292 unless ($ok) {
269293 return {
270294 status => 'failed',
271295 message => "ssh write failed",
272296 backup_path => $backup,
273297 };
274298 }
275299
276300 # Step 3: Verify SHA remotely
277301 ($rc, $out, $err) = _ssh_run($row, "sha256sum " . _sh_quote($row->{file_name}));
278302 my $vsha = ($out =~ /^([0-9a-f]{64})\s/) ? $1 : '';
279303 if ($vsha ne $blob_sha) {
280304 return {
281305 status => 'failed',
282306 message => "post-write remote SHA mismatch: $vsha vs $blob_sha",
283307 backup_path => $backup,
284308 };
285309 }
286310 return {
287311 status => 'success',
288312 message => "remote restored " . length($content) . " bytes",
289313 backup_path => $backup,
290314 };
291315}
292316
293317#---------------------------------------------------------------------
294318sub _log_restore {
295319 my ($dbh, $row, $result) = @_;
296320 my $q_file = $dbh->quote($row->{file_name} // '');
297321 my $q_sha = $dbh->quote($row->{blob_sha} // '');
298322 my $q_bak = $dbh->quote($result->{backup_path} // '');
299323 my $q_stat = $dbh->quote($result->{status} // 'failed');
300324 my $q_err = $dbh->quote($result->{status} eq 'success' ? '' : ($result->{message} // ''));
301325 my $sid = int($row->{server_id} || 0);
302326 my $cid = int($row->{id} || 0);
303327 $db->db_readwrite($dbh, qq~
304328 INSERT INTO RESTORE_LOG
305329 (source_change_id, server_id, target_file, source_blob_sha,
306330 backup_path, status, error_message)
307331 VALUES
308332 ($cid, $sid, $q_file, $q_sha, $q_bak, $q_stat, $q_err)
309333 ~, __FILE__, __LINE__);
310334}
311335
312336#---------------------------------------------------------------------
313337# SSH helpers -- resolve key (encrypted blob or on-disk), spawn ssh
314338#---------------------------------------------------------------------
315339sub _ssh_argv {
316340 my ($row) = @_;
317341 my $user = $row->{ssh_user} || 'root';
318342 my $host = $row->{ssh_host};
319343 my $port = $row->{ssh_port} || 22;
320344 my $key_path = $row->{ssh_key_path} || '';
321345 my $tmp_key;
322346
323347 if ($row->{ssh_key_blob}) {
324348 my $pem = eval { MODS::Crypto::decrypt($row->{ssh_key_blob}) };
325349 if ($pem) {
326350 my $t = time();
327351 my $p = "/tmp/.ds_restore_key_${t}_$$_" . int(rand(1_000_000));
328352 if (sysopen(my $fh, $p,
329353 Fcntl::O_WRONLY() | Fcntl::O_CREAT() | Fcntl::O_EXCL(), 0600)) {
330354 print $fh $pem; close $fh;
331355 $key_path = $p;
332356 $tmp_key = $p;
333357 }
334358 }
335359 }
336360
337361 my @argv = ('/usr/bin/ssh',
338362 '-o', 'BatchMode=yes',
339363 '-o', 'StrictHostKeyChecking=no',
340364 '-o', 'UserKnownHostsFile=/dev/null',
341365 '-o', 'LogLevel=ERROR',
342366 '-o', 'ConnectTimeout=8',
343367 '-p', $port);
344368 push @argv, '-i', $key_path if $key_path && -r $key_path;
345369 if ($row->{ssh_options}) {
346370 foreach my $o (split /\s+/, $row->{ssh_options}) {
347371 push @argv, '-o', $o if length $o;
348372 }
349373 }
350374 push @argv, "$user\@$host";
351375 return (\@argv, $tmp_key);
352376}
353377
354378sub _ssh_run {
355379 my ($row, $cmd) = @_;
356380 my ($base, $tmp_key) = _ssh_argv($row);
357381 my @full = (@$base, $cmd);
358382 my ($wtr, $rdr, $err_fh);
359383 $err_fh = gensym;
360384 my $pid = eval { open3($wtr, $rdr, $err_fh, @full) };
361385 if ($@ || !$pid) {
362386 unlink $tmp_key if $tmp_key;
363387 return (-1, '', $@);
364388 }
365389 close $wtr;
366390 my $out = do { local $/; <$rdr> // '' };
367391 my $err = do { local $/; <$err_fh> // '' };
368392 close $rdr; close $err_fh;
369393 waitpid $pid, 0;
370394 my $rc = $? >> 8;
371395 unlink $tmp_key if $tmp_key;
372396 return ($rc, $out, $err);
373397}
374398
375399sub _ssh_write {
376400 my ($row, $path, $content) = @_;
377401 my ($base, $tmp_key) = _ssh_argv($row);
378402 # `cat > $path` on the remote side, content on stdin
379403 my @full = (@$base, "cat > " . _sh_quote($path));
380404 my ($wtr, $rdr, $err_fh);
381405 $err_fh = gensym;
382406 my $pid = eval { open3($wtr, $rdr, $err_fh, @full) };
383407 if ($@ || !$pid) {
384408 unlink $tmp_key if $tmp_key;
385409 return 0;
386410 }
387411 binmode $wtr;
388412 print {$wtr} $content;
389413 close $wtr;
390414 my $out = do { local $/; <$rdr> // '' };
391415 my $err = do { local $/; <$err_fh> // '' };
392416 close $rdr; close $err_fh;
393417 waitpid $pid, 0;
394418 my $rc = $? >> 8;
395419 unlink $tmp_key if $tmp_key;
396420 return $rc == 0 ? 1 : 0;
397421}
398422
399423sub _sh_quote {
400424 my $s = shift; $s //= '';
401425 $s =~ s/'/'\\''/g;
402426 return "'$s'";
403427}
404428
405429sub _render_error {
406430 my ($msg) = @_;
407431 print "Content-Type: text/html; charset=utf-8\nCache-Control: no-cache\n\n";
408432 my @body = $tpl->template('restore.html', {
409433 error_msg => $msg,
410434 has_error => 1,
411435 did_restore => 0,
412436 });
413437 MODS::PageWrapper->new->wrapper(
414438 page_title => 'Restore', page_key => '',
415439 body_html => join('', @body), userinfo => { display_name => 'Operator' },
416440 );
417441 exit;
418442}