-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbwrapper
More file actions
executable file
·695 lines (576 loc) · 21.1 KB
/
bwrapper
File metadata and controls
executable file
·695 lines (576 loc) · 21.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
#!/usr/bin/env perl
# bwrapper — Generic bwrap sandboxing helper with configuration support
# Usage:
# bwrapper <config> [files...] # Run with configuration
# bwrapper --edit <config> # Edit configuration
# bwrapper --list # List available configurations
use strict;
use warnings;
use File::Spec;
use File::Path qw(make_path);
use File::Basename;
use Cwd 'abs_path', 'getcwd';
use Getopt::Long;
use YAML::Tiny;
my $CONFIG_DIR = "./configurations";
my $PROFILE_DIR = "$ENV{HOME}/.config/bwrapper/profiles";
# Parse command line arguments
my $edit_mode = 0;
my $list_mode = 0;
my $help_mode = 0;
my $dryrun_mode = 0;
my $save_mode = 0;
my $executable = '';
my @args = ();
my @rw_paths = ();
my %env_vars = ();
my $home_path = '';
my $work_path = '';
GetOptions(
'edit' => \$edit_mode,
'list' => \$list_mode,
'help' => \$help_mode,
'h' => \$help_mode,
'dryrun' => \$dryrun_mode,
'save' => \$save_mode,
'exec=s' => \$executable,
'arg=s@' => \@args,
'rw=s@' => \@rw_paths,
'env=s%' => \%env_vars,
'home=s' => \$home_path,
'work=s' => \$work_path
);
if ($help_mode) {
show_help();
exit 0;
}
if ($list_mode) {
list_configurations();
exit 0;
}
if ($edit_mode) {
my $config_name = shift @ARGV;
if (!$config_name) {
die "Error: --edit requires a configuration name\n";
}
edit_configuration($config_name);
exit 0;
}
# Main execution
# Check if we have CLI options instead of a config file
if ($executable) {
my $config_name = shift @ARGV; # This will be the config name for --save
my @files = @ARGV;
if ($save_mode) {
# Save CLI options as configuration
save_cli_options_as_config($config_name, $executable, \@args, \@rw_paths, \%env_vars, $home_path, $work_path);
} else {
# Use CLI options directly
run_with_cli_options($executable, \@args, \@rw_paths, \%env_vars, $home_path, $work_path, $dryrun_mode, @files);
}
} else {
# Use configuration file mode
my $config_name = shift @ARGV;
my @files = @ARGV;
if (!$config_name) {
die "Error: Configuration name required\nUsage: $0 <config> [files...] OR $0 --exec <program> [options] [files...]\n";
}
# Validate that CLI options are not used in config mode
if (@args || @rw_paths || %env_vars || $save_mode || $home_path || $work_path) {
die "Error: --arg, --rw, --env, --save, --home, and --work options cannot be used with configuration files\n";
}
run_with_configuration($config_name, @files, $dryrun_mode);
}
sub show_help {
print <<'EOF';
bwrapper — Generic bwrap sandboxing helper with configuration support
Usage:
bwrapper <config> [files...] # Run with configuration file
bwrapper --exec <program> [options] [files...] # Run with command-line options
bwrapper --exec <program> --save <config> [options] # Save CLI options as configuration
bwrapper --edit <config> # Edit configuration
bwrapper --list # List available configurations
bwrapper --dryrun <config> # Show the command that would be executed
bwrapper --help # Show this help
Command-line options (when using --exec):
--exec <program> # Program to execute in the sandbox
--arg <argument> # Add argument to pass to the program (can be used multiple times)
--rw <path> # Add read-write path to bind (can be used multiple times)
--env <key=value> # Set environment variable (can be used multiple times)
--home <path> # Use custom home directory (isolates $HOME)
--work <path> # Mount files under work subdirectory (requires --home)
--save <config> # Save CLI options as configuration file
--dryrun # Show the command that would be executed
Configuration files can be stored in:
- ./configurations/ (regular .conf files)
- ~/.config/bwrapper/profiles/ (profile .profile files)
Configuration file format:
- executable: The program to run
- args: Array of arguments to pass to the program (optional)
- rw_paths: Array of paths to bind read-write (optional)
Profile resolution:
- If config name contains "/" or ends with ".profile", treat as file path
- Otherwise, look for ~/.config/bwrapper/profiles/<name>.profile
The script provides sensible defaults for:
- Entire filesystem is read-only (--ro-bind / /)
- Essential system paths (--proc, --dev, --tmpfs)
- Environment variables (DISPLAY, WAYLAND_DISPLAY, XDG_RUNTIME_DIR, HOME, DBUS)
- X11 and GPU passthrough
- Security checks
Examples:
# Using configuration file:
bwrapper cursor /path/to/project
# Using profile configuration:
bwrapper myprofile /path/to/project # looks for ~/.config/bwrapper/profiles/myprofile.profile
# Using profile file with path:
bwrapper /path/to/some.profile /path/to/project
# Using command-line options:
bwrapper --exec /usr/bin/cursor --arg=-a --arg=-b --rw=$HOME/.config/Cursor --rw=$HOME/.cache/Cursor /path/to/project
# Using custom home directory:
bwrapper --exec /usr/bin/cursor --home ~/NEW_HOME /path/to/project
# Using custom home with work subdirectory:
bwrapper --exec /usr/bin/cursor --home ~/NEW_HOME --work WORK /path/to/project
# Save CLI options as configuration:
bwrapper --exec /usr/bin/cursor --arg=-a --arg=-b --rw=$HOME/.config/Cursor --save myconfig
# Minimal configuration file:
executable: /usr/bin/cursor
args: []
rw_paths:
- $HOME/.config/Cursor
- $HOME/.cache/Cursor
Requirements:
sudo apt install libyaml-tiny-perla
EOF
}
sub list_configurations {
make_path($CONFIG_DIR) unless -d $CONFIG_DIR;
make_path($PROFILE_DIR) unless -d $PROFILE_DIR;
my @configs = glob("$CONFIG_DIR/*.conf");
my @profiles = glob("$PROFILE_DIR/*.profile");
if (@configs || @profiles) {
print "Available configurations:\n";
if (@configs) {
print " Regular configurations:\n";
foreach my $config (@configs) {
my $name = basename($config, '.conf');
print " $name\n";
}
}
if (@profiles) {
print " Profile configurations:\n";
foreach my $profile (@profiles) {
my $name = basename($profile, '.profile');
print " $name\n";
}
}
} else {
print "No configurations found in $CONFIG_DIR or $PROFILE_DIR\n";
}
}
sub edit_configuration {
my $config_name = shift;
my $config_file = resolve_config_path($config_name);
# Ensure the directory exists for the config file
my $config_dir = dirname($config_file);
make_path($config_dir) unless -d $config_dir;
my $editor = $ENV{EDITOR} || $ENV{VISUAL} || 'nano' || 'vi';
system($editor, $config_file) == 0 or die "Failed to edit configuration: $!\n";
}
sub load_configuration {
my $config_name = shift;
my $config_file = resolve_config_path($config_name);
unless (-f $config_file) {
die "Configuration file not found: $config_file\n";
}
unless (-r $config_file) {
die "Configuration file not readable: $config_file\n";
}
my $yaml = YAML::Tiny->read($config_file);
if (!$yaml) {
die "Error parsing YAML file $config_file: " . YAML::Tiny->errstr . "\n";
}
my $config = $yaml->[0] || {};
# Ensure required fields exist with defaults
$config->{args} ||= [];
$config->{rw_paths} ||= [];
$config->{env_vars} ||= {};
$config->{additional_bwrap_args} ||= [];
# Expand ~ to $ENV{HOME} in all string values
$config = expand_tilde_in_config($config);
return $config;
}
sub expand_tilde_in_config {
my $config = shift;
my $home = $ENV{HOME} || $ENV{USERPROFILE} || '';
# Recursively process the config hash
if (ref($config) eq 'HASH') {
my %expanded = ();
for my $key (keys %$config) {
$expanded{$key} = expand_tilde_in_config($config->{$key});
}
return \%expanded;
}
elsif (ref($config) eq 'ARRAY') {
my @expanded = ();
for my $item (@$config) {
push @expanded, expand_tilde_in_config($item);
}
return \@expanded;
}
elsif (defined($config) && $config =~ /^~/) {
# Replace leading ~ with home directory
$config =~ s/^~/$home/;
return $config;
}
else {
return $config;
}
}
sub resolve_abs_path {
my $path = shift;
return abs_path($path) || $path;
}
sub resolve_config_path {
my $config_name = shift;
# If config name contains "/" or ends with ".profile", treat it as a file path
if ($config_name =~ /\// || $config_name =~ /\.profile$/) {
return resolve_abs_path($config_name);
}
# Otherwise, look for it in the profile directory
my $profile_file = "$PROFILE_DIR/$config_name.profile";
return resolve_abs_path($profile_file);
}
sub check_not_root_dirs {
my $project_path = shift;
my $abs_path = resolve_abs_path($project_path);
if ($abs_path eq '/' || $abs_path eq '/usr' || $abs_path eq '/etc' || $abs_path eq $ENV{HOME}) {
die "Error: selecting a high-level system or home directory ('$abs_path') is not allowed.\n";
}
}
sub validate_distinct_final_dirs {
my $home_path = shift;
my $work_path = shift;
my @files = @_;
return if @files == 0; # No files to validate
my %final_dirs;
foreach my $file (@files) {
my $abs_file = resolve_abs_path($file);
my $final_dir;
if ($home_path) {
# Calculate the final directory path within the home directory
if ($work_path) {
$final_dir = "$home_path/$work_path/" . basename($abs_file);
} else {
$final_dir = "$home_path/" . basename($abs_file);
}
} else {
# Use the original directory
$final_dir = -d $abs_file ? $abs_file : dirname($abs_file);
}
if (exists $final_dirs{$final_dir}) {
die "Error: Final directories would not be distinct: '$final_dir' (from '$file' and '$final_dirs{$final_dir}')\n";
}
$final_dirs{$final_dir} = $file;
}
}
sub setup_bwrap_environment {
my $project_path = shift;
my $rw_paths_ref = shift;
my $env_vars_ref = shift;
my $additional_bwrap_args_ref = shift;
my $home_path = shift;
my $work_path = shift;
my $dryrun = shift;
my $files_ref = shift;
my $executable = shift;
my @files = @$files_ref;
# Run security checks (always enabled by default)
check_not_root_dirs($project_path);
# Validate distinct final directories if home isolation is used
if ($home_path) {
validate_distinct_final_dirs($home_path, $work_path, @files);
}
# Setup runtime environment
my $uid = $>;
my $xdg_rt = $ENV{XDG_RUNTIME_DIR} || "/run/user/$uid";
make_path($xdg_rt) unless -d $xdg_rt;
chmod 0700, $xdg_rt;
# Build bwrap arguments with sensible defaults
my @bwrap_args = (
'--ro-bind', '/', '/', # Show entire host read-only
'--proc', '/proc',
'--dev', '/dev',
'--tmpfs', '/tmp',
'--bind', $xdg_rt, $xdg_rt
);
# Add home isolation if specified
if ($home_path) {
# Expand environment variables in home path
$home_path =~ s/\$(\w+)/$ENV{$1}/g;
$home_path = resolve_abs_path($home_path);
# Create home directory if it doesn't exist (only if not in dryrun mode)
unless ($dryrun) {
make_path($home_path) unless -d $home_path;
}
# Set up home isolation
push @bwrap_args, '--tmpfs', '/home';
push @bwrap_args, '--dir', '/home';
push @bwrap_args, '--bind', $home_path, '/home/app';
push @bwrap_args, '--setenv', 'HOME', '/home/app';
# Mount files in the home directory
if (@files) {
foreach my $file (@files) {
my $abs_file = resolve_abs_path($file);
my $mount_point;
if ($work_path) {
# Mount under work subdirectory
my $work_dir = "/home/app/$work_path";
push @bwrap_args, '--dir', $work_dir;
$mount_point = "$work_dir/" . basename($abs_file);
} else {
# Mount directly in home
$mount_point = "/home/app/" . basename($abs_file);
}
push @bwrap_args, '--bind', $abs_file, $mount_point;
}
}
# Set working directory to the first file's location or work directory
if (@files) {
my $first_file = resolve_abs_path($files[0]);
my $work_dir = $work_path ? "/home/app/$work_path" : "/home/app";
push @bwrap_args, '--chdir', "$work_dir/" . basename($first_file);
} else {
my $work_dir = $work_path ? "/home/app/$work_path" : "/home/app";
push @bwrap_args, '--chdir', $work_dir;
}
} else {
# Normal mode - bind project path
push @bwrap_args, '--bind', $project_path, $project_path;
push @bwrap_args, '--chdir', $project_path;
}
# Add configured read-write paths
if ($rw_paths_ref && @$rw_paths_ref) {
foreach my $path (@$rw_paths_ref) {
# Expand environment variables
$path =~ s/\$(\w+)/$ENV{$1}/g;
push @bwrap_args, '--bind', $path, $path;
}
}
# Add additional bwrap arguments if specified
if ($additional_bwrap_args_ref && @$additional_bwrap_args_ref) {
push @bwrap_args, @$additional_bwrap_args_ref;
}
# Add X11 socket if present
if (-d '/tmp/.X11-unix') {
push @bwrap_args, '--ro-bind', '/tmp/.X11-unix', '/tmp/.X11-unix';
}
# Add GPU passthrough
if (-d '/dev/dri') {
push @bwrap_args, '--bind', '/dev/dri', '/dev/dri';
}
for my $nvidia_dev (qw(/dev/nvidiactl /dev/nvidia0 /dev/nvidia-uvm /dev/nvidia-uvm-tools)) {
if (-e $nvidia_dev) {
push @bwrap_args, '--bind', $nvidia_dev, $nvidia_dev;
}
}
# Add environment variables (with sensible defaults)
if (defined $ENV{DISPLAY}) {
push @bwrap_args, '--setenv', 'DISPLAY', $ENV{DISPLAY};
}
if (defined $ENV{WAYLAND_DISPLAY}) {
push @bwrap_args, '--setenv', 'WAYLAND_DISPLAY', $ENV{WAYLAND_DISPLAY};
}
if (-S "$xdg_rt/bus") {
push @bwrap_args, '--setenv', 'DBUS_SESSION_BUS_ADDRESS', "unix:path=$xdg_rt/bus";
}
push @bwrap_args, '--setenv', 'XDG_RUNTIME_DIR', $xdg_rt;
# Add custom environment variables if specified
if ($env_vars_ref && %$env_vars_ref) {
foreach my $key (keys %$env_vars_ref) {
my $value = $env_vars_ref->{$key};
$value =~ s/\$(\w+)/$ENV{$1}/g;
push @bwrap_args, '--setenv', $key, $value;
}
}
return @bwrap_args;
}
sub determine_project_path_and_targets {
my @files = @_;
my $project_path;
my @targets;
if (@files == 0) {
$project_path = getcwd();
@targets = (); # No targets when no files specified
} else {
# Use the first file/directory to determine the project path
my $first_file = resolve_abs_path($files[0]);
if (-d $first_file) {
$project_path = $first_file;
} else {
$project_path = dirname($first_file);
}
# All files become targets
@targets = @files;
}
return ($project_path, @targets);
}
sub execute_bwrap_command {
my $executable = shift;
my $bwrap_args_ref = shift;
my $exec_args_ref = shift;
my $dryrun = shift;
# Check if bwrap command exists
unless ($dryrun) {
system('which', 'bwrap') == 0 or die "Error: bwrap command not found. Please install bubblewrap.\n";
}
# Use the arguments as provided
my @exec_args = @$exec_args_ref;
# Execute or show command
if ($dryrun) {
print "Executable: $executable\n";
print "Arguments: " . join(" ", @exec_args) . "\n";
print "Bwrap arguments: " . scalar(@$bwrap_args_ref) . " total\n";
print "\nFull bwrap command:\n";
print "bwrap \\\n";
foreach my $arg (@$bwrap_args_ref) {
print " \"$arg\" \\\n";
}
print " -- $executable";
foreach my $arg (@exec_args) {
print " \"$arg\"";
}
print "\n";
} else {
exec 'bwrap', @$bwrap_args_ref, '--', $executable, @exec_args;
}
}
sub run_with_configuration {
my $config_name = shift;
my @files = @_;
my $dryrun = pop @files; # Last parameter is dryrun flag
if ($dryrun) {
print "=== BWAPPER DRYRUN MODE ===\n";
print "Loading profile: $config_name\n";
my $config_path = resolve_config_path($config_name);
print "Path: $config_path\n";
}
my $config = load_configuration($config_name);
if ($dryrun) {
print "Config loaded:\n";
print " executable: " . ($config->{executable} || 'undef') . "\n";
print " args: [" . join(", ", @{$config->{args} || []}) . "]\n";
print " additional_bwrap_args: [" . join(", ", @{$config->{additional_bwrap_args} || []}) . "]\n";
}
# Determine project path and targets
my ($project_path, @targets) = determine_project_path_and_targets(@files);
# Setup bwrap environment using shared logic
my @bwrap_args = setup_bwrap_environment(
$project_path,
$config->{rw_paths},
$config->{env_vars},
$config->{additional_bwrap_args},
$config->{home_path},
$config->{work_path},
$dryrun,
\@files,
$config->{executable}
);
# Build command
my $executable = $config->{executable};
my @exec_args = @{$config->{args} || []};
push @exec_args, @targets;
# Execute command using shared logic
execute_bwrap_command($executable, \@bwrap_args, \@exec_args, $dryrun);
}
sub run_with_cli_options {
my $executable = shift;
my $args_ref = shift;
my $rw_paths_ref = shift;
my $env_vars_ref = shift;
my $home_path = shift;
my $work_path = shift;
my $dryrun = shift; # Dryrun flag is a separate parameter
my @files = @_;
# Determine project path and targets
my ($project_path, @targets) = determine_project_path_and_targets(@files);
# Setup bwrap environment using shared logic
my @bwrap_args = setup_bwrap_environment(
$project_path,
$rw_paths_ref,
$env_vars_ref,
undef, # No additional bwrap args for CLI mode
$home_path,
$work_path,
$dryrun,
\@files, # Pass original files for home isolation as reference
$executable
);
# Build command
my @exec_args = @$args_ref;
push @exec_args, @targets;
# Execute command using shared logic
execute_bwrap_command($executable, \@bwrap_args, \@exec_args, $dryrun);
}
sub save_cli_options_as_config {
my $config_name = shift;
my $executable = shift;
my $args_ref = shift;
my $rw_paths_ref = shift;
my $env_vars_ref = shift;
my $home_path = shift;
my $work_path = shift;
unless ($config_name) {
die "Error: Configuration name required when using --save\nUsage: $0 --exec <program> --save <config_name> [options]\n";
}
my $config_file = resolve_config_path($config_name);
# Ensure config directory exists
my $config_dir = dirname($config_file);
make_path($config_dir) unless -d $config_dir;
# Check if config file already exists
if (-f $config_file) {
print "Warning: Configuration file $config_file already exists.\n";
print "Do you want to overwrite it? (y/N): ";
my $response = <STDIN>;
chomp $response;
unless ($response =~ /^[yY]/) {
print "Aborted.\n";
exit 0;
}
}
# Write configuration file
open my $fh, '>', $config_file or die "Cannot write $config_file: $!\n";
print $fh "# Configuration saved from command-line options\n";
print $fh "# Generated on " . scalar localtime() . "\n\n";
print $fh "executable: $executable\n";
if (@$args_ref) {
print $fh "args: []\n";
foreach my $arg (@$args_ref) {
print $fh " - $arg\n";
}
} else {
print $fh "args: []\n";
}
if (@$rw_paths_ref) {
print $fh "rw_paths: []\n";
foreach my $path (@$rw_paths_ref) {
print $fh " - $path\n";
}
} else {
print $fh "rw_paths: []\n";
}
if (%$env_vars_ref) {
print $fh "env_vars: {}\n";
foreach my $key (sort keys %$env_vars_ref) {
print $fh " $key: $env_vars_ref->{$key}\n";
}
}
if ($home_path) {
print $fh "home_path: $home_path\n";
}
if ($work_path) {
print $fh "work_path: $work_path\n";
}
close $fh;
print "Configuration saved to: $config_file\n";
print "You can now use: $0 $config_name [files...]\n";
}