tilde-oauth/auth/setKey.php

81 lines
2.3 KiB
PHP

<?php
// Create an account and apply SSH key
$config = json_decode(file_get_contents("/var/www/usergen/secret/config.json", true));
require_once("/var/www/usergen/secret/helpers.php");
require_once("/var/www/usergen/secret/oauth.php");
require_once("/var/www/usergen/secret/rsa.php");
function checkParameters($parameterArray){
$error = false;
foreach($parameterArray as $parameter){
if(!isset($_POST[$parameter])){
$error = true;
}
}
return $error;
}
function apiResult($result){
header('Content-type: application/json');
echo json_encode($result);
exit();
}
function success($encryptedToken){
$Auth = verifyEncToken($encryptedToken);
returnSuccess(true, buildEncToken($Auth["AuthToken"], $Auth["UserID"], $_SERVER["REMOTE_ADDR"], $_SERVER["HTTP_USER_AGENT"]));
}
function error($error){
returnError($error);
}
function validateUsername($username){
return (preg_match("/^([a-zA-Z0-9_.]+)$/", $username) == 1);
}
function validatePublicKey($key){
return (preg_match("/^(ssh-rsa AAAAB3NzaC1yc2|ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNT|ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzOD|ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1Mj|ssh-ed25519 AAAAC3NzaC1lZDI1NTE5|ssh-dss AAAAB3NzaC1kc3)[0-9A-Za-z+\/]+[=]{0,3}( .*)?$/", $key) == 1);
}
if (checkParameters(array("pubkey", "token"))){
error("Missing parameters");
}
$userToken = $_POST["token"];
$pubkey = $_POST["pubkey"];
if(!validatePublicKey($pubkey)){
error("Invalid public key");
}
$User = verifyEncToken($userToken);
// Check User
if (gettype($User) == "string") {
// Invalid Token
error($User);
}else{
// Valid Token
$User = $User["MastodonData"];
}
if(!validateUsername($User->username)){
error("Invalid POSIX Username");
}
// Create temporary pubkey holding file
$TempFileName = "/etc/ttyserver/tmp/".uniqid("ssh-", true).".pub";
if(!file_put_contents($TempFileName, $pubkey."\n")){
error("Key Addition Failed: Temp");
}
// Run User Generation Tool
// TODO: Replace with custom Rust PHP Extension?
$UserGenCode = shell_exec("/usr/bin/sudo /etc/ttyserver/bin/mkuser \"".$User->username."\" \"".$TempFileName."\" 2>&1; echo $?");
if($UserGenCode != "0"){
error("Key Addition Failed: MK-".$UserGenCode);
}
success($userToken);
?>