Subversion Repositories web_pages

Rev

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