Subversion Repositories web_pages

Rev

Rev 16 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
14 rodolico 1
# Copyright (c) 2025, Daily Data, Inc.
2
# All rights reserved.
3
#
4
# Redistribution and use in source and binary forms, with or without modification,
5
# are permitted provided that the following conditions are met:
6
#
7
# 1. Redistributions of source code must retain the above copyright notice, this list
8
#    of conditions and the following disclaimer.
9
# 2. Redistributions in binary form must reproduce the above copyright notice, this
10
#    list of conditions and the following disclaimer in the documentation and/or other
11
#    materials provided with the distribution.
12
# 3. Neither the name of Daily Data, Inc. nor the names of its contributors may be
13
#    used to endorse or promote products derived from this software without specific
14
#    prior written permission.
15
#
16
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
17
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
19
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
21
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
22
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
23
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
24
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
25
# DAMAGE.
16 rodolico 26
#
27
# Library to interface with the OPNsense API
28
# Provides methods to interact with OPNsense routers via their API.
29
#
30
# Change History:
31
#  v1.0.0 2025-10-01 - RWR
32
#    Initial version
17 rodolico 33
#  v1.0.1 2025-10-07 - RWR
34
#    Fixed bug where script was looking for localport, but was localPort
35
#    Fixed bug where not all users were returned because opnSense (v24.7)
36
#       does not send the username, it sends the description. Possible
37
#       programming error, but quick fix is to use username, then description
14 rodolico 38
 
17 rodolico 39
 
14 rodolico 40
package opnsense;
41
use strict;
42
use warnings;
43
 
44
use LWP::UserAgent;
45
use JSON;
46
use Data::Dumper;
47
use XML::Simple;
48
 
16 rodolico 49
our $VERSION = "1.0.0";
14 rodolico 50
 
16 rodolico 51
our $useCurl = 1; # set to 1 to use curl for API requests, 0 to use LWP
52
our $debug = 0;    # set to 1 for debug output
14 rodolico 53
 
16 rodolico 54
#-----------------------------
55
# new: Constructor
56
#-----------------------------
14 rodolico 57
sub new {
16 rodolico 58
   my ($class, %args) = @_;
59
   my $self = {
60
      baseUrl   => $args{url},
61
      apiKey    => $args{apiKey},
62
      apiSecret => $args{apiSecret},
63
      ovpnIndex => $args{ovpnIndex},
64
      template  => $args{template},
65
      hostname  => $args{hostname},
66
      localPort => $args{localPort},
67
      ua        => $useCurl ?
68
         'curl -s --insecure' :
69
         LWP::UserAgent->new(
70
            ssl_opts => { verify_hostname => 0, SSL_verify_mode => 0 }
71
         ),
72
   };
73
   bless $self, $class;
74
   return $self;
14 rodolico 75
}
76
 
16 rodolico 77
#-----------------------------
78
# apiRequest: API request dispatcher
79
#-----------------------------
80
sub apiRequest {
14 rodolico 81
 
16 rodolico 82
   if ($useCurl) {
83
       return apiRequestCurl(@_);
14 rodolico 84
   } else {
16 rodolico 85
       return apiRequestLwp(@_);
14 rodolico 86
   }
87
}
88
 
16 rodolico 89
#-----------------------------
90
# apiRequestCurl: API request using curl
91
#-----------------------------
92
sub apiRequestCurl {
14 rodolico 93
   my ($self, $endpoint, $method, $data) = @_;
94
   $method ||= 'GET';
16 rodolico 95
   my $url = $self->{baseUrl} . $endpoint;
14 rodolico 96
 
97
   my @data = ();
98
   push @data, '--request', $method;
99
   push @data, "--header 'Content-Type: application/json'" if ( $method eq 'POST' || $method eq 'PUT' );
100
   push @data, "--user '$self->{apiKey}:$self->{apiSecret}'";
101
   push @data, "--data '" . encode_json($data) . "'" if $data;
102
   my $cmd = join(' ', $self->{ua}, @data, $url);
16 rodolico 103
   die "In apiRequestCurl, command is:\n $cmd" if $debug;
14 rodolico 104
   my $json_text = `$cmd`;
105
   if ( $json_text =~ /<\?xml/) {
106
      # returned an XML string, just send it
107
      return $json_text;
108
   }
109
   return decode_json($json_text);
110
}
111
 
112
 
16 rodolico 113
#-----------------------------
114
# apiRequestLwp: API request using LWP
115
#-----------------------------
116
sub apiRequestLwp {
14 rodolico 117
    my ($self, $endpoint, $method, $data) = @_;
118
    $method ||= 'GET';
16 rodolico 119
    my $url = $self->{baseUrl} . $endpoint;
14 rodolico 120
    my $req = HTTP::Request->new($method => $url);
121
    $req->header('Content-Type' => 'application/json');
122
    $req->header('Authorization' => 'key ' . $self->{apiKey} . ':' . $self->{apiSecret});
16 rodolico 123
    die "In apiRequestLwp, request object:\n" . Dumper($req);
14 rodolico 124
    $req->content(encode_json($data)) if $data;
125
    my $res = $self->{ua}->request($req);
126
    return decode_json($res->decoded_content) if $res->is_success;
127
    die "API request failed: " . $res->status_line;
128
 
129
}
130
 
16 rodolico 131
#-----------------------------
132
# getVpnUsers: get VPN users
133
#-----------------------------
134
sub getVpnUsers {
14 rodolico 135
    my ($self) = @_;
136
    my $return = {};
137
    my $endpoint = "/api/openvpn/export/accounts/$self->{ovpnIndex}";
16 rodolico 138
    my $users = $self->apiRequest($endpoint);
17 rodolico 139
    #print "In get_vpn_users, users object:\n" . Dumper($users); die;
14 rodolico 140
    foreach my $user ( keys %$users ) {
17 rodolico 141
      next unless $user;
142
      # the username can be in the array users (preferable) or in the description
143
      my $username = ($users->{$user}->{'users'}->[0] ? $users->{$user}->{'users'}->[0] : $users->{$user}->{'description'} );
144
      # we do not allow usernames with spaces in our setup
145
      next if $username =~ m/ /;
146
#         $user && 
147
#         $users->{$user}->{'users'} &&
148
#         ref($users->{$user}->{'users'}) eq 'ARRAY'
149
#         && @{$users->{$user}->{'users'}} > 0;
14 rodolico 150
         # only return the first user in the array
17 rodolico 151
      $return->{$user} = $username;
14 rodolico 152
    }
17 rodolico 153
#    print "In get_vpn_users, return object:\n" . Dumper($return); die;
14 rodolico 154
    return $return;
155
}
156
 
16 rodolico 157
#-----------------------------
158
# getAllUsers: get all users on the system
159
#-----------------------------
14 rodolico 160
# returns a hashref keyed by username, value is the user object
161
# The api is seriously broken. It is supposed to be /api/system/user, but that returns an error
162
# so, we download the entire config and extract the users from there
16 rodolico 163
sub getAllUsers {
14 rodolico 164
    my ($self) = @_;
165
    my $endpoint = "/api/core/backup/download/this";
166
    my $xml = XML::Simple->new();
16 rodolico 167
    my $data = $self->apiRequest($endpoint);
14 rodolico 168
    my $config = $xml->XMLin($data);
169
    my $return = {};
170
    if (ref($config->{system}->{user}) eq 'ARRAY') {
171
        foreach my $user (@{$config->{system}->{user}}) {
172
            $return->{$user->{name}} = $user;
173
        }
174
    } elsif (ref($config->{system}->{user}) eq 'HASH') {
175
        $return = $config->{system}->{user};
176
    }
177
    return $return;
178
}
179
 
16 rodolico 180
#-----------------------------
181
# getVpnProviders: get VPN providers
182
#-----------------------------
183
sub getVpnProviders {
14 rodolico 184
   my ($self) = @_;
185
   my $endpoint = "/api/openvpn/export/providers";
186
   my $return = {};
16 rodolico 187
   my $providers = $self->apiRequest($endpoint);
14 rodolico 188
   #die "In getVPNProviders, providers object:\n" . Dumper($providers);
189
   return $return unless
190
      ref($providers) eq 'HASH' && keys %$providers;
191
    # key by vpnid, value is name
192
   foreach my $provider ( keys %$providers ) {
193
       $return->{$providers->{$provider}->{'vpnid'}} = $providers->{$provider}->{'name'};
194
    }
195
   return $return; 
196
}
197
 
16 rodolico 198
#-----------------------------
199
# getVpnConfig: get VPN configuration file
200
#-----------------------------
201
sub getVpnConfig {
14 rodolico 202
   my ( $self, $cert ) = @_;
203
   my $endpoint = "/api/openvpn/export/download/$self->{ovpnIndex}/$cert";
204
   my $payload = ();
205
   $payload->{'openvpn_export'} = {
206
       validate_server_cn => 1,
207
       hostname => $self->{hostname},
208
       template => $self->{template},
209
       auth_nocache => 0,
210
       p12_password_confirm => "",
211
       random_local_port => 1,
212
       servers => "\"1\"",
213
       plain_config => "",
214
       p12_password => "",
17 rodolico 215
       local_port => $self->{localPort},
14 rodolico 216
       cryptoapi => 0
217
   };
16 rodolico 218
   $debug = 0;
219
   my $return = $self->apiRequest($endpoint, 'POST', $payload);
14 rodolico 220
   return $return;
221
}
222
 
223
 
224
1;