Script to create cert.pem for Cloudflared tunnel

I tried this bash script to generate cert.pem certificate because I plan to use it on systems which not have any browser on board:

#!/bin/bash

## example parameters, adjust as needed
ORIGIN_CA_KEY="v1.0-foobar"
CF_API_KEY="asdfasdfasdfasdf"
CF_EMAIL="[email protected]"
TUNNEL_ZONE_ID="6795546b5945173001744653a958d6cf"
TUNNEL_HOSTNAMES='["mytunnel.example.com"]'
 
## now for the actual script:
set -e
 
curl -s https://api.cloudflare.com/client/v4/user/service_keys/origintunnel \
  -H "x-auth-key: $CF_API_KEY" \
  -H "x-auth-email: $CF_EMAIL" \
  | jq -r .result.service_key \
  > tunnel_service_key.txt
 
# generate private key
openssl ecparam -name prime256v1 -out tunnel_private_key_params.txt
openssl req -batch -new -newkey ec:tunnel_private_key_params.txt -nodes -out csr.txt -keyout tunnel_private_key.txt -subj "/C=US/CN=CloudFlare"
 
# make cert.pem, containing
# 1. Private key (in PKCS #8 format)
openssl pkcs8 -topk8 -in tunnel_private_key.txt -nocrypt -out cert.pem
 
# 2. public key from originCA
curl -s -XPOST https://api.cloudflare.com/client/v4/certificates \
  -H "Content-Type: application/json" \
  -H "X-Auth-User-Service-Key: $ORIGIN_CA_KEY" \
  -d "$(jq -n --arg csr "$(cat csr.txt)" --argjson hostnames "$TUNNEL_HOSTNAMES" '{hostnames:$hostnames,requested_validity:5475,request_type:"origin-ecc",csr:$csr}')" \
  | jq -r .result.certificate \
  >> cert.pem
 
# 3. Argo Tunnel token
echo "-----BEGIN ARGO TUNNEL TOKEN-----" >> cert.pem
echo -n "$(echo $TUNNEL_ZONE_ID; cat tunnel_service_key.txt)" | base64 | fold -w 64 >> cert.pem
echo "-----END ARGO TUNNEL TOKEN-----" >> cert.pem

It created successfully cert.pem file contained from 3 sections:


-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
-----BEGIN ARGO TUNNEL TOKEN-----
...
-----END ARGO TUNNEL TOKEN-----

but when I run command for creating tunnel this error message occured:

$ cloudflared tunnel create mytunnel
failed to create tunnel: couldn't create client to talk to Cloudflare Tunnel backend: Origin certificate needs to be refreshed before creating new tunnels.\nDelete /home/tun/.cloudflared/cert.pem and run "cloudflared login" to obtain a new cert.

I used my values of environment variables: ORIGIN_CA_KEY, CF_API_KEY, CF_EMAIL, TUNNEL_ZONE_ID, TUNNEL_HOSTNAMES and double checked it.

So maybe a reason - a new version of Cloudflared API and this script is outdated? Maybe someone has a fresh version of similar script?

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.