Subversion Repositories zfs_utils

Rev

Rev 25 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
24 rodolico 1
package ZFS_Utils;
2
 
3
use strict;
4
use warnings;
5
use Exporter 'import';
6
use Data::Dumper;
7
use POSIX qw(strftime);
8
use File::Path qw(make_path);
9
 
10
our @EXPORT_OK = qw(loadConfig shredFile mountDriveByLabel mountGeli logMsg $logFileName $displayLogsOnConsole);
11
 
12
 
13
our $VERSION = '0.1';
14
our $logFileName = '/tmp/zfs_utils.log'; # this can be overridden by the caller, and turned off with empty string
15
our $displayLogsOnConsole = 1;
16
 
17
# this calls gshred which will overwrite the file 3 times, then
18
# remove it.
19
# NOTE: this will not work on ZFS, since ZFS is CopyOnWrite (COW)
20
# so assuming file is on something without COW (ramdisk, UFS, etc)
21
sub shredFile {
22
   my $filename = shift;
23
   `/usr/local/bin/gshred -u -f -s 32 $filename` if -e $filename;
24
}
25
 
26
sub logMsg {
27
    my $msg = shift;
28
    my $filename = shift // $logFileName;
29
    my $timeStampFormat = shift // '%Y-%m-%d %H:%M:%S';
30
    my $timestamp = strftime($timeStampFormat, localtime());
31
    if (defined $filename && $filename ne '' ) {
32
       open my $logfh, '>>', $filename or die "Could not open log file $filename: $!\n";
33
       print $logfh "$timestamp\t$msg\n";
34
       close $logfh;
35
    }
36
    print "$timestamp\t$msg\n" if ($displayLogsOnConsole);
37
}
38
 
39
# find a drive by it's label by scanning /dev/gpt/ for $timeout seconds.
40
# If the drive is found, mount it on mountPath and return the mountPath.
41
# If not found, return empty string.
42
sub mountDriveByLabel {
43
   my ($label, $mountPath, $timeout, $checkEvery ) = @_;
44
   unless ($label) {
45
      logMsg("mountDriveByLabel: No label provided");
46
      return '';
47
   }
48
   unless ( $label =~ /^[a-zA-Z0-9_\-]+$/ ) {
49
      logMsg("mountDriveByLabel: Invalid label '$label'");
50
      return '';
51
   }
52
 
53
   logMsg("mountDriveByLabel: Looking for drive with label '$label'");
54
   # default to /mnt/label if not provided
55
   $mountPath //= "/mnt/$label"; # this is where we'll mount it if we find it
56
   $label = "/dev/gpt/$label"; #  this is where FreeBSD puts gpt labeled drives
57
   # default to 10 minutes (600 seconds) if not provided
58
   $timeout //= 600;
59
   # default to checking every minute if not provided
60
   $checkEvery //= 60;
61
   # wait up to $timeout seconds for device to appear, checking every 10 seconds
62
   while ( $timeout > 0 ) {
63
      if ( -e "$label" ) {
64
         last;
65
      } else {
66
         sleep $checkEvery;
67
         $timeout -= $checkEvery;
68
      }
69
    }
70
    # if we found it, mount and return mount path
71
    if ( -e "$label" ) {
72
       # ensure mount point
73
       unless ( -d $mountPath || make_path($mountPath) ) {
74
         logMsg("Failed to create $mountPath: $!");
75
         return '';
76
       }
77
       # mount device (let mount detect filesystem)
78
       unless ( system('mount', $label, $mountPath) == 0 ) {
79
         logMsg("Failed to mount $label on $mountPath: $!");
80
         return '';
81
       }
82
       return $mountPath;
83
    } else {
84
       return '';
85
    }
86
}
87
 
88
## Load a YAML configuration file into a hashref.
89
## If the file does not exist, and a default hashref is provided,
90
## create the file by dumping the default to YAML, then return the default.
91
sub loadConfig {
92
    my ($filename, $default) = @_;
93
 
94
    # If no filename was provided, return default or empty hashref
95
    die "No filename provided to loadConfig\n" unless defined $filename;
96
 
97
    # If file doesn't exist but a default hashref was provided, try to
98
    # create the file by dumping the default to YAML, then return the default.
99
    unless (-e $filename) {
100
      logMsg("Config file $filename does not exist. Creating it with default values.");
101
      if ($default && ref $default eq 'HASH') {
102
         my $wrote = 0;
103
         eval {
104
               require YAML::XS;
105
               YAML::XS->import();
106
               YAML::XS::DumpFile($filename, $default);
107
               $wrote = 1;
108
               1;
109
         } or do {
110
               eval {
111
                  require YAML::Tiny;
112
                  YAML::Tiny->import();
113
                  my $yt = YAML::Tiny->new($default);
114
                  $yt->write($filename);
115
                  $wrote = 1;
116
                  1;
117
               } or do {
118
                  logMsg("No YAML writer available (YAML::XS or YAML::Tiny). Could not create $filename");
119
               };
120
         };
121
 
122
         die "Failed to write default config to $filename:$!\n" unless $wrote;
123
        }
124
 
125
        # No default provided; nothing to create
126
        return {};
127
    }
128
 
129
    my $yaml;
130
 
131
    # Try YAML::XS first, fall back to YAML::Tiny
132
    eval {
133
        require YAML::XS;
134
        YAML::XS->import();
135
        $yaml = YAML::XS::LoadFile($filename);
136
        logMsg("using YAML::XS to load $filename");
137
        1;
138
    } or do {
139
        eval {
140
            require YAML::Tiny;
141
            YAML::Tiny->import();
142
            $yaml = YAML::Tiny->read($filename);
143
            $yaml = $yaml->[0] if $yaml;  # YAML::Tiny returns an arrayref of documents
144
            logMsg("using YAML::Tiny to load $filename");
145
            1;
146
        } or do {
147
            logMsg("No YAML parser installed (YAML::XS or YAML::Tiny). Skipping config load from $filename");
148
            return ($default && ref $default eq 'HASH') ? $default : {};
149
        };
150
    };
151
 
152
    # Ensure we have a hashref
153
    die "Config file $filename did not produce a HASH.\n" unless (defined $yaml && ref $yaml eq 'HASH');
154
 
155
    return $yaml;
156
}
157
 
158
 
159
 
160
sub mountGeli {
161
   my $geliConfig = shift;
162
   unless ( -e $geliConfig->{'localKey'} ) {
163
      logMsg "Could not find local key file: " . $geliConfig->{'localKey'} . "\n";
164
      return '';
165
   }
166
   # find the keyfile disk and mount it
167
   my $path = mountDriveByLabel( $geliConfig->{'keydiskname'} );
168
   unless ( $path ne '' and -e "$path/" . $geliConfig->{'keyfile'} ) {
169
      logMsg "Could not find or mount keyfile disk with label: " . $geliConfig->{'keydiskname'} . "\n";
170
      return '';
171
   }
172
   # create the combined geli keyfile in target location
173
   unless ( makeGeliKey( "$path/" . $geliConfig->{'keyfile'}, $geliConfig->{'localKey'}, $geliConfig->{'target'} ) ) {
174
         logMsg "Could not create geli keyfile\n";
175
         return '';
176
      }
177
   # decrypt and mount the geli disks and zfs pool
178
   my $poolname = decryptAndMountGeli( $geliConfig );
179
   return $poolname;
180
 
181
}
182
 
183
## Decrypt each GELI disk from $geliConfig->{'diskList'} using the keyfile,
184
## then import and mount the ZFS pool specified in $geliConfig->{'poolname'}.
185
##
186
## Returns the pool name on success, empty on error.
187
sub decryptAndMountGeli {
188
   my ($geliConfig) = @_;
189
   # these are configuration sanity checks, so die if they fail
190
   die "No disk list found in GELI config\n" unless $geliConfig->{'diskList'};
191
   die "No pool name specified in config\n" unless $geliConfig->{'poolname'};
192
 
193
   my $diskList = $geliConfig->{'diskList'};
194
   my $poolname = $geliConfig->{'poolname'};
195
   my $keyfile = $geliConfig->{'target'};
196
   unless ( -e $keyfile ) {
197
      logMsg "GELI keyfile $keyfile does not exist\n";
198
      return '';
199
   }
200
 
201
   my @decrypted_devices;
202
 
203
   # Decrypt each disk in the list
204
   foreach my $disk (@{$diskList}) {
205
      unless ( -e $disk ) {
206
         logMsg "Disk $disk does not exist\n";
207
         return '';
208
      }
209
 
210
      # Derive the decrypted device name (.eli suffix on FreeBSD)
211
      my $decrypted = $disk . '.eli';
212
 
213
      # Decrypt using geli attach with the keyfile
214
      logMsg("Decrypting $disk with keyfile $keyfile");
215
      if ( my $result = system('geli', 'attach', '-k', $keyfile, $disk) == 0 ) {
216
         logMsg "Failed to decrypt $disk (exit $result)\n";
217
         return '';
218
      }
219
 
220
      unless ( -e $decrypted ) {
221
         logMsg "Decrypted device $decrypted does not exist after geli attach\n";
222
         return '';
223
      }
224
      push @decrypted_devices, $decrypted;
225
   }
226
 
227
   # Import the ZFS pool
228
   logMsg("Importing ZFS pool $poolname");
229
   my @import_cmd = ('zpool', 'import');
230
   # If decrypted devices exist, add their directories to -d list
231
   foreach my $dev (@decrypted_devices) {
232
      my $dir = $dev;
233
      $dir =~ s!/[^/]+$!!;  # Remove filename to get directory
234
      push @import_cmd, '-d', $dir;
235
   }
236
   push @import_cmd, $poolname;
237
 
238
   my $result = system(@import_cmd);
239
   unless ( $result == 0 ) {
240
      logMsg("Failed to import zfs pool $poolname (exit $result)\n");
241
      return '';
242
   }
243
 
244
   # Mount the ZFS pool (zfs mount -a mounts all filesystems in the pool)
245
   logMsg("Mounting ZFS pool $poolname");
246
   $result = system('zfs', 'mount', '-a');
247
   unless ( $result == 0 ) {
248
      logMsg("Failed to mount zfs pool $poolname (exit $result)\n");
249
      return '';
250
   }
251
 
252
   logMsg("Successfully decrypted and mounted pool $poolname");
253
   return $poolname;
254
}
255
 
256
## Create a GELI key by XOR'ing a remote binary keyfile and a local key (hex string).
257
##
258
## Arguments:
259
##   $remote_keyfile - path to binary keyfile (32 bytes)
260
##   $localKeyHexOrPath - hex string (64 hex chars) or path to file containing hex
261
##   $target - path to write the resulting 32-byte binary key
262
##
263
## Returns true on success, dies on fatal error.
264
sub makeGeliKey {
265
   my ($remote_keyfile, $localKeyHexOrPath, $target) = @_;
266
 
267
   die "remote keyfile not provided" unless defined $remote_keyfile;
268
   die "local key not provided" unless defined $localKeyHexOrPath;
269
   die "target not provided" unless defined $target;
270
 
271
   die "Remote keyfile $remote_keyfile does not exist\n" unless -e $remote_keyfile;
272
 
273
   # Read remote binary key
274
   open my $rh, '<:raw', $remote_keyfile or die "Unable to open $remote_keyfile: $!\n";
275
   my $rbuf;
276
   my $read = read($rh, $rbuf, 32);
277
   close $rh;
278
   die "Failed to read 32 bytes from $remote_keyfile (got $read)\n" unless defined $read && $read == 32;
279
 
280
   # Get local hex string (either direct string or file contents)
281
   my $hex;
282
   if (-e $localKeyHexOrPath) {
283
      open my $lh, '<', $localKeyHexOrPath or die "Unable to open local key file $localKeyHexOrPath: $!\n";
284
      local $/ = undef;
285
      $hex = <$lh>;
286
      close $lh;
287
   } else {
288
      $hex = $localKeyHexOrPath;
289
   }
290
   # clean hex (remove whitespace/newlines and optional 0x)
291
   $hex =~ s/0x//g;
292
   $hex =~ s/[^0-9a-fA-F]//g;
293
 
294
   die "Local key must be 64 hex characters (256-bit)\n" unless length($hex) == 64;
295
 
296
   my $lbuf = pack('H*', $hex);
297
   die "Local key decoded to unexpected length " . length($lbuf) . "\n" unless length($lbuf) == 32;
298
 
299
   # XOR the two buffers
300
   my $out = '';
301
   for my $i (0 .. 31) {
302
      $out .= chr( ord(substr($rbuf, $i, 1)) ^ ord(substr($lbuf, $i, 1)) );
303
   }
304
 
305
   # Ensure target directory exists
306
   my ($vol, $dirs, $file) = ($target =~ m{^(/?)(.*/)?([^/]+)$});
307
   if ($dirs) {
308
      my $dir = $dirs;
309
      $dir =~ s{/$}{};
310
      unless (-d $dir) {
311
         require File::Path;
312
         File::Path::make_path($dir) or die "Failed to create directory $dir: $!\n";
313
      }
314
   }
315
 
316
   # Write out binary key and protect permissions
317
   open my $oh, '>:raw', $target or die "Unable to open $target for writing: $!\n";
318
   print $oh $out or die "Failed to write to $target: $!\n";
319
   close $oh;
320
   chmod 0600, $target;
321
 
322
   return 1;
323
}
324
 
325
1;