2021-11-11 18:31:28 +00:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
from flask import Blueprint, request
|
2021-11-11 18:45:57 +00:00
|
|
|
from flask_restful import Resource, reqparse
|
2021-11-15 13:49:06 +00:00
|
|
|
import portalocker
|
|
|
|
import json
|
2021-11-11 18:31:28 +00:00
|
|
|
|
|
|
|
from selfprivacy_api.resources.services import api
|
|
|
|
|
|
|
|
# Enable SSH
|
|
|
|
class EnableSSH(Resource):
|
|
|
|
def post(self):
|
2021-11-15 13:49:06 +00:00
|
|
|
with portalocker.Lock("/etc/nixos/userdata/userdata.json", "r+") as f:
|
|
|
|
portalocker.lock(f, portalocker.LOCK_EX)
|
|
|
|
try:
|
|
|
|
data = json.load(f)
|
|
|
|
if "ssh" not in data:
|
|
|
|
data["ssh"] = {}
|
|
|
|
data["ssh"]["enable"] = True
|
|
|
|
f.seek(0)
|
|
|
|
json.dump(data, f, indent=4)
|
|
|
|
f.truncate()
|
|
|
|
finally:
|
|
|
|
portalocker.unlock(f)
|
2021-11-11 18:31:28 +00:00
|
|
|
|
|
|
|
return {
|
|
|
|
"status": 0,
|
|
|
|
"message": "SSH enabled",
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
# Write new SSH key
|
|
|
|
class WriteSSHKey(Resource):
|
|
|
|
def put(self):
|
2021-11-11 18:45:57 +00:00
|
|
|
parser = reqparse.RequestParser()
|
|
|
|
parser.add_argument(
|
|
|
|
"public_key", type=str, required=True, help="Key cannot be blank!"
|
|
|
|
)
|
|
|
|
args = parser.parse_args()
|
2021-11-11 18:31:28 +00:00
|
|
|
|
2021-11-11 18:45:57 +00:00
|
|
|
publicKey = args["public_key"]
|
2021-11-11 18:31:28 +00:00
|
|
|
|
2021-11-15 13:49:06 +00:00
|
|
|
with portalocker.Lock("/etc/nixos/userdata/userdata.json", "r+") as f:
|
|
|
|
portalocker.lock(f, portalocker.LOCK_EX)
|
|
|
|
try:
|
|
|
|
data = json.load(f)
|
|
|
|
if "ssh" not in data:
|
|
|
|
data["ssh"] = {}
|
|
|
|
# Return 400 if key already in array
|
|
|
|
for key in data["ssh"]["rootSshKeys"]:
|
|
|
|
if key == publicKey:
|
|
|
|
return {
|
|
|
|
"error": "Key already exists",
|
|
|
|
}, 400
|
|
|
|
data["ssh"]["rootSshKeys"].append(publicKey)
|
|
|
|
f.seek(0)
|
|
|
|
json.dump(data, f, indent=4)
|
|
|
|
f.truncate()
|
|
|
|
finally:
|
|
|
|
portalocker.unlock(f)
|
2021-11-11 18:31:28 +00:00
|
|
|
|
|
|
|
return {
|
|
|
|
"status": 0,
|
2021-11-15 13:49:06 +00:00
|
|
|
"message": "New SSH key successfully written",
|
2021-11-11 18:31:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
api.add_resource(EnableSSH, "/ssh/enable")
|
|
|
|
api.add_resource(WriteSSHKey, "/ssh/key/send")
|