How to export OpenVPN config using the API?

Started by dataprolet, July 22, 2024, 12:32:29 PM

Previous topic - Next topic
July 22, 2024, 12:32:29 PM Last Edit: July 22, 2024, 12:42:30 PM by dataprolet
I can't wrap my head around the API to export an OpenVPN config.

I have created an OpenVPN instance, which has an ID (e. g. "12345678-1234-123a-a123-12a34b56c78d") and a description (e. g. "my-test-vpn"). I also created a user which has all "effective privileges" and an API key. Now I'm trying the following command:

curl -k -X POST "{$url}/api/openvpn/export/download" \
    -u "{$key}:{$secret}" \
    -H "Content-Type: application/json" \
    -d '{"vpnid": "12345678-1234-123a-a123-12a34b56c78d" , "certref": "my-test-vpn"}' \
    -o config.ovpn

This returns a file containing:
{"status":401,"message":"Authentication Failed"}

I followed these instructions:
https://docs.opnsense.org/development/api.html
https://docs.opnsense.org/development/api/core/openvpn.html

Is the vpnid even the right thing and what is the certref? I really don't get how to use this. Can somebody please help me?

July 23, 2024, 03:04:19 PM #1 Last Edit: July 23, 2024, 03:06:58 PM by dataprolet
Took me a day to figure this out, because the official documentation of the API is horrible.

You need a little more than just a simple curl:
/usr/bin/curl -s -k --location ${url}/api/openvpn/export/download/${vpnid}/${certref} \
    -u "$key":"$secret" \
    --header 'Content-Type: application/json' \
    --data "{\"openvpn_export\":{\"servers\":\"$vpnid\",\"template\":\"PlainOpenVPN\",\"hostname\":\"${ip}\",\"local_port\":\"${port}\",\"random_local_port\":\"1\",\"p12_password\":\"\",\"p12_password_confirm\":\"\",\"validate_server_cn\":\"1\",\"cryptoapi\":\"0\",\"auth_nocache\":\"0\",\"plain_config\":\"\"}}"


You can get the $vpnid from /api/openvpn/instances/search and the $certref from /api/openvpn/instances/get under "cert" (it a 13-letter ID).

This will return a file that contains the config encoded in base64.

The trick was to inspect the download button in the GUI and retreive the actual API call from there. Thanks to the kind user "Monviech" from IRC.

> because the official documentation of the API is horrible.

Thanks and feel free to help improve it. ;)


Cheers,
Franco