luci.openfortivpn 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/env lua
  2. local json = require "luci.jsonc"
  3. local fs = require "nixio.fs"
  4. local function readfile(path)
  5. if fs.stat(path, "type") == "reg" then
  6. local s = fs.readfile(path)
  7. return s and (s:gsub("^%s+", ""):gsub("%s+$", ""))
  8. else
  9. return null
  10. end
  11. end
  12. local function writefile(path, data)
  13. local n = fs.writefile(path, data)
  14. return (n == #data)
  15. end
  16. local function parseInput()
  17. local parse = json.new()
  18. local done, err
  19. while true do
  20. local chunk = io.read(4096)
  21. if not chunk then
  22. break
  23. elseif not done and not err then
  24. done, err = parse:parse(chunk)
  25. end
  26. end
  27. if not done then
  28. print(json.stringify({ error = err or "Incomplete input" }))
  29. os.exit(1)
  30. end
  31. return parse:get()
  32. end
  33. if arg[1] == "list" then
  34. print(json.stringify({
  35. getCertificates = {
  36. interface = "interface"
  37. },
  38. setCertificates = {
  39. interface = "interface",
  40. user_cert = "user_cert",
  41. user_key = "user_key",
  42. ca_file = "ca_file"
  43. }
  44. }))
  45. elseif arg[1] == "call" then
  46. local args = parseInput()
  47. if not args.interface or
  48. type(args.interface) ~= "string" or
  49. not args.interface:match("^[a-zA-Z0-9_]+$")
  50. then
  51. print(json.stringify({ error = "Invalid interface name" }))
  52. os.exit(1)
  53. end
  54. local user_cert_pem = string.format("/etc/openfortivpn/user-cert-%s.pem", args.interface)
  55. local user_key_pem = string.format("/etc/openfortivpn/user-key-%s.pem", args.interface)
  56. local ca_file_pem = string.format("/etc/openfortivpn/ca-%s.pem", args.interface)
  57. if arg[2] == "getCertificates" then
  58. print(json.stringify({
  59. user_cert = readfile(user_cert_pem),
  60. user_key = readfile(user_key_pem),
  61. ca_file = readfile(ca_file_pem)
  62. }))
  63. elseif arg[2] == "setCertificates" then
  64. if args.user_cert then
  65. writefile(user_cert_pem, args.user_cert)
  66. end
  67. if args.user_key then
  68. writefile(user_key_pem, args.user_key)
  69. end
  70. if args.ca_file then
  71. writefile(ca_file_pem, args.ca_file)
  72. end
  73. print(json.stringify({ result = true }))
  74. end
  75. end