Subversion Repositories web_pages

Rev

Rev 14 | Go to most recent revision | 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
14 rodolico 33
 
34
package opnsense;
35
use strict;
36
use warnings;
37
 
38
use LWP::UserAgent;
39
use JSON;
40
use Data::Dumper;
41
use XML::Simple;
42
 
16 rodolico 43
our $VERSION = "1.0.0";
14 rodolico 44
 
16 rodolico 45
our $useCurl = 1; # set to 1 to use curl for API requests, 0 to use LWP
46
our $debug = 0;    # set to 1 for debug output
14 rodolico 47
 
16 rodolico 48
#-----------------------------
49
# new: Constructor
50
#-----------------------------
14 rodolico 51
sub new {
16 rodolico 52
   my ($class, %args) = @_;
53
   my $self = {
54
      baseUrl   => $args{url},
55
      apiKey    => $args{apiKey},
56
      apiSecret => $args{apiSecret},
57
      ovpnIndex => $args{ovpnIndex},
58
      template  => $args{template},
59
      hostname  => $args{hostname},
60
      localPort => $args{localPort},
61
      ua        => $useCurl ?
62
         'curl -s --insecure' :
63
         LWP::UserAgent->new(
64
            ssl_opts => { verify_hostname => 0, SSL_verify_mode => 0 }
65
         ),
66
   };
67
   bless $self, $class;
68
   return $self;
14 rodolico 69
}
70
 
16 rodolico 71
#-----------------------------
72
# apiRequest: API request dispatcher
73
#-----------------------------
74
sub apiRequest {
14 rodolico 75
 
16 rodolico 76
   if ($useCurl) {
77
       return apiRequestCurl(@_);
14 rodolico 78
   } else {
16 rodolico 79
       return apiRequestLwp(@_);
14 rodolico 80
   }
81
}
82
 
16 rodolico 83
#-----------------------------
84
# apiRequestCurl: API request using curl
85
#-----------------------------
86
sub apiRequestCurl {
14 rodolico 87
   my ($self, $endpoint, $method, $data) = @_;
88
   $method ||= 'GET';
16 rodolico 89
   my $url = $self->{baseUrl} . $endpoint;
14 rodolico 90
 
91
   my @data = ();
92
   push @data, '--request', $method;
93
   push @data, "--header 'Content-Type: application/json'" if ( $method eq 'POST' || $method eq 'PUT' );
94
   push @data, "--user '$self->{apiKey}:$self->{apiSecret}'";
95
   push @data, "--data '" . encode_json($data) . "'" if $data;
96
   my $cmd = join(' ', $self->{ua}, @data, $url);
16 rodolico 97
   die "In apiRequestCurl, command is:\n $cmd" if $debug;
14 rodolico 98
   my $json_text = `$cmd`;
99
   if ( $json_text =~ /<\?xml/) {
100
      # returned an XML string, just send it
101
      return $json_text;
102
   }
103
   return decode_json($json_text);
104
}
105
 
106
 
16 rodolico 107
#-----------------------------
108
# apiRequestLwp: API request using LWP
109
#-----------------------------
110
sub apiRequestLwp {
14 rodolico 111
    my ($self, $endpoint, $method, $data) = @_;
112
    $method ||= 'GET';
16 rodolico 113
    my $url = $self->{baseUrl} . $endpoint;
14 rodolico 114
    my $req = HTTP::Request->new($method => $url);
115
    $req->header('Content-Type' => 'application/json');
116
    $req->header('Authorization' => 'key ' . $self->{apiKey} . ':' . $self->{apiSecret});
16 rodolico 117
    die "In apiRequestLwp, request object:\n" . Dumper($req);
14 rodolico 118
    $req->content(encode_json($data)) if $data;
119
    my $res = $self->{ua}->request($req);
120
    return decode_json($res->decoded_content) if $res->is_success;
121
    die "API request failed: " . $res->status_line;
122
 
123
}
124
 
16 rodolico 125
#-----------------------------
126
# getVpnUsers: get VPN users
127
#-----------------------------
128
sub getVpnUsers {
14 rodolico 129
    my ($self) = @_;
130
    my $return = {};
131
    my $endpoint = "/api/openvpn/export/accounts/$self->{ovpnIndex}";
16 rodolico 132
    my $users = $self->apiRequest($endpoint);
14 rodolico 133
    # die "In get_vpn_users, users object:\n" . Dumper($users);
134
    foreach my $user ( keys %$users ) {
135
      next unless
136
         $user && 
137
         $users->{$user}->{'users'} &&
138
         ref($users->{$user}->{'users'}) eq 'ARRAY'
139
         && @{$users->{$user}->{'users'}} > 0;
140
         # only return the first user in the array
141
      $return->{$user} = $users->{$user}->{'users'}->[0];
142
    }
143
    #die Dumper($return);
144
    return $return;
145
}
146
 
16 rodolico 147
#-----------------------------
148
# getAllUsers: get all users on the system
149
#-----------------------------
14 rodolico 150
# returns a hashref keyed by username, value is the user object
151
# The api is seriously broken. It is supposed to be /api/system/user, but that returns an error
152
# so, we download the entire config and extract the users from there
16 rodolico 153
sub getAllUsers {
14 rodolico 154
    my ($self) = @_;
155
    my $endpoint = "/api/core/backup/download/this";
156
    my $xml = XML::Simple->new();
16 rodolico 157
    my $data = $self->apiRequest($endpoint);
14 rodolico 158
    my $config = $xml->XMLin($data);
159
    my $return = {};
160
    if (ref($config->{system}->{user}) eq 'ARRAY') {
161
        foreach my $user (@{$config->{system}->{user}}) {
162
            $return->{$user->{name}} = $user;
163
        }
164
    } elsif (ref($config->{system}->{user}) eq 'HASH') {
165
        $return = $config->{system}->{user};
166
    }
167
    return $return;
168
}
169
 
16 rodolico 170
#-----------------------------
171
# getVpnProviders: get VPN providers
172
#-----------------------------
173
sub getVpnProviders {
14 rodolico 174
   my ($self) = @_;
175
   my $endpoint = "/api/openvpn/export/providers";
176
   my $return = {};
16 rodolico 177
   my $providers = $self->apiRequest($endpoint);
14 rodolico 178
   #die "In getVPNProviders, providers object:\n" . Dumper($providers);
179
   return $return unless
180
      ref($providers) eq 'HASH' && keys %$providers;
181
    # key by vpnid, value is name
182
   foreach my $provider ( keys %$providers ) {
183
       $return->{$providers->{$provider}->{'vpnid'}} = $providers->{$provider}->{'name'};
184
    }
185
   return $return; 
186
}
187
 
16 rodolico 188
#-----------------------------
189
# getVpnConfig: get VPN configuration file
190
#-----------------------------
191
sub getVpnConfig {
14 rodolico 192
   my ( $self, $cert ) = @_;
193
   my $endpoint = "/api/openvpn/export/download/$self->{ovpnIndex}/$cert";
194
   my $payload = ();
195
   $payload->{'openvpn_export'} = {
196
       validate_server_cn => 1,
197
       hostname => $self->{hostname},
198
       template => $self->{template},
199
       auth_nocache => 0,
200
       p12_password_confirm => "",
201
       random_local_port => 1,
202
       servers => "\"1\"",
203
       plain_config => "",
204
       p12_password => "",
205
       local_port => $self->{localport},
206
       cryptoapi => 0
207
   };
16 rodolico 208
   $debug = 0;
209
   my $return = $self->apiRequest($endpoint, 'POST', $payload);
14 rodolico 210
   return $return;
211
}
212
 
213
 
214
1;