tilde-oauth/auth/setKey.php

79 lines
2.3 KiB
PHP
Raw Normal View History

2022-05-07 08:02:58 +00:00
<?php
// Create an account and apply SSH key
2023-10-02 00:29:59 +00:00
$config = json_decode(file_get_contents("/var/www/usergen/secret/config.json", true));
2022-05-07 08:02:58 +00:00
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(){
apiResult(array("status" => true));
}
function error($error){
apiResult(array("status" => false, "error" => $error));
}
function validateUsername($username){
return (preg_match("/^([a-zA-Z0-9_.]+)$/", $username) == 1);
}
2022-05-07 23:45:13 +00:00
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);
}
2022-05-07 08:02:58 +00:00
if (checkParameters(array("pubkey", "userId", "authToken"))){
error("Missing parameters");
}
$userToken = $_POST["authToken"];
$userId = $_POST["userId"];
$pubkey = $_POST["pubkey"];
2022-05-07 23:45:13 +00:00
if(!validatePublicKey($pubkey)){
error("Invalid public key");
}
2022-05-07 08:02:58 +00:00
$request = curl_init();
curl_setopt($request, CURLOPT_URL, "https://hackers.town/api/v1/accounts/verify_credentials");
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($request, CURLOPT_HTTPHEADER, array(
"Authorization: Bearer ".$userToken
));
$response = curl_exec($request);
curl_close($request);
$User = json_decode($response);
// Check User
if($User->id != $userId){
error("User Mismatch");
}
if(!validateUsername($User->username)){
error("Invalid Username");
}
// Create temporary pubkey holding file
2022-06-26 02:40:39 +00:00
$TempFileName = "/etc/ttyserver/tmp/".uniqid("ssh-", true).".pub";
2022-05-07 08:02:58 +00:00
if(!file_put_contents($TempFileName, $pubkey."\n")){
error("Key Addition Failed: Temp");
}
// Run User Generation Tool
// TODO: Replace with custom Rust PHP Extension
2022-06-26 02:40:39 +00:00
$UserGenCode = shell_exec("/usr/bin/sudo /etc/ttyserver/bin/mkuser \"".$User->username."\" \"".$TempFileName."\" 2>&1; echo $?");
2022-05-07 08:02:58 +00:00
if($UserGenCode != "0"){
error("Key Addition Failed: MK-".$UserGenCode);
}
success();
2023-10-02 00:29:59 +00:00
?>