#!/bin/sh
#
# ovpn_auth_verify_async
#
# part of pfSense (https://www.pfsense.org)
# Copyright (c) 2004-2018 Rubicon Communications, LLC (Netgate)
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

#----------- Plugin Environment Variables
# username          - client username
# password          - client password
# auth_control_file - path to which a 0 or 1 is written to indicate success

#----------- pfSense Arguments 
# --- All
# type              - $1 
# --- User 
# authcfg           - $2
# strictcn          - $3
# modeid            - $4
# nas_port          - $5

# ---------- Command Definitions
fcgicli="/usr/local/sbin/fcgicli"
openssl="/usr/bin/openssl"
sed="/usr/bin/sed"
auth_user_php="/etc/inc/openvpn.auth-user.php"

# ---------- Constants
auth_success=1
auth_failure=0

# ---------- Capture Arguments 
authcfg=$2
strictcn=$3
modeid=$4
nas_port=$5

# ---------- Convert Username & Password to Base64

# Single quoting $password breaks getting the value from the variable.
# Base64 and urlEncode usernames and passwords
password=$(printf "%s" "${password}" | "${openssl}" enc -base64 | \
    "${sed}" -e 's_=_%3D_g;s_+_%2B_g;s_/_%2F_g')
username=$(printf "%s" "${username}" | "${openssl}" enc -base64 | \
    "${sed}" -e 's_=_%3D_g;s_+_%2B_g;s_/_%2F_g')

# ---------- Perform Check
auth_credentials="username=${username}&password=${password}"
# Note that common_name is also assumed to be set by the environment
auth_server_1="cn=${common_name}&strictcn=${strictcn}&authcfg=${authcfg}"
auth_server_2="modeid=${modeid}&nas_port=${nas_port}"
auth_args="${auth_credentials}&${auth_server_1}&${auth_server_2}"

result=$("${fcgicli}" -f "${auth_user_php}" -d "${auth_args}")

# ---------- Write the Result

auth_result="${auth_failure}"
if [ "${result}" = "OK" ]; then
    auth_result="${auth_success}"
fi

# The output file path should be set in the environment
printf "%s" "${auth_result}" > "${auth_control_file}"

exit 0
