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

O Operator
Diff

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

added on local at 2026-07-11 23:34:31

Added
+418
lines
Removed
-0
lines
Context
0
unchanged
Blobs
from
to 1ea1f8830b27
Restore this content →
Unified diff
Naive LCS-based line diff. Additions in emerald, deletions in rose. Both sides decompressed live from BLOB_STORE.
1#!/usr/bin/perl
2#======================================================================
3# DriftSense -- /restore.cgi
4#
5# Restore a captured file to its original path. Two flavors:
6# Local (server.kind = local) -> write blob to target path directly
7# Agent (server.kind = ssh_agent) -> pipe blob content over SSH to target
8#
9# Safety:
10# - GET /restore.cgi?id=N -> preview page (dry-run details)
11# - POST /restore.cgi id=N confirm=1 -> perform the restore
12#
13# * Path must be inside a configured FILE_MONITOR_SETTINGS.scan_path
14# for that server (prevents restoring blob to /etc/passwd from a
15# tampered FILE_CHANGES row).
16# * Current file content is backed up to
17# $target.drift_restore_backup_$UNIX_TIMESTAMP before overwrite.
18# * Every attempt (success, failure, dry_run) is logged to RESTORE_LOG.
19#======================================================================
20use strict;
21use warnings;
22use CGI ();
23use IPC::Open3;
24use Symbol 'gensym';
25use Fcntl ();
26use POSIX ();
27use Compress::Zlib qw(uncompress);
28use Digest::SHA qw(sha256_hex);
29use MODS::Config;
30use MODS::DBConnect;
31use MODS::Template;
32use MODS::PageWrapper;
33use MODS::Crypto;
34
35my $cgi = CGI->new;
36my $db = MODS::DBConnect->new;
37my $tpl = MODS::Template->new;
38$|=1;
39
40my $dbh = $db->db_connect or die "DriftSense: DB connect failed\n";
41
42my $method = $ENV{REQUEST_METHOD} || 'GET';
43my $id = int($cgi->param('id') || 0);
44
45# ---- Load the source change row -------------------------------------
46my $row = _load_change_row($dbh, $id);
47unless ($row && $row->{id}) {
48 _render_error("Change #$id not found");
49}
50
51# ---- Path safety: target file must be inside a monitored scan_path --
52my $monitor = _load_monitor($dbh, $row->{file_monitor_list_id});
53my $path_ok = 0;
54if ($monitor && $monitor->{scan_path}) {
55 my $sp = $monitor->{scan_path};
56 $sp =~ s!/+$!!;
57 $path_ok = 1 if index($row->{file_name}, "$sp/") == 0 || $row->{file_name} eq $sp;
58}
59unless ($path_ok) {
60 _render_error("Target path <code>$row->{file_name}</code> is outside its monitor's configured scan_path; refusing to restore.");
61}
62
63# ---- If POST, perform the restore ----------------------------------
64if ($method eq 'POST' && $cgi->param('confirm')) {
65 my $result = _do_restore($dbh, $row, $monitor);
66 _log_restore($dbh, $row, $result);
67
68 # Render result page
69 my $tvars = {
70 id => $id,
71 target_file => $row->{file_name},
72 server_name => $row->{server_name} // 'local',
73 server_kind => $row->{server_kind} // 'local',
74 source_sha => substr($row->{blob_sha} // '', 0, 12),
75 captured_h => $row->{date_time} // '',
76 captured_epoch => int($row->{ts_epoch} || 0),
77 result_status => $result->{status},
78 result_ok => $result->{status} eq 'success' ? 1 : 0,
79 result_msg => $result->{message} // '',
80 backup_path => $result->{backup_path} // '',
81 did_restore => 1,
82 };
83 print "Content-Type: text/html; charset=utf-8\nCache-Control: no-cache\n\n";
84 my @body = $tpl->template('restore.html', $tvars);
85 MODS::PageWrapper->new->wrapper(
86 page_title => 'Restore', page_key => '',
87 body_html => join('', @body), userinfo => { display_name => 'Operator' },
88 );
89 $db->db_disconnect($dbh);
90 exit;
91}
92
93# ---- GET: preview page ---------------------------------------------
94my ($current_sha, $current_exists, $current_size) = _peek_current($row, $monitor);
95my $tvars = {
96 id => $id,
97 target_file => $row->{file_name},
98 server_name => $row->{server_name} // 'local',
99 server_kind => $row->{server_kind} // 'local',
100 scan_name => $monitor->{scan_name} // '',
101 source_sha => substr($row->{blob_sha} // '', 0, 12),
102 source_sha_full=> $row->{blob_sha} // '',
103 captured_h => $row->{date_time} // '',
104 captured_epoch => int($row->{ts_epoch} || 0),
105 current_sha => substr($current_sha // '', 0, 12),
106 current_exists => $current_exists,
107 current_size => defined($current_size) ? "$current_size bytes" : 'unknown',
108 same_content => ($current_sha && $current_sha eq ($row->{blob_sha} // '')) ? 1 : 0,
109 did_restore => 0,
110 diff_url => "/diff.cgi?kind=file&id=$id",
111};
112
113print "Content-Type: text/html; charset=utf-8\nCache-Control: no-cache\n\n";
114my @body = $tpl->template('restore.html', $tvars);
115MODS::PageWrapper->new->wrapper(
116 page_title => 'Restore', page_key => '',
117 body_html => join('', @body), userinfo => { display_name => 'Operator' },
118);
119$db->db_disconnect($dbh);
120exit;
121
122#======================================================================
123sub _load_change_row {
124 my ($dbh, $id) = @_;
125 return undef unless $id > 0;
126 return $db->db_readwrite($dbh, qq~
127 SELECT fc.file_changes_id AS id,
128 fc.file_monitor_list_id, fc.server_id,
129 fc.file_name, fc.blob_sha, fc.status, fc.date_time,
130 UNIX_TIMESTAMP(fc.date_time) AS ts_epoch,
131 s.server_name, s.kind AS server_kind,
132 s.ssh_host, s.ssh_user, s.ssh_port,
133 s.ssh_key_path, s.ssh_options,
134 s.ssh_key_blob
135 FROM FILE_CHANGES fc
136 LEFT JOIN SERVERS s ON s.server_id = fc.server_id
137 WHERE fc.file_changes_id = $id
138 LIMIT 1
139 ~, __FILE__, __LINE__);
140}
141
142sub _load_monitor {
143 my ($dbh, $mid) = @_;
144 return undef unless $mid;
145 return $db->db_readwrite($dbh, qq~
146 SELECT file_monitor_list_id, scan_path, scan_name, server_id
147 FROM FILE_MONITOR_SETTINGS
148 WHERE file_monitor_list_id = $mid
149 LIMIT 1
150 ~, __FILE__, __LINE__);
151}
152
153sub _fetch_blob {
154 my ($dbh, $sha) = @_;
155 return undef unless $sha;
156 my $sth = $dbh->prepare("SELECT content_gz FROM BLOB_STORE WHERE blob_sha = ?");
157 return undef unless $sth && $sth->execute($sha);
158 my $r = $sth->fetchrow_arrayref;
159 $sth->finish;
160 return undef unless $r && $r->[0];
161 return eval { uncompress($r->[0]) };
162}
163
164#---------------------------------------------------------------------
165# _peek_current($row, $monitor) -> ($sha, $exists, $size)
166# For local: stat + hash the current on-disk content.
167# For ssh_agent: SSH and sha256sum + wc -c.
168#---------------------------------------------------------------------
169sub _peek_current {
170 my ($row, $monitor) = @_;
171 my $path = $row->{file_name};
172 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);
176 local $/; my $c = <$fh>; close $fh;
177 return (sha256_hex($c), 1, length $c);
178 }
179 # SSH agent
180 my ($rc, $out, $err) = _ssh_run($row, "test -f " . _sh_quote($path) . " && sha256sum " . _sh_quote($path) . " && wc -c < " . _sh_quote($path));
181 if ($rc != 0) {
182 return (undef, 0, undef);
183 }
184 my @lines = split /\n/, $out;
185 my $sha;
186 my $size;
187 foreach my $l (@lines) {
188 if ($l =~ /^([0-9a-f]{64})\s/) { $sha = $1; }
189 elsif ($l =~ /^(\d+)$/) { $size = int($1); }
190 }
191 return ($sha, 1, $size);
192}
193
194#---------------------------------------------------------------------
195# _do_restore($dbh, $row, $monitor) -> { status, message, backup_path }
196#---------------------------------------------------------------------
197sub _do_restore {
198 my ($dbh, $row, $monitor) = @_;
199 my $blob_sha = $row->{blob_sha};
200 unless ($blob_sha) {
201 return { status => 'failed', message => 'source change has no blob_sha' };
202 }
203 my $content = _fetch_blob($dbh, $blob_sha);
204 unless (defined $content) {
205 return { status => 'failed', message => "blob $blob_sha not in BLOB_STORE" };
206 }
207
208 my $stamp = time();
209 my $backup = "$row->{file_name}.drift_restore_backup_$stamp";
210
211 if (($row->{server_kind} // 'local') eq 'local') {
212 # Local restore -- backup then write
213 if (-e $row->{file_name}) {
214 unless (rename($row->{file_name}, $backup)) {
215 # Fallback: cp to backup, then overwrite in place
216 open(my $src, '<:raw', $row->{file_name}) or return {
217 status => 'failed',
218 message => "cannot read current file: $!"
219 };
220 open(my $bak, '>:raw', $backup) or return {
221 status => 'failed',
222 message => "cannot write backup: $!"
223 };
224 local $/; print {$bak} <$src>;
225 close $src; close $bak;
226 }
227 } else {
228 $backup = ''; # nothing to back up
229 }
230 # Write new content
231 open(my $out, '>:raw', $row->{file_name}) or return {
232 status => 'failed',
233 message => "write failed: $!",
234 backup_path => $backup,
235 };
236 print {$out} $content;
237 close $out;
238 # Verify SHA post-write
239 open(my $v, '<:raw', $row->{file_name});
240 local $/; my $verify = <$v>; close $v;
241 my $vsha = sha256_hex($verify);
242 if ($vsha ne $blob_sha) {
243 return {
244 status => 'failed',
245 message => "post-write SHA mismatch: $vsha vs $blob_sha",
246 backup_path => $backup,
247 };
248 }
249 return {
250 status => 'success',
251 message => "restored " . length($content) . " bytes",
252 backup_path => $backup,
253 };
254 }
255
256 # SSH agent restore
257 # Step 1: cp current to backup (best-effort)
258 my ($rc, $out, $err) = _ssh_run($row,
259 "test -f " . _sh_quote($row->{file_name}) .
260 " && cp -p " . _sh_quote($row->{file_name}) . " " . _sh_quote($backup) .
261 " ; echo done");
262 if ($rc != 0) {
263 $backup = ''; # backup failed but we'll still try the restore
264 }
265
266 # Step 2: write content via SSH stdin
267 my $ok = _ssh_write($row, $row->{file_name}, $content);
268 unless ($ok) {
269 return {
270 status => 'failed',
271 message => "ssh write failed",
272 backup_path => $backup,
273 };
274 }
275
276 # Step 3: Verify SHA remotely
277 ($rc, $out, $err) = _ssh_run($row, "sha256sum " . _sh_quote($row->{file_name}));
278 my $vsha = ($out =~ /^([0-9a-f]{64})\s/) ? $1 : '';
279 if ($vsha ne $blob_sha) {
280 return {
281 status => 'failed',
282 message => "post-write remote SHA mismatch: $vsha vs $blob_sha",
283 backup_path => $backup,
284 };
285 }
286 return {
287 status => 'success',
288 message => "remote restored " . length($content) . " bytes",
289 backup_path => $backup,
290 };
291}
292
293#---------------------------------------------------------------------
294sub _log_restore {
295 my ($dbh, $row, $result) = @_;
296 my $q_file = $dbh->quote($row->{file_name} // '');
297 my $q_sha = $dbh->quote($row->{blob_sha} // '');
298 my $q_bak = $dbh->quote($result->{backup_path} // '');
299 my $q_stat = $dbh->quote($result->{status} // 'failed');
300 my $q_err = $dbh->quote($result->{status} eq 'success' ? '' : ($result->{message} // ''));
301 my $sid = int($row->{server_id} || 0);
302 my $cid = int($row->{id} || 0);
303 $db->db_readwrite($dbh, qq~
304 INSERT INTO RESTORE_LOG
305 (source_change_id, server_id, target_file, source_blob_sha,
306 backup_path, status, error_message)
307 VALUES
308 ($cid, $sid, $q_file, $q_sha, $q_bak, $q_stat, $q_err)
309 ~, __FILE__, __LINE__);
310}
311
312#---------------------------------------------------------------------
313# SSH helpers -- resolve key (encrypted blob or on-disk), spawn ssh
314#---------------------------------------------------------------------
315sub _ssh_argv {
316 my ($row) = @_;
317 my $user = $row->{ssh_user} || 'root';
318 my $host = $row->{ssh_host};
319 my $port = $row->{ssh_port} || 22;
320 my $key_path = $row->{ssh_key_path} || '';
321 my $tmp_key;
322
323 if ($row->{ssh_key_blob}) {
324 my $pem = eval { MODS::Crypto::decrypt($row->{ssh_key_blob}) };
325 if ($pem) {
326 my $t = time();
327 my $p = "/tmp/.ds_restore_key_${t}_$$_" . int(rand(1_000_000));
328 if (sysopen(my $fh, $p,
329 Fcntl::O_WRONLY() | Fcntl::O_CREAT() | Fcntl::O_EXCL(), 0600)) {
330 print $fh $pem; close $fh;
331 $key_path = $p;
332 $tmp_key = $p;
333 }
334 }
335 }
336
337 my @argv = ('/usr/bin/ssh',
338 '-o', 'BatchMode=yes',
339 '-o', 'StrictHostKeyChecking=no',
340 '-o', 'UserKnownHostsFile=/dev/null',
341 '-o', 'LogLevel=ERROR',
342 '-o', 'ConnectTimeout=8',
343 '-p', $port);
344 push @argv, '-i', $key_path if $key_path && -r $key_path;
345 if ($row->{ssh_options}) {
346 foreach my $o (split /\s+/, $row->{ssh_options}) {
347 push @argv, '-o', $o if length $o;
348 }
349 }
350 push @argv, "$user\@$host";
351 return (\@argv, $tmp_key);
352}
353
354sub _ssh_run {
355 my ($row, $cmd) = @_;
356 my ($base, $tmp_key) = _ssh_argv($row);
357 my @full = (@$base, $cmd);
358 my ($wtr, $rdr, $err_fh);
359 $err_fh = gensym;
360 my $pid = eval { open3($wtr, $rdr, $err_fh, @full) };
361 if ($@ || !$pid) {
362 unlink $tmp_key if $tmp_key;
363 return (-1, '', $@);
364 }
365 close $wtr;
366 my $out = do { local $/; <$rdr> // '' };
367 my $err = do { local $/; <$err_fh> // '' };
368 close $rdr; close $err_fh;
369 waitpid $pid, 0;
370 my $rc = $? >> 8;
371 unlink $tmp_key if $tmp_key;
372 return ($rc, $out, $err);
373}
374
375sub _ssh_write {
376 my ($row, $path, $content) = @_;
377 my ($base, $tmp_key) = _ssh_argv($row);
378 # `cat > $path` on the remote side, content on stdin
379 my @full = (@$base, "cat > " . _sh_quote($path));
380 my ($wtr, $rdr, $err_fh);
381 $err_fh = gensym;
382 my $pid = eval { open3($wtr, $rdr, $err_fh, @full) };
383 if ($@ || !$pid) {
384 unlink $tmp_key if $tmp_key;
385 return 0;
386 }
387 binmode $wtr;
388 print {$wtr} $content;
389 close $wtr;
390 my $out = do { local $/; <$rdr> // '' };
391 my $err = do { local $/; <$err_fh> // '' };
392 close $rdr; close $err_fh;
393 waitpid $pid, 0;
394 my $rc = $? >> 8;
395 unlink $tmp_key if $tmp_key;
396 return $rc == 0 ? 1 : 0;
397}
398
399sub _sh_quote {
400 my $s = shift; $s //= '';
401 $s =~ s/'/'\\''/g;
402 return "'$s'";
403}
404
405sub _render_error {
406 my ($msg) = @_;
407 print "Content-Type: text/html; charset=utf-8\nCache-Control: no-cache\n\n";
408 my @body = $tpl->template('restore.html', {
409 error_msg => $msg,
410 has_error => 1,
411 did_restore => 0,
412 });
413 MODS::PageWrapper->new->wrapper(
414 page_title => 'Restore', page_key => '',
415 body_html => join('', @body), userinfo => { display_name => 'Operator' },
416 );
417 exit;
418}