mirror of
https://github.com/kmc7468/arkvault.git
synced 2025-12-14 22:08:45 +00:00
클라이언트 등록시 검증키도 등록하도록 변경 (WiP)
This commit is contained in:
@@ -1,10 +1,21 @@
|
|||||||
import { and, eq, gt, lte } from "drizzle-orm";
|
import { and, or, eq, gt, lte, count } from "drizzle-orm";
|
||||||
import db from "./drizzle";
|
import db from "./drizzle";
|
||||||
import { client, userClient, userClientChallenge } from "./schema";
|
import { client, userClient, userClientChallenge } from "./schema";
|
||||||
|
|
||||||
export const createClient = async (pubKey: string, userId: number) => {
|
export const createClient = async (encPubKey: string, sigPubKey: string, userId: number) => {
|
||||||
return await db.transaction(async (tx) => {
|
return await db.transaction(async (tx) => {
|
||||||
const insertRes = await tx.insert(client).values({ pubKey }).returning({ id: client.id });
|
const clients = await tx
|
||||||
|
.select()
|
||||||
|
.from(client)
|
||||||
|
.where(or(eq(client.encPubKey, sigPubKey), eq(client.sigPubKey, encPubKey)));
|
||||||
|
if (clients.length > 0) {
|
||||||
|
throw new Error("Already used public key(s)");
|
||||||
|
}
|
||||||
|
|
||||||
|
const insertRes = await tx
|
||||||
|
.insert(client)
|
||||||
|
.values({ encPubKey, sigPubKey })
|
||||||
|
.returning({ id: client.id });
|
||||||
const { id: clientId } = insertRes[0]!;
|
const { id: clientId } = insertRes[0]!;
|
||||||
await tx.insert(userClient).values({ userId, clientId });
|
await tx.insert(userClient).values({ userId, clientId });
|
||||||
|
|
||||||
@@ -12,11 +23,28 @@ export const createClient = async (pubKey: string, userId: number) => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getClientByPubKey = async (pubKey: string) => {
|
export const getClient = async (clientId: number) => {
|
||||||
const clients = await db.select().from(client).where(eq(client.pubKey, pubKey)).execute();
|
const clients = await db.select().from(client).where(eq(client.id, clientId)).execute();
|
||||||
return clients[0] ?? null;
|
return clients[0] ?? null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const getClientByPubKeys = async (encPubKey: string, sigPubKey: string) => {
|
||||||
|
const clients = await db
|
||||||
|
.select()
|
||||||
|
.from(client)
|
||||||
|
.where(and(eq(client.encPubKey, encPubKey), eq(client.sigPubKey, sigPubKey)))
|
||||||
|
.execute();
|
||||||
|
return clients[0] ?? null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const countClientByPubKey = async (pubKey: string) => {
|
||||||
|
const clients = await db
|
||||||
|
.select({ count: count() })
|
||||||
|
.from(client)
|
||||||
|
.where(or(eq(client.encPubKey, pubKey), eq(client.encPubKey, pubKey)));
|
||||||
|
return clients[0]?.count ?? 0;
|
||||||
|
};
|
||||||
|
|
||||||
export const createUserClient = async (userId: number, clientId: number) => {
|
export const createUserClient = async (userId: number, clientId: number) => {
|
||||||
await db.insert(userClient).values({ userId, clientId }).execute();
|
await db.insert(userClient).values({ userId, clientId }).execute();
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,10 +1,17 @@
|
|||||||
import { sqliteTable, text, integer, primaryKey } from "drizzle-orm/sqlite-core";
|
import { sqliteTable, text, integer, primaryKey, unique } from "drizzle-orm/sqlite-core";
|
||||||
import { user } from "./user";
|
import { user } from "./user";
|
||||||
|
|
||||||
export const client = sqliteTable("client", {
|
export const client = sqliteTable(
|
||||||
id: integer("id").primaryKey(),
|
"client",
|
||||||
pubKey: text("public_key").notNull().unique(), // Base64
|
{
|
||||||
});
|
id: integer("id").primaryKey(),
|
||||||
|
encPubKey: text("encryption_public_key").notNull().unique(), // Base64
|
||||||
|
sigPubKey: text("signature_public_key").notNull().unique(), // Base64
|
||||||
|
},
|
||||||
|
(t) => ({
|
||||||
|
unq: unique().on(t.encPubKey, t.sigPubKey),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
export const userClient = sqliteTable(
|
export const userClient = sqliteTable(
|
||||||
"user_client",
|
"user_client",
|
||||||
|
|||||||
34
src/lib/server/modules/crypto.ts
Normal file
34
src/lib/server/modules/crypto.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import { constants, randomBytes, createPublicKey, publicEncrypt, verify } from "crypto";
|
||||||
|
import { promisify } from "util";
|
||||||
|
|
||||||
|
export const generateRandomBytes = async (length: number) => {
|
||||||
|
return await promisify(randomBytes)(length);
|
||||||
|
};
|
||||||
|
|
||||||
|
const makePubKeyPem = (pubKey: string) =>
|
||||||
|
`-----BEGIN PUBLIC KEY-----\n${pubKey}\n-----END PUBLIC KEY-----`;
|
||||||
|
|
||||||
|
export const verifyPubKey = (pubKey: string) => {
|
||||||
|
const pubKeyPem = makePubKeyPem(pubKey);
|
||||||
|
const pubKeyObject = createPublicKey(pubKeyPem);
|
||||||
|
return (
|
||||||
|
pubKeyObject.asymmetricKeyType === "rsa" &&
|
||||||
|
pubKeyObject.asymmetricKeyDetails?.modulusLength === 4096
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const encryptAsymmetric = (data: Buffer, encPubKey: string) => {
|
||||||
|
return publicEncrypt({ key: makePubKeyPem(encPubKey), oaepHash: "sha256" }, data);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const verifySignature = (data: string, signature: string, sigPubKey: string) => {
|
||||||
|
return verify(
|
||||||
|
"rsa-sha256",
|
||||||
|
Buffer.from(data, "base64"),
|
||||||
|
{
|
||||||
|
key: makePubKeyPem(sigPubKey),
|
||||||
|
padding: constants.RSA_PKCS1_PSS_PADDING,
|
||||||
|
},
|
||||||
|
Buffer.from(signature, "base64"),
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -1,17 +1,23 @@
|
|||||||
import { error } from "@sveltejs/kit";
|
import { error } from "@sveltejs/kit";
|
||||||
import { randomBytes, publicEncrypt, createPublicKey } from "crypto";
|
|
||||||
import ms from "ms";
|
import ms from "ms";
|
||||||
import { promisify } from "util";
|
|
||||||
import {
|
import {
|
||||||
createClient,
|
createClient,
|
||||||
getClientByPubKey,
|
getClient,
|
||||||
|
getClientByPubKeys,
|
||||||
|
countClientByPubKey,
|
||||||
createUserClient,
|
createUserClient,
|
||||||
getAllUserClients,
|
getAllUserClients,
|
||||||
getUserClient,
|
getUserClient,
|
||||||
|
setUserClientStateToPending,
|
||||||
createUserClientChallenge,
|
createUserClientChallenge,
|
||||||
getUserClientChallenge,
|
getUserClientChallenge,
|
||||||
setUserClientStateToPending,
|
|
||||||
} from "$lib/server/db/client";
|
} from "$lib/server/db/client";
|
||||||
|
import {
|
||||||
|
generateRandomBytes,
|
||||||
|
verifyPubKey,
|
||||||
|
encryptAsymmetric,
|
||||||
|
verifySignature,
|
||||||
|
} from "$lib/server/modules/crypto";
|
||||||
import { isInitialMekNeeded } from "$lib/server/modules/mek";
|
import { isInitialMekNeeded } from "$lib/server/modules/mek";
|
||||||
import env from "$lib/server/loadenv";
|
import env from "$lib/server/loadenv";
|
||||||
|
|
||||||
@@ -28,42 +34,53 @@ export const getUserClientList = async (userId: number) => {
|
|||||||
const expiresIn = ms(env.challenge.pubKeyExp);
|
const expiresIn = ms(env.challenge.pubKeyExp);
|
||||||
const expiresAt = () => new Date(Date.now() + expiresIn);
|
const expiresAt = () => new Date(Date.now() + expiresIn);
|
||||||
|
|
||||||
const generateChallenge = async (userId: number, ip: string, clientId: number, pubKey: string) => {
|
const generateChallenge = async (
|
||||||
const answer = await promisify(randomBytes)(32);
|
userId: number,
|
||||||
|
ip: string,
|
||||||
|
clientId: number,
|
||||||
|
encPubKey: string,
|
||||||
|
) => {
|
||||||
|
const answer = await generateRandomBytes(32);
|
||||||
const answerBase64 = answer.toString("base64");
|
const answerBase64 = answer.toString("base64");
|
||||||
await createUserClientChallenge(userId, clientId, answerBase64, ip, expiresAt());
|
await createUserClientChallenge(userId, clientId, answerBase64, ip, expiresAt());
|
||||||
|
|
||||||
const pubKeyPem = `-----BEGIN PUBLIC KEY-----\n${pubKey}\n-----END PUBLIC KEY-----`;
|
const challenge = encryptAsymmetric(answer, encPubKey);
|
||||||
const challenge = publicEncrypt({ key: pubKeyPem, oaepHash: "sha256" }, answer);
|
|
||||||
return challenge.toString("base64");
|
return challenge.toString("base64");
|
||||||
};
|
};
|
||||||
|
|
||||||
export const registerUserClient = async (userId: number, ip: string, pubKey: string) => {
|
export const registerUserClient = async (
|
||||||
const client = await getClientByPubKey(pubKey);
|
userId: number,
|
||||||
|
ip: string,
|
||||||
|
encPubKey: string,
|
||||||
|
sigPubKey: string,
|
||||||
|
) => {
|
||||||
let clientId;
|
let clientId;
|
||||||
|
|
||||||
|
const client = await getClientByPubKeys(encPubKey, sigPubKey);
|
||||||
if (client) {
|
if (client) {
|
||||||
const userClient = await getUserClient(userId, client.id);
|
const userClient = await getUserClient(userId, client.id);
|
||||||
if (userClient) {
|
if (userClient) {
|
||||||
error(409, "Public key already registered");
|
error(409, "Client already registered");
|
||||||
}
|
}
|
||||||
|
|
||||||
await createUserClient(userId, client.id);
|
await createUserClient(userId, client.id);
|
||||||
clientId = client.id;
|
clientId = client.id;
|
||||||
} else {
|
} else {
|
||||||
const pubKeyPem = `-----BEGIN PUBLIC KEY-----\n${pubKey}\n-----END PUBLIC KEY-----`;
|
if (!verifyPubKey(encPubKey) || !verifyPubKey(sigPubKey)) {
|
||||||
const pubKeyObject = createPublicKey(pubKeyPem);
|
error(400, "Invalid public key(s)");
|
||||||
if (
|
} else if (encPubKey === sigPubKey) {
|
||||||
pubKeyObject.asymmetricKeyType !== "rsa" ||
|
error(400, "Public keys must be different");
|
||||||
pubKeyObject.asymmetricKeyDetails?.modulusLength !== 4096
|
} else if (
|
||||||
|
(await countClientByPubKey(encPubKey)) > 0 ||
|
||||||
|
(await countClientByPubKey(sigPubKey)) > 0
|
||||||
) {
|
) {
|
||||||
error(400, "Invalid public key");
|
error(409, "Public key(s) already registered");
|
||||||
}
|
}
|
||||||
|
|
||||||
clientId = await createClient(pubKey, userId);
|
clientId = await createClient(encPubKey, sigPubKey, userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
return await generateChallenge(userId, ip, clientId, pubKey);
|
return { challenge: await generateChallenge(userId, ip, clientId, encPubKey) };
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getUserClientStatus = async (userId: number, clientId: number) => {
|
export const getUserClientStatus = async (userId: number, clientId: number) => {
|
||||||
@@ -78,7 +95,12 @@ export const getUserClientStatus = async (userId: number, clientId: number) => {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export const verifyUserClient = async (userId: number, ip: string, answer: string) => {
|
export const verifyUserClient = async (
|
||||||
|
userId: number,
|
||||||
|
ip: string,
|
||||||
|
answer: string,
|
||||||
|
sigAnswer: string,
|
||||||
|
) => {
|
||||||
const challenge = await getUserClientChallenge(answer, ip);
|
const challenge = await getUserClientChallenge(answer, ip);
|
||||||
if (!challenge) {
|
if (!challenge) {
|
||||||
error(401, "Invalid challenge answer");
|
error(401, "Invalid challenge answer");
|
||||||
@@ -86,5 +108,12 @@ export const verifyUserClient = async (userId: number, ip: string, answer: strin
|
|||||||
error(403, "Forbidden");
|
error(403, "Forbidden");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const client = await getClient(challenge.clientId);
|
||||||
|
if (!client) {
|
||||||
|
error(500, "Invalid challenge answer");
|
||||||
|
} else if (!verifySignature(answer, sigAnswer, client.sigPubKey)) {
|
||||||
|
error(401, "Invalid challenge answer signature");
|
||||||
|
}
|
||||||
|
|
||||||
await setUserClientStateToPending(userId, challenge.clientId);
|
await setUserClientStateToPending(userId, challenge.clientId);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -12,12 +12,18 @@ export const POST: RequestHandler = async ({ request, cookies, getClientAddress
|
|||||||
|
|
||||||
const zodRes = z
|
const zodRes = z
|
||||||
.object({
|
.object({
|
||||||
pubKey: z.string().base64().nonempty(),
|
encPubKey: z.string().base64().nonempty(),
|
||||||
|
sigPubKey: z.string().base64().nonempty(),
|
||||||
})
|
})
|
||||||
.safeParse(await request.json());
|
.safeParse(await request.json());
|
||||||
if (!zodRes.success) error(400, "Invalid request body");
|
if (!zodRes.success) error(400, "Invalid request body");
|
||||||
const { pubKey } = zodRes.data;
|
const { encPubKey, sigPubKey } = zodRes.data;
|
||||||
|
|
||||||
const challenge = await registerUserClient(userId, getClientAddress(), pubKey.trim());
|
const { challenge } = await registerUserClient(
|
||||||
|
userId,
|
||||||
|
getClientAddress(),
|
||||||
|
encPubKey.trim(),
|
||||||
|
sigPubKey.trim(),
|
||||||
|
);
|
||||||
return json({ challenge });
|
return json({ challenge });
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -13,11 +13,12 @@ export const POST: RequestHandler = async ({ request, cookies, getClientAddress
|
|||||||
const zodRes = z
|
const zodRes = z
|
||||||
.object({
|
.object({
|
||||||
answer: z.string().base64().nonempty(),
|
answer: z.string().base64().nonempty(),
|
||||||
|
sigAnswer: z.string().base64().nonempty(),
|
||||||
})
|
})
|
||||||
.safeParse(await request.json());
|
.safeParse(await request.json());
|
||||||
if (!zodRes.success) error(400, "Invalid request body");
|
if (!zodRes.success) error(400, "Invalid request body");
|
||||||
const { answer } = zodRes.data;
|
const { answer, sigAnswer } = zodRes.data;
|
||||||
|
|
||||||
await verifyUserClient(userId, getClientAddress(), answer.trim());
|
await verifyUserClient(userId, getClientAddress(), answer.trim(), sigAnswer.trim());
|
||||||
return text("Client verified", { headers: { "Content-Type": "text/plain" } });
|
return text("Client verified", { headers: { "Content-Type": "text/plain" } });
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user