Guest User

Keenetic OpenVPN management script

a guest
May 7th, 2020
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 2.25 KB | None | 0 0
  1. #!/bin/sh
  2.  
  3. HOST=192.168.0.1 # Keenetic IP address
  4. PORT=80          # Keenetic web-interface port
  5. USER=user        # Keenetic web-interface user
  6. PASS=pa$$word    # and their password
  7.  
  8. VPN_IFACE=OpenVPN0    # OpenVPN service interface ID, see 'show interfaces' CLI
  9. VPN_DESC=TestVPN      # OpenVPN service description, any string
  10. VPN_USER=new@TestVPN  # A new VPN user name  
  11. VPN_PASS=newPassword  # A new VPN password
  12.  
  13. JAR=/tmp/ovpn-jar
  14. TMP=/tmp/ovpn-tmp
  15. TMP2=/tmp/ovpn-patched
  16.  
  17. # compute password hash required to log into Keenetic's
  18. # web-interface: acquire new session cookie,
  19. # new password challenge and a realm from the router
  20. OPTS='-s -c '$JAR' -b '$JAR
  21. AUTH=`curl -v $OPTS http://$HOST:$PORT/auth 2>&1`
  22. CHALLENGE=`printf "$AUTH" | grep 'X-NDM-Challenge' | cut -d ':' -f2 | sed 's/ //' | tr -d '\r'`
  23. REALM=`printf "$AUTH" | grep 'X-NDM-Realm' | cut -d ':' -f2 | sed 's/ //' | tr -d '\r'`
  24.  
  25. # compute password hash
  26. printf "$USER:$REALM:$PASS" > $TMP
  27. HASH=`md5sum $TMP | cut -d ' ' -f1`
  28. printf "$CHALLENGE$HASH" > $TMP
  29. HASH=`sha256sum $TMP | cut -d ' ' -f1`
  30.  
  31. # now, use user and computed hash to log into the router
  32. curl $OPTS -X POST http://$HOST:$PORT/auth \
  33.   -H 'Content-Type: application/json;charset=UTF-8' \
  34.   --data-binary "{\"login\":\"$USER\",\"password\":\"$HASH\"}"
  35.  
  36. # get OpenVPN config via REST, and patch it to insert new VPN credentials
  37. curl $OPTS http://$HOST:$PORT/rci/interface | jq '.'"$VPN_IFACE"'.openvpn.config.config' > $TMP
  38. sed 's/pass>.*</pass>\\n'$VPN_USER'\\n'$VPN_PASS'\\n</' < $TMP > $TMP2
  39.  
  40. # post new OpenVPN config back to the router, effectively applying it
  41. VPN_CONFIG=`cat $TMP2`
  42. # VPN_DATA must fit into a single line (!), a very long one:
  43. VPN_DATA='[{"interface":{"'"$VPN_IFACE"'":{"authentication":{"no":true}}}},{"interface":{"'"$VPN_IFACE"'":{"description":"'"$VPN_DESC"'","role":["misc"],"ip":{"tcp":{"adjust-mss":{"pmtu":true}},"address":{"no":true},"name-server":false,"mtu":{"no":true}},"openvpn":{"accept-routes":true,"config":{"config":'"$VPN_CONFIG"'},"connect":{"via":"","no":false}},"schedule":{"no":true}}}},{"system":{"configuration":{"save":true}}}]'
  44. curl $OPTS http://$HOST:$PORT/rci/ \
  45.   -H 'Content-Type: application/json;charset=UTF-8' \
  46.   --data-binary "$VPN_DATA"
  47.  
  48. # clean up
  49. rm $TMP2 $TMP $JAR
Add Comment
Please, Sign In to add comment