Score:0

OpenVPN adding static ip for client dynamically based on a script

cn flag

In my VPN logic all of my client certificates have the folowing CN template:

number.mycompany.com where number is between 2-65536

For each CN I add a config file which looks like so:

$ cat 65501.mycompany.com
ifconfig-push 10.22.255.221 255.255.0.0

So basically based on the CN number area I configure the static ip in the relevant file, conversion from number to ip logic:

$ python3 -c "print('10.22.{}.{}'.format(*divmod(65501, 256)))"
10.22.255.221

Is there a way to do it dynamically in the config with a script or something else, instead of adding client config file everytime?

Score:0
cn flag

Reading the manuall carefully I saw it's possible to add a script with the ability to dynamically change the config per client using the --client-connect flag.

I added the following config line to my server.conf file:

client-connect /etc/openvpn/client_set_static_ip.sh

and the file content is the following bash script:

#!/usr/bin/env bash

DYNAMIC_GENERATED_CONFIG_PATH=$1

function get_client_num() {
  # returns the client number from the `common_name` env variable
  local cn_arr=(${common_name//./ })
  local cn_arr_first=${cn_arr[0]}
  echo "${cn_arr_first}"
}

function generate_client_ip() {
  # returns generated remote client ip from the `ifconfig_pool_remote_ip` env variable and client_num
  local ifconfig_remote_arr=(${ifconfig_pool_remote_ip//./ })

  local client_num=$(get_client_num)
  local remote_ip_octet_1=${ifconfig_remote_arr[0]}
  local remote_ip_octet_2=${ifconfig_remote_arr[1]}
  local remote_ip_octet_3=$((client_num/256))
  local remote_ip_octet_4=$((client_num%256))

  echo "${remote_ip_octet_1}.${remote_ip_octet_2}.${remote_ip_octet_3}.${remote_ip_octet_4}"
}

  remote_ip=$(generate_client_ip)
  echo "ifconfig-push ${remote_ip} 255.255.0.0" > "${DYNAMIC_GENERATED_CONFIG_PATH}"
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.