Subversion Repositories web_pages

Rev

Rev 18 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
14 rodolico 1
#! /usr/bin/env perl
16 rodolico 2
 
3
# Copyright (c) 2025, Daily Data, Inc.
4
# All rights reserved.
5
#
6
# Redistribution and use in source and binary forms, with or without modification,
7
# are permitted provided that the following conditions are met:
8
#
9
# 1. Redistributions of source code must retain the above copyright notice, this list
10
#    of conditions and the following disclaimer.
11
# 2. Redistributions in binary form must reproduce the above copyright notice, this
12
#    list of conditions and the following disclaimer in the documentation and/or other
13
#    materials provided with the distribution.
14
# 3. Neither the name of Daily Data, Inc. nor the names of its contributors may be
15
#    used to endorse or promote products derived from this software without specific
16
#    prior written permission.
17
#
18
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
19
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
21
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
23
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
24
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
27
# DAMAGE.
28
#
29
# Script which will read information from an OPNsense router via its API
30
# and create/update user OTP secrets, QR codes, and OpenVPN configuration files
31
# for each user with a VPN certificate.
32
#
33
# Change History:
34
#  v1.0 2025-10-01 - Initial version RWR
35
#     Initial Release
36
#  v1.0.1 2025-10-01 RWR
37
#     Added a lock file to not allow the script to run if it is already running. If we can not
38
#       get an exclusive lock on $lockFile in $lockRetryTime*$lockRetries seconds, script will abort
39
#     Added both the full path to the data directories as well as the relative, to help
40
#       the web site (relative) and the script (full path, even if we're running from a different)
41
#       location to work easily (less code)
20 rodolico 42
#  v1.1.0 2026-01-04 RWR
43
#     Removed hardcoded additionalOvpnStrings variable
44
#     Added support for formats hash in router configuration
45
#     Modified makeVPNConfigFile to accept filename template with ROUTER and USER placeholders
46
#     Added support for multiple OVPN files per user based on formats configuration
47
#     Formats structure allows specifying filename and additionalStrings per format
48
#     Expands \n in additionalStrings to actual newlines in config files
16 rodolico 49
 
14 rodolico 50
use strict;
51
use warnings;
52
 
16 rodolico 53
# use libraries from the directory this script is in
54
BEGIN {
55
   use FindBin;
56
   use File::Spec;
57
   # use libraries from the directory this script is in
58
   use Cwd 'abs_path';
59
   use File::Basename;
60
   use lib dirname( abs_path( __FILE__ ) );
61
}
14 rodolico 62
 
16 rodolico 63
 
14 rodolico 64
use JSON; # for encode_json, decode_json
65
use Data::Dumper; # for debugging
66
use opnsense; # our module to handle opnsense API calls
67
use GD::Barcode::QRcode; # for creating the QR code images
68
use MIME::Base64 qw( decode_base64 ); # for decoding the ovpn file returned from the API
69
use File::Path qw( make_path ); # for creating directories
16 rodolico 70
use Fcntl qw(:flock); # Import locking constants
71
 
20 rodolico 72
our $VERSION = '1.1.0';
16 rodolico 73
 
74
# Check if running as root
75
if ($> != 0) {
76
   die "Error: This script must be run as root.\n";
77
}
78
 
79
#-----------------------------
80
# Configuration Variables
81
#-----------------------------
82
# Location of the configuration files and directories where we will store data
83
# relative to the script directory as written
84
my $scriptDir = $FindBin::RealBin;
85
my $configFile = $scriptDir . '/routers.json';
86
my $usersFile = $scriptDir . '/users.json';
87
my $qrLocation =  './qrcodes';
88
my $ovpnFileLocation =  './openvpn_configs';
89
# size of the QR code modules, basically a magnification factor
14 rodolico 90
my $moduleSize = 10;
16 rodolico 91
# using a lock file to ensure script does not run while another request has it running
92
my $lockFile = '/tmp/opnsense.lock';
93
my $lockRetryTime = 10; # number of seconds between subsequent tries for a lock
94
my $lockRetries = 6; # number of times we will attempt to get a lock before failing
14 rodolico 95
 
16 rodolico 96
#-----------------------------
97
# slurpFile: Reads in the entire contents of a file and returns it as a string
98
# $file - name of file to read
99
# returns the contents of the file as a string, or empty string if file does not exist
100
# since we do this a lot, make it a separate function. This is likely the most efficient way
101
# to read a file in Perl
102
#-----------------------------
103
sub slurpFile {
104
   my ($file) = @_;
105
   my $data = '';
106
   if (-e $file) {
107
      open(my $fh, '<', $file) or die "Cannot open $file: $!";
14 rodolico 108
      local $/;  # slurp mode
16 rodolico 109
      $data = <$fh>;
14 rodolico 110
      close $fh;
111
   }
112
   return $data;
113
}
114
 
16 rodolico 115
#-----------------------------
116
# loadConfig: Load router configuration from config file
117
# $file - name of file to read
118
# $entry - name of the router entry to load
119
# returns a reference to the data structure for the router, or empty hash if not found
120
#-----------------------------
121
sub loadConfig {
122
   my ($file, $entry) = @_;
123
   my $return = &slurpFile($file);
124
   return {} unless $return && $return ne '';
125
   my $data = decode_json($return);
126
   return $data->{$entry} if (exists $data->{$entry});
127
   return {};
128
}
129
 
130
#-----------------------------
131
# loadUsers: Load users data structure from file
132
# $file - name of file to read
133
# returns a reference to the data structure
134
# $file assumed to be in JSON format
135
#-----------------------------
136
sub loadUsers {
137
   my ($file) = @_;
138
   my $data = &slurpFile($file);
139
   return {} unless $data && $data ne '';
140
   my $return = decode_json($data);
141
   return {} unless $return && ref($return) eq 'HASH';
142
   return $return;
143
}
144
 
145
#-----------------------------
146
# saveUsers: Save users data structure to file
147
# $file - name of file to write
148
# $data - reference to the data to write
149
# $timeStampFile - optional name of a file to write the current timestamp to
150
# writes the data in JSON format
151
#-----------------------------
14 rodolico 152
sub saveUsers {
16 rodolico 153
   my ($file, $data) = @_;
154
   open(my $fh, '>', $file) or die "Cannot open $file: $!";
14 rodolico 155
   print $fh encode_json($data);
156
   close $fh;
157
}
158
 
16 rodolico 159
#-----------------------------
160
# makeQR: Creates a QR code file
161
# $routerName - name of the router (used in filename and OTP URL)
162
# $account - account name (used in filename and OTP URL)
163
# $secret - OTP secret
164
# $moduleSize - size of the QR code modules
165
# $relativeDir - directory to save the QR code file
166
# $absDir - The directory the script is in, so writing relative directories will correctly place
167
# returns the filename of the created QR code image
168
#-----------------------------
14 rodolico 169
sub makeQR {
16 rodolico 170
   # Creates a QR code image for the user's OTP secret
171
   my ($routerName, $account, $secret, $moduleSize, $relativeDir, $absDir ) = @_;
172
   # build the OTP URL to include router name as issuer and the account name for display in authenticator apps
173
   my $otpUrl = "otpauth://totp/$routerName:$account?secret=$secret&issuer=$routerName";
174
   # generate the QR code
175
   my $barcode = GD::Barcode::QRcode->new($otpUrl, { Ecc => 'M', ModuleSize => $moduleSize } );
14 rodolico 176
   my $image = $barcode->plot();
16 rodolico 177
   my $fileName = ($routerName ? $routerName . '_' : '' ) . $account . '.png'; 
178
   # This allows us to retain the relative file path for storage, but ensuring we write the file to 
179
   # the correct path even if we are not running the script from the script directory.
180
   open my $out, '>', "$absDir/" . $fileName or die "Cannot write file $fileName to $absDir: $!";
14 rodolico 181
   binmode $out;
182
   print $out $image->png;
183
   close $out;
16 rodolico 184
   return $relativeDir . '/' . $fileName;
14 rodolico 185
}
186
 
16 rodolico 187
#-----------------------------
188
# makeVPNConfigFile: Creates a VPN configuration file for the user
189
# $contents - reference to the hash containing the 'content' key with base64 encoded ovpn file
20 rodolico 190
# $routerName - name of the router (used in filename template replacement)
191
# $userName - name of the user (used in filename template replacement)
16 rodolico 192
# $ovpnLocation - The relative path to the output directory
193
# $absDir - The absolute path to the output directory
20 rodolico 194
# $filenameTemplate - template for filename with ROUTER and USER placeholders
195
# $additionalOvpnStrings - additional strings to add to the ovpn file, \n will be expanded to newlines
16 rodolico 196
# returns the filename of the created ovpn file
197
#-----------------------------
14 rodolico 198
sub makeVPNConfigFile {
20 rodolico 199
   my ($contents, $routerName, $userName, $ovpnLocation, $absDir, $filenameTemplate, $additionalOvpnStrings) = @_;
14 rodolico 200
   return '' unless $contents && $contents->{'content'};
20 rodolico 201
   # Replace ROUTER and USER in the filename template
202
   my $fileName = $filenameTemplate;
203
   $fileName =~ s/ROUTER/$routerName/g;
204
   $fileName =~ s/USER/$userName/g;
14 rodolico 205
   $contents->{'content'} = decode_base64($contents->{'content'});
206
   $contents->{'content'} .= "\n";
207
   $contents->{'content'} =~ s/(\r?\n)+/\n/g; # normalize line endings
208
   my $comment = '';
209
   if ( $contents->{'content'} !~ /# Added by loadOpnSense.pl/ ) {
210
      $comment = "# Added by loadOpnSense.pl\n";
211
   }
20 rodolico 212
   # Expand \n to actual newlines in additionalOvpnStrings
213
   $additionalOvpnStrings =~ s/\\n/\n/g if $additionalOvpnStrings;
214
   foreach my $string ( split( /\n/, $additionalOvpnStrings || '' ) ) {
215
      next if $string eq '';
216
      unless ( $contents->{'content'} =~ /\Q$string\E/ ) {
14 rodolico 217
         $contents->{'content'} .= "$comment$string\n";
218
         $comment = ''; # only add comment once
219
      }
220
   }
16 rodolico 221
   # This allows us to retain the relative file path for storage, but ensuring we write the file to 
222
   # the correct path even if we are not running the script from the script directory.
223
   open my $out, '>', "$absDir/" . $fileName or die "Cannot write file $fileName to $absDir: $!";
14 rodolico 224
   print $out $contents->{'content'};
225
   close $out;
16 rodolico 226
   return $ovpnLocation . '/' . $fileName;
14 rodolico 227
}
228
 
16 rodolico 229
# cleanOldDataFiles: Deletes old data files in the specified directory matching the given pattern
230
# $directory - directory to scan for old files
231
# $pattern - regex pattern to match files to delete
232
# simply removes all files matching the pattern
233
#-----------------------------
234
sub cleanOldDataFiles {
235
   my ( $directory, $pattern ) = @_;
236
   opendir(my $dh, $directory) or die "Cannot open directory $directory: $!";
237
   while (my $file = readdir($dh)) {
238
      next if ($file =~ /^\./);
239
      if ($file =~ /$pattern/) {
240
         unlink "$directory/$file" or warn "Could not delete $directory/$file: $!";
241
      }
242
   }
243
   closedir($dh);
244
}
14 rodolico 245
 
246
 
16 rodolico 247
#-----------------------------
248
# Main program
249
#-----------------------------
250
 
251
# make sure script does not run more than once at the same time
252
# Open the lock file
253
open(my $fh, '>', $lockFile) or die "Cannot open lock file $lockFile: $!";
254
# Attempt to acquire an exclusive lock. We will try $lockTimeOut times, each
255
# waiting $lockRetryTime
256
while ( $lockRetries-- ) {
257
   if (flock($fh, LOCK_EX | LOCK_NB)) {
258
      last;
259
   } else {
260
      sleep($lockRetryTime);
261
   }
262
}
263
# if $lockTimeOut is zero, we could not get a lock in, so die
264
die "Another instance of the script is already running and retries exceeded!\n" unless ( $lockRetries );
265
 
14 rodolico 266
# get the router name from the command line
267
my $router = shift @ARGV or die "Usage: $0 <router_name>\n";
268
# Load existing configuration or initialize a new one
16 rodolico 269
my $config = &loadConfig($configFile, $router );
270
die "Configuration for router $router not found in $configFile\n" unless $config && ref($config) eq 'HASH';
20 rodolico 271
# die Dumper( $config ) . "\n";
14 rodolico 272
 
273
# load the users file. We will update the entry for this router
16 rodolico 274
my $users = &loadUsers( $usersFile );
14 rodolico 275
 
276
# if there is no entry for this router, create an empty one
277
$users->{$router} = {} unless exists $users->{$router};
278
$users->{$router}->{'qrLocation'} = $qrLocation unless exists $users->{$router}->{'qrLocation'};
279
$users->{$router}->{'ovpnLocation'} = $ovpnFileLocation unless exists $users->{$router}->{'ovpnLocation'};
280
$users->{$router}->{'users'} = {}; # clean out the users list, we will reload it
16 rodolico 281
# and get the location on the file system in case we are not running the script from the script directory
282
$users->{$router}->{'qrLocationFileystem'} = abs_path( $scriptDir . '/' . $qrLocation )
283
   unless exists $users->{$router}->{'qrLocationFileystem'};
284
$users->{$router}->{'ovpnLocationFileSystem'} = abs_path( $scriptDir . '/' . $ovpnFileLocation )
285
   unless exists $users->{$router}->{'ovpnLocationFileSystem'};
18 rodolico 286
# finally, copy the download token if it exists
287
$users->{$router}->{'downloadToken'} = $config->{'downloadToken'}
288
   if exists $config->{'downloadToken'};
14 rodolico 289
 
18 rodolico 290
#die Dumper( $users ) . "\n";
16 rodolico 291
 
18 rodolico 292
 
14 rodolico 293
# ensure the directories exist and give them full access
16 rodolico 294
make_path( $users->{$router}->{'qrLocationFileystem'}, 0777 ) unless -d $users->{$router}->{'qrLocationFileystem'};
295
make_path( $users->{$router}->{'ovpnLocationFileSystem'}, 0777 ) unless -d $users->{$router}->{'ovpnLocationFileSystem'};
14 rodolico 296
 
16 rodolico 297
# instead of actually going through and cleaning files no longer in the users list,
298
# just delete all files for this router and recreate them
299
&cleanOldDataFiles( $users->{$router}->{'qrLocationFileystem'}, qr/^\Q$router\E_.*\.png$/ );
300
&cleanOldDataFiles( $users->{$router}->{'ovpnLocationFileSystem'}, qr/^\Q$router\E_.*\.ovpn$/ );
301
 
14 rodolico 302
# this does most of the work, all the API calls are handled in the module
303
# create the opnsense object
16 rodolico 304
my $opnsense = opnsense->new(
14 rodolico 305
   url    => $config->{'url'},
306
   apiKey    => $config->{'apiKey'},
307
   apiSecret => $config->{'apiSecret'},
308
   ovpnIndex  => $config->{'ovpnIndex'},
16 rodolico 309
   localPort => $config->{'localPort'},
14 rodolico 310
   template  => $config->{'template'},
311
   hostname  => $config->{'hostname'}, 
312
);
313
 
314
# get the VPN users. This is a hashref keyed by cert name, value is username
16 rodolico 315
my $vpnCerts = $opnsense->getVpnUsers();
17 rodolico 316
#die Dumper($vpnCerts);
14 rodolico 317
# convert the cert-"user" to username->certs, array ref of certs as not sure if multiple certs per user allowed
318
foreach my $cert ( keys %$vpnCerts ) {
319
   push @{$users->{$router}->{'users'}->{$vpnCerts->{$cert}}->{'certs'}}, $cert;
320
}
321
 
322
# these are all of the users on the system
16 rodolico 323
my $allUsers = $opnsense->getAllUsers();
14 rodolico 324
 
325
# for each user in the system, if they are in the vpnUsers list, copy otp_seed, cert, and password
326
# we'll also delete any users who are disabled
327
my @keys = ('otp_seed', 'cert', 'password' ); # these are the keys we want to copy
328
foreach my $user ( keys %$allUsers ) {
329
   next unless exists $users->{$router}->{'users'}->{$user}; # skip users who do not have vpn certs
330
   if ( $allUsers->{$user}->{'disabled'} ) { # skip users who are disabled
331
      delete $users->{$router}->{'users'}->{$user};
332
      next;
333
   }
334
   foreach my $key ( @keys ) {
335
      $users->{$router}->{'users'}->{$user}->{$key} = ref($allUsers->{$user}->{$key}) ? '' : $allUsers->{$user}->{$key};
336
   }
337
}
338
 
339
# create the QR code file and VPN configuration for each user
340
foreach my $entry ( keys %{$users->{$router}->{'users'}} ) {
341
   my $account = $entry;
16 rodolico 342
   my $secret = $users->{$router}->{'users'}->{$entry}->{'otp_seed'} || '';
343
   # Create the QR code file and store the filename in the data structure
344
   # If there is no secret, do not create a QR code
14 rodolico 345
   $users->{$router}->{'users'}->{$entry}->{'qrFile'} = 
16 rodolico 346
      $secret && $secret ne '' ?
347
      &makeQR(
348
            $router,
349
            $account,
350
            $secret,
351
            $moduleSize,
352
            $users->{$router}->{'qrLocation'},
353
            $users->{$router}->{'qrLocationFileystem'}
354
            ) :
355
      '';
356
 
20 rodolico 357
   # Create the VPN configuration file(s), if they exist. If multiple certs, only use the first one
16 rodolico 358
   # warn user if there are multiple certs
14 rodolico 359
   if ( scalar(@{$users->{$router}->{'users'}->{$entry}->{'certs'}}) > 1 ) {
360
      warn "$entry has multiple certs, using first one only\n";
361
   }
16 rodolico 362
   my $cert = $opnsense->getVpnConfig( $users->{$router}->{'users'}->{$entry}->{'certs'}->[0] );
14 rodolico 363
   if ( !$cert || ref($cert) ne 'HASH' || !exists $cert->{'content'} ) {
364
      warn "Could not get VPN configuration for $entry, cert $users->{$router}->{'users'}->{$entry}->{'certs'}->[0]\n";
365
      next;
366
   }
20 rodolico 367
 
368
   # Process formats to create multiple OVPN files if formats are defined
369
   my @ovpnFiles = ();
370
   my $formats = $config->{'formats'};
371
   # die Dumper($config) . "\n";
372
   # die Dumper($formats) . "\n";
373
   if ( $formats && ref($formats) eq 'HASH' && keys %$formats ) {
374
      # Iterate through each format
375
      foreach my $formatName ( keys %$formats ) {
376
         my $format = $formats->{$formatName};
377
         next unless ref($format) eq 'HASH';
378
         my $filename = $format->{'filename'} || '';
379
         my $additionalStrings = $format->{'additionalStrings'} || '';
380
         next if $filename eq '';
381
         my $ovpnFile = &makeVPNConfigFile(
382
            $cert,
383
            $router,
384
            $entry,
385
            $users->{$router}->{'ovpnLocation'},
386
            $users->{$router}->{'ovpnLocationFileSystem'},
387
            $filename,
388
            $additionalStrings
389
         );
390
         push @ovpnFiles, $ovpnFile if $ovpnFile;
391
      }
392
   }
393
 
394
   # If no formats defined or no files created, create a default file
395
   if ( scalar(@ovpnFiles) == 0 ) {
396
      my $defaultFilename = $router . '_' . $entry . '.ovpn';
397
      my $ovpnFile = &makeVPNConfigFile(
16 rodolico 398
         $cert,
399
         $router,
400
         $entry,
401
         $users->{$router}->{'ovpnLocation'},
402
         $users->{$router}->{'ovpnLocationFileSystem'},
20 rodolico 403
         $defaultFilename,
404
         "static-challenge 'Enter Auth Code' 0\nauth-nocache"
405
      );
406
      push @ovpnFiles, $ovpnFile if $ovpnFile;
407
   }
408
 
409
   # Store as array if multiple files, or single string if only one
410
   $users->{$router}->{'users'}->{$entry}->{'ovpnFile'} = 
411
      scalar(@ovpnFiles) > 1 ? \@ovpnFiles : $ovpnFiles[0];
14 rodolico 412
}
16 rodolico 413
# update the timestamp for the current router
414
$users->{$router}->{'lastUpdate'} = time;
415
# save the users file
416
&saveUsers( $usersFile, $users );
14 rodolico 417
 
16 rodolico 418
# Remove the lock file so the script can run again
419
close($fh);
420
unlink($lockFile) or warn "Could not unlink lock file: $!";
421
 
422
1;