Subversion Repositories web_pages

Rev

Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

# Copyright (c) 2025, Daily Data, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list
#    of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice, this
#    list of conditions and the following disclaimer in the documentation and/or other
#    materials provided with the distribution.
# 3. Neither the name of Daily Data, Inc. nor the names of its contributors may be
#    used to endorse or promote products derived from this software without specific
#    prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
# DAMAGE.

package opnsense;

use strict;
use warnings;

use LWP::UserAgent;
use JSON;
use Data::Dumper;
use XML::Simple;


our $USE_CURL = 1; # set to 1 to use curl for API requests, 0 to use LWP
our $DEBUG = 0;    # set to 1 for debug output

sub new {
    my ($class, %args) = @_;
    my $self = {
        base_url => $args{url},
        apiKey  => $args{apiKey},
        apiSecret => $args{apiSecret},
        ovpnIndex => $args{ovpnIndex},
        template => $args{template},
        hostname => $args{hostname},
        localport => $args{localport},
        ua => $USE_CURL ? 
           'curl -s --insecure' :
           LWP::UserAgent->new(
              ssl_opts => { verify_hostname => 0, SSL_verify_mode => 0 }
           ),
    };
    bless $self, $class;
    return $self;
}

sub api_request {

   if ( $USE_CURL ) {
       return api_request_curl(@_);
   } else {
       return api_request_lwp(@_);
   }
}

sub api_request_curl {
   my ($self, $endpoint, $method, $data) = @_;
   $method ||= 'GET';
   my $url = $self->{base_url} . $endpoint;

   my @data = ();
   push @data, '--request', $method;
   push @data, "--header 'Content-Type: application/json'" if ( $method eq 'POST' || $method eq 'PUT' );
   push @data, "--user '$self->{apiKey}:$self->{apiSecret}'";
   push @data, "--data '" . encode_json($data) . "'" if $data;
   my $cmd = join(' ', $self->{ua}, @data, $url);
   die "In api_request_curl, command is:\n $cmd" if $DEBUG;
   my $json_text = `$cmd`;
   if ( $json_text =~ /<\?xml/) {
      # returned an XML string, just send it
      return $json_text;
   }
   return decode_json($json_text);
}


sub api_request_lwp {
    my ($self, $endpoint, $method, $data) = @_;
    $method ||= 'GET';
    my $url = $self->{base_url} . $endpoint;
    my $req = HTTP::Request->new($method => $url);
    $req->header('Content-Type' => 'application/json');
    $req->header('Authorization' => 'key ' . $self->{apiKey} . ':' . $self->{apiSecret});
    die "In api_request_lwp, request object:\n" . Dumper($req);
    $req->content(encode_json($data)) if $data;
    my $res = $self->{ua}->request($req);
    return decode_json($res->decoded_content) if $res->is_success;
    die "API request failed: " . $res->status_line;

}

sub get_vpn_users {
    my ($self) = @_;
    my $return = {};
    my $endpoint = "/api/openvpn/export/accounts/$self->{ovpnIndex}";
    my $users = $self->api_request($endpoint);
    # die "In get_vpn_users, users object:\n" . Dumper($users);
    foreach my $user ( keys %$users ) {
      next unless
         $user && 
         $users->{$user}->{'users'} &&
         ref($users->{$user}->{'users'}) eq 'ARRAY'
         && @{$users->{$user}->{'users'}} > 0;
         # only return the first user in the array
      $return->{$user} = $users->{$user}->{'users'}->[0];
    }
    #die Dumper($return);
    return $return;
}

# get all users on the system
# returns a hashref keyed by username, value is the user object
# The api is seriously broken. It is supposed to be /api/system/user, but that returns an error
# so, we download the entire config and extract the users from there
sub get_all_users {
    my ($self) = @_;
    my $endpoint = "/api/core/backup/download/this";
    my $xml = XML::Simple->new();
    my $data = $self->api_request($endpoint);
    my $config = $xml->XMLin($data);
    my $return = {};
    if (ref($config->{system}->{user}) eq 'ARRAY') {
        foreach my $user (@{$config->{system}->{user}}) {
            $return->{$user->{name}} = $user;
        }
    } elsif (ref($config->{system}->{user}) eq 'HASH') {
        $return = $config->{system}->{user};
    }
    return $return;
}

sub get_vpn_providers {
   my ($self) = @_;
   my $endpoint = "/api/openvpn/export/providers";
   my $return = {};
   my $providers = $self->api_request($endpoint);
   #die "In getVPNProviders, providers object:\n" . Dumper($providers);
   return $return unless
      ref($providers) eq 'HASH' && keys %$providers;
    # key by vpnid, value is name
   foreach my $provider ( keys %$providers ) {
       $return->{$providers->{$provider}->{'vpnid'}} = $providers->{$provider}->{'name'};
    }
   return $return; 
}

###
# get VPN configuration file
sub get_vpn_config {
   my ( $self, $cert ) = @_;
   my $endpoint = "/api/openvpn/export/download/$self->{ovpnIndex}/$cert";
   my $payload = ();
   $payload->{'openvpn_export'} = {
       validate_server_cn => 1,
       hostname => $self->{hostname},
       template => $self->{template},
       auth_nocache => 0,
       p12_password_confirm => "",
       random_local_port => 1,
       servers => "\"1\"",
       plain_config => "",
       p12_password => "",
       local_port => $self->{localport},
       cryptoapi => 0
   };
   $DEBUG = 0;
   my $return = $self->api_request($endpoint, 'POST', $payload);
   return $return;
}


1;