automating openvpn configuration with php
Written by: daniel
July 21, 2010
Virtual Private Networks can be very handy, but even with easy-rsa scripts it’s a little time taking to add new computers to the network, especially if you frecuently add new machines.
With this handy php script you can automate this process a little bit - you could for example publish it on a web server and then make customers to connet to it in order to generate their access keys and configuration (It would be a good idea to password protect it first
)
You will need to generate the CA key and certificate first before you will be able to use it.
Check this guide on how to do it:
http://www.openvpn.net/index.php/open-source/documentation/howto.html#pki
and here goes the code:
//this should be unique for each client
$commonName = 'ayd-test';
$tmpDir = '/tmp/openvpn-'.time();
$dn = array(
"countryName" => 'ES',
"stateOrProvinceName" => 'Baleares',
"localityName" => 'Palma de Mallorca',
"organizationName" => 'AYD',
"organizationalUnitName" => 'AYD test',
"commonName" => $commonName,
"emailAddress" => 'test@test.com'
);
$privkeypass = null;
$numberofdays = 3650;
//load previously generated server private key
$fp=fopen("./ca.key","r");
$caData = fread($fp,8192);
fclose($fp);
// $passphrase is required if your key is encoded (suggested)
$caKey = openssl_get_privatekey($caData);
//load previously generated server cartificate
$fp=fopen("./ca.crt","r");
$caCrt = fread($fp,8192);
fclose($fp);
//--------------- generating a new user cert and key -------------
// create private key for the user
$privkey = openssl_pkey_new();
openssl_pkey_export($privkey, $privatekey, $privkeypass);
//make certificate request for the user
$csr = openssl_csr_new($dn, $privatekey);
openssl_csr_export($csr, $csrStr);
//sign certificate request with the CA key
$sscert = openssl_csr_sign($csrStr, $caCrt, $caKey, $numberofdays);
openssl_x509_export($sscert, $publickey);
//create a tmp dir
mkdir($tmpDir);
//write a private key
echo "writting private key...\n";
echo $privatekey; // Will hold the exported PriKey
file_put_contents($tmpDir."/".$commonName.'.key', $privatekey);
//write an user cert
echo "writting ceritifate...\n";
echo $publickey; // Will hold the exported Certificate
file_put_contents($tmpDir."/".$commonName.'.crt', $publickey);
//copy server certificate (we need it for openvpn config)
copy('./ca.crt', $tmpDir.'/ca.crt');
//generate and write openvpn config file
//edit data for according to your configuration
$config = "client
dev tun
tun-mtu 1200
proto udp
remote yourserver.com 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca /etc/openvpn/server_ca.crt
cert /etc/openvpn/$commonName.crt
key /etc/openvpn/{$commonName}.key
comp-lzo
verb 5
";
file_put_contents($tmpDir.'/server.conf', $config);
echo "generated files are in: ".$tmpDir;
you can then copy the generated files to your /etc/openvpn directory and you should be able to connect to the vpn.
Posted in


