Skip to content

Commit 5492fe2

Browse files
authored
Create server.php
This is the backend for account.html, fixing some serious impersonation issues.
1 parent edf5acf commit 5492fe2

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

server.php

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
<?php
2+
session_start();
3+
4+
// Function to check if a Scratch username exists
5+
function checkScratchUser($username) {
6+
$url = "https://api.scratch.mit.edu/users/$username/";
7+
$response = @file_get_contents($url);
8+
return $response !== false;
9+
}
10+
11+
// Function to generate an RSA key pair
12+
function generateKeyPair($username) {
13+
$config = [
14+
"private_key_bits" => 2048,
15+
"private_key_type" => OPENSSL_KEYTYPE_RSA,
16+
];
17+
$res = openssl_pkey_new($config);
18+
openssl_pkey_export($res, $privateKey);
19+
$publicKey = openssl_pkey_get_details($res)["key"];
20+
21+
// Store public key on server
22+
file_put_contents("keys/$username.pub", $publicKey);
23+
24+
// Return private key to the user (normally, you'd encrypt this before sending)
25+
return $privateKey;
26+
}
27+
28+
// Handle user registration and key generation
29+
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["username"])) {
30+
$username = trim($_POST["username"]);
31+
32+
if (!checkScratchUser($username)) {
33+
echo json_encode(["error" => "Invalid Scratch username."]);
34+
exit;
35+
}
36+
37+
$privateKey = generateKeyPair($username);
38+
$_SESSION["username"] = $username;
39+
echo json_encode(["privateKey" => $privateKey]);
40+
exit;
41+
}
42+
43+
// Handle authentication challenge
44+
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["challengeResponse"])) {
45+
$username = $_SESSION["username"] ?? "";
46+
$challengeResponse = trim($_POST["challengeResponse"]);
47+
$publicKeyPath = "keys/$username.pub";
48+
49+
if (!file_exists($publicKeyPath)) {
50+
echo json_encode(["error" => "User not registered."]);
51+
exit;
52+
}
53+
54+
$publicKey = file_get_contents($publicKeyPath);
55+
openssl_public_decrypt(base64_decode($challengeResponse), $decrypted, $publicKey);
56+
57+
if ($decrypted === $_SESSION["challenge"] ?? "") {
58+
$_SESSION["authenticated"] = true;
59+
echo json_encode(["success" => "Login successful!"]);
60+
} else {
61+
echo json_encode(["error" => "Invalid key response."]);
62+
}
63+
exit;
64+
}

0 commit comments

Comments
 (0)