From 709dc7280e8b4aab2b173c3897b418f6e1759ae7 Mon Sep 17 00:00:00 2001 From: Puyodead1 Date: Sun, 29 Jan 2023 21:30:42 -0500 Subject: [PATCH] Implement WebAuthn (#967) * implement webauthn * code review --------- Co-authored-by: Madeline <46743919+MaddyUnderStars@users.noreply.github.com> --- assets/openapi.json | Bin 216568 -> 222559 bytes assets/schemas.json | Bin 1028336 -> 1091332 bytes package-lock.json | Bin 262828 -> 271966 bytes package.json | 1 + src/api/Server.ts | 9 +- src/api/middlewares/Authentication.ts | 1 + src/api/routes/auth/login.ts | 56 ++++- src/api/routes/auth/mfa/webauthn.ts | 112 ++++++++++ .../mfa/webauthn/credentials/#key_id/index.ts | 35 ++++ .../@me/mfa/webauthn/credentials/index.ts | 196 ++++++++++++++++++ src/util/entities/SecurityKey.ts | 46 ++++ src/util/entities/User.ts | 7 + src/util/entities/index.ts | 3 +- .../mariadb/1675045120206-webauthn.ts | 27 +++ .../migration/mysql/1675045120206-webauthn.ts | 27 +++ .../postgresql/1675044825710-webauthn.ts | 27 +++ src/util/schemas/WebAuthnSchema.ts | 38 ++++ src/util/schemas/index.ts | 69 +++--- src/util/util/WebAuthn.ts | 68 ++++++ src/util/util/index.ts | 1 + 20 files changed, 676 insertions(+), 47 deletions(-) create mode 100644 src/api/routes/auth/mfa/webauthn.ts create mode 100644 src/api/routes/users/@me/mfa/webauthn/credentials/#key_id/index.ts create mode 100644 src/api/routes/users/@me/mfa/webauthn/credentials/index.ts create mode 100644 src/util/entities/SecurityKey.ts create mode 100644 src/util/migration/mariadb/1675045120206-webauthn.ts create mode 100644 src/util/migration/mysql/1675045120206-webauthn.ts create mode 100644 src/util/migration/postgresql/1675044825710-webauthn.ts create mode 100644 src/util/schemas/WebAuthnSchema.ts create mode 100644 src/util/util/WebAuthn.ts diff --git a/assets/openapi.json b/assets/openapi.json index 42a64baf285d1bcb52c4c87f9269cdb6d0a269d4..0eafe6cbae6fedae62e5184b492b314588979607 100644 GIT binary patch delta 1086 zcmaKrOH30{7=?4E518_*0Vz=Wpfpen!y`Nb3Z{TUFxCKKh{hPF<&qYrEzC?K;KD*; ze1t{eU))4UtQ$;}L`)ZrZfx9`$igwvxU>rsjV4-l#;9?ow88>dP3E6-&i~yrGe1`g zKE5v4?3#yuYy)Yc9HRBD8ry`A!@%n5z$!4142^*0>}hp+I9*W+k-S`p&Naa3{5D95 znzSvFmk%#YcKKO8{5j(wsdE&Q7Dfu}J5E;D0Mg%Pa5k*(4Bi$w$a@7@*y9!slAvT zhvnyWnGWccIs*xoA`2wTb0A!3152d_o)lI?IF<{)hD|%b`d6qD5~gaoHM)3~5pY1{ z=NO(9F~j-%J`uJ%YBLEnnS@#;fgD$%DkZ`U&TCeh$BK=e5JB=;AaYkPZ#+n!47C%f z0aYn0_ZYXSqe}NBwtXnb@E9sizl`Xd0m73_;CJWP25vhPlab0FDUmS1<`LUps(vg%)rH%VrP`8$Bw4kayIeMHCMETVSx9)eM z`29}GFaIumm!N$DJ+~is0;lT;3LqdLAbkpbdR-z> diff --git a/assets/schemas.json b/assets/schemas.json index 3cd45c5e265fb966d570e925d79ffb82d93192ec..c840b2612291e3723a14585f3a3a2a0a35914617 100644 GIT binary patch delta 9634 zcmdT}ZA=_R7|!nP-tB$t-EqKu@OgY$f$(9J#I{J5(zLXsaM<1lRLgOAN-Y98Xwh1e zrZJKlRH8l2D;AiTI{RP`)H^UjS6GEws3Fd3*3ArKeI!hm+3B|J@e5I%dyG3V13rFi9m`hn9Bo$GqSda>1o>-Jig(Hu$Ajgyqf>I?o zWkn(J7o8H{Y-g>=_?;Qq-?l((iM9^ir!8Q-&WKhDZGzx3CBTm*OqvXL=x@r1I^VGk zL^&kzW|(ejB=}+g3+IIsFG= zM5|~)<<_*dfgDigp`7^FR9!LoFhA+%50H-%@43VQO}@`R>QfCS0L*)(3U2~9J@@MpiA7(h&I7ox=6a5G2es|;BJCx55&!`*U z2`aORKSH0wAB<9JqIZ5QZd0>rw0JCOAex7S8~MzOhdcam$HRRduU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?EBOOKiacM0bF`Jx{8}W_Gn%M)nGbm|`>th^4Su#+^nX{2 zMZ|Y4mcvnO)r5TFqc>PD(IFUj2{OK&BJ0>3>Rbx7lwrH)C)h%4By77^E&N4hu5N5B z;~MG6)Tq4}pXS;(FH+ROOX4xQiqRU-kw{$sTHL_qFgBV4I%1k_-&X4u1`;EAaAi;$ zqkBd7qX%a>`3hadwA1g#h#cx%0<$>xTjX*2LniVuV82f7IqJwhg>A01ZxQ8Gfv_V^ zZj9`SV5%67u%mN^|72rw!QProy0^@P>Zau)ktu>dDs4UN;s!szI7olTD1Y#d;RWVA z?5k8f!4I|(vINX3HgN2*X{r^ID)!h!9rM#$ZW<@2OUa?9Z;S)1meh$wRJM855hjw) H%a{KF0~mL< diff --git a/package-lock.json b/package-lock.json index d6a90f43ce6b0a640f99f34b6301b8bbbfa3754c..b9a712aa02dcb71411f571840da123764a20d61e 100644 GIT binary patch delta 5668 zcmbtYTa4r8bq1xZleN2EkJmfS?!w-kS+9#&tKn6ol){d6qo@lhi4t{d>zFr*lqixC zDT-8UFZ>XoL7Jwi0uu?+zy^vI1rlH#BbWerNL-+OX$!}7FKCMvFjBNd1GILY+CG(( zW;8R~9nUs>63PFZ|3ByZ&-uf7@%Gmu zfA#Jy!I;Kn*PimC4T{HJ;u1fdt9qQDj&aO?@9V&}|IJGPk~=PQx&jzKeJzgo^*4Z< zcLc4K@e*`rfsawV7dgZ6fm;WQ+wl{fE4msiga4F zbfQUA^=eK^xjnUl>U7q@>ztB){`uY851&7OepfVSfv>+DKA+!Rd9fQl|LS_xF#RuI zh+goae*zx5WLQU%YqxiOUIwn+dhtwe-Q(aqkoYOk1REU!qu^z-x|ocT!%ou~Rr|Kb z7TblXL|EneqV6EWmej1I^m3z*<`8L`b?O$!eXobS1v>!`FLQS`4~?%RiC+G*c=7T3#Y@lk-is}&B7rnk_FAwkt7xi z+_2_N`4(oBCSEI_7--<6n=yH?tt+^OyOlhm4MAnD51U9w>}9ix)S0)zF4==C9A)8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QgtjDs@tBc^QzZ}adweQl+yk?K=f(9{1xEBowE!HZ#tm6fZGnQ z?ktTBt%jM zw^l(Gpt|}Ek___S_zAGf@z|`PSago=^&!qw8CjOhG+ShlW>y)JI_559g38BoV^p&` zF$19~u`y0o`bg7`^EIA~J6vSF* zs1Ui)gx1ZLBeUcLs}1sj>$g{}Z)nEF{{pUrEibxdI;&=7WyI>qzuOK>FlkdyLlaga zO%xGetE9p6YKd`sl{z8{bvHJ`?IC0Ll3CMfDa<5aV+X3!L)ukNc91U34`orJ2+`(h zIVUeC37wy+M}3A$NB3TiXp;XX1#G|mhmms;2=l-C?I?IDq?W*#6~)9udVwK-$Bf?K zYT8207h5$7GzP+?sx;6<8KJYx*@;-S>v+s-Wc1j;s*Q&UC6(xUcCklP zkdB5yCeMwBP!s1y28K}bfGX78jw;V|s#u?;GwsGWoYk)Gzy6)*uRs6L!N3sO7KQhS zRW*BNQz%wW2G*VY5Db&Vx~??`eBSLMAeyJ@8p|+Dt1%S{NOq9I*qN;n{WM=LRvPd; z*~=*fS0bzY9M22cK2>yUUdpjScWx#Os8vt9Dc)<;NL=BTcei)%Y>HNxd&lR3u!X`8 n$>~AIhkFuu(}Hc%DCD1)Rs-L9>!tt7qpR58zxdPW?>_lI^79^n delta 104 zcmV-u0GI#X%n+=F5U`#Cv$+Dx&$HOuXbY3y>kYF}=pq!Cj|%|@w^;!JhkLhTegW_s zw}6`g849=isR4wiw|G+mDqpwLvjQq. */ -import { Request, Response, Router } from "express"; -import { route, getIpAdress, verifyCaptcha } from "@fosscord/api"; -import bcrypt from "bcrypt"; +import { getIpAdress, route, verifyCaptcha } from "@fosscord/api"; import { - Config, - User, - generateToken, adjustEmail, + Config, FieldErrors, + generateToken, + generateWebAuthnTicket, LoginSchema, + User, + WebAuthn, } from "@fosscord/util"; +import bcrypt from "bcrypt"; import crypto from "crypto"; +import { Request, Response, Router } from "express"; const router: Router = Router(); export default router; @@ -73,7 +75,10 @@ router.post( "settings", "totp_secret", "mfa_enabled", + "webauthn_enabled", + "security_keys", ], + relations: ["security_keys"], }).catch(() => { throw FieldErrors({ login: { @@ -116,7 +121,7 @@ router.post( }); } - if (user.mfa_enabled) { + if (user.mfa_enabled && !user.webauthn_enabled) { // TODO: This is not a discord.com ticket. I'm not sure what it is but I'm lazy const ticket = crypto.randomBytes(40).toString("hex"); @@ -130,6 +135,40 @@ router.post( }); } + if (user.mfa_enabled && user.webauthn_enabled) { + if (!WebAuthn.fido2) { + // TODO: I did this for typescript and I can't use ! + throw new Error("WebAuthn not enabled"); + } + + const options = await WebAuthn.fido2.assertionOptions(); + const challenge = JSON.stringify({ + publicKey: { + ...options, + challenge: Buffer.from(options.challenge).toString( + "base64", + ), + allowCredentials: user.security_keys.map((x) => ({ + id: x.key_id, + type: "public-key", + })), + transports: ["usb", "ble", "nfc"], + timeout: 60000, + }, + }); + + const ticket = await generateWebAuthnTicket(challenge); + await User.update({ id: user.id }, { totp_last_ticket: ticket }); + + return res.json({ + ticket: ticket, + mfa: true, + sms: false, // TODO + token: null, + webauthn: challenge, + }); + } + const token = await generateToken(user.id); // Notice this will have a different token structure, than discord @@ -147,6 +186,9 @@ router.post( * MFA required: * @returns {"token": null, "mfa": true, "sms": true, "ticket": "SOME TICKET JWT TOKEN"} + * WebAuthn MFA required: + * @returns {"token": null, "mfa": true, "webauthn": true, "sms": true, "ticket": "SOME TICKET JWT TOKEN"} + * Captcha required: * @returns {"captcha_key": ["captcha-required"], "captcha_sitekey": null, "captcha_service": "recaptcha"} diff --git a/src/api/routes/auth/mfa/webauthn.ts b/src/api/routes/auth/mfa/webauthn.ts new file mode 100644 index 00000000..e574b969 --- /dev/null +++ b/src/api/routes/auth/mfa/webauthn.ts @@ -0,0 +1,112 @@ +/* + Fosscord: A FOSS re-implementation and extension of the Discord.com backend. + Copyright (C) 2023 Fosscord and Fosscord Contributors + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +import { route } from "@fosscord/api"; +import { + generateToken, + SecurityKey, + User, + verifyWebAuthnToken, + WebAuthn, + WebAuthnTotpSchema, +} from "@fosscord/util"; +import { Request, Response, Router } from "express"; +import { ExpectedAssertionResult } from "fido2-lib"; +import { HTTPError } from "lambert-server"; +const router = Router(); + +function toArrayBuffer(buf: Buffer) { + const ab = new ArrayBuffer(buf.length); + const view = new Uint8Array(ab); + for (let i = 0; i < buf.length; ++i) { + view[i] = buf[i]; + } + return ab; +} + +router.post( + "/", + route({ body: "WebAuthnTotpSchema" }), + async (req: Request, res: Response) => { + if (!WebAuthn.fido2) { + // TODO: I did this for typescript and I can't use ! + throw new Error("WebAuthn not enabled"); + } + + const { code, ticket } = req.body as WebAuthnTotpSchema; + + const user = await User.findOneOrFail({ + where: { + totp_last_ticket: ticket, + }, + select: ["id", "settings"], + }); + + const ret = await verifyWebAuthnToken(ticket); + if (!ret) + throw new HTTPError(req.t("auth:login.INVALID_TOTP_CODE"), 60008); + + await User.update({ id: user.id }, { totp_last_ticket: "" }); + + const clientAttestationResponse = JSON.parse(code); + const securityKey = await SecurityKey.findOneOrFail({ + where: { + user_id: req.user_id, + key_id: clientAttestationResponse.rawId, + }, + }); + + if (!clientAttestationResponse.rawId) + throw new HTTPError("Missing rawId", 400); + + clientAttestationResponse.rawId = toArrayBuffer( + Buffer.from(clientAttestationResponse.rawId, "base64"), + ); + + const assertionExpectations: ExpectedAssertionResult = JSON.parse( + Buffer.from( + clientAttestationResponse.response.clientDataJSON, + "base64", + ).toString(), + ); + + const authnResult = await WebAuthn.fido2.assertionResult( + clientAttestationResponse, + { + ...assertionExpectations, + factor: "second", + publicKey: securityKey.public_key, + prevCounter: securityKey.counter, + userHandle: securityKey.key_id, + }, + ); + + const counter = authnResult.authnrData.get("counter"); + + securityKey.counter = counter; + + await securityKey.save(); + + return res.json({ + token: await generateToken(user.id), + user_settings: user.settings, + }); + }, +); + +export default router; diff --git a/src/api/routes/users/@me/mfa/webauthn/credentials/#key_id/index.ts b/src/api/routes/users/@me/mfa/webauthn/credentials/#key_id/index.ts new file mode 100644 index 00000000..c451e357 --- /dev/null +++ b/src/api/routes/users/@me/mfa/webauthn/credentials/#key_id/index.ts @@ -0,0 +1,35 @@ +/* + Fosscord: A FOSS re-implementation and extension of the Discord.com backend. + Copyright (C) 2023 Fosscord and Fosscord Contributors + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +import { route } from "@fosscord/api"; +import { SecurityKey } from "@fosscord/util"; +import { Request, Response, Router } from "express"; +const router = Router(); + +router.delete("/", route({}), async (req: Request, res: Response) => { + const { key_id } = req.params; + + await SecurityKey.delete({ + id: key_id, + user_id: req.user_id, + }); + + res.sendStatus(204); +}); + +export default router; diff --git a/src/api/routes/users/@me/mfa/webauthn/credentials/index.ts b/src/api/routes/users/@me/mfa/webauthn/credentials/index.ts new file mode 100644 index 00000000..581950b8 --- /dev/null +++ b/src/api/routes/users/@me/mfa/webauthn/credentials/index.ts @@ -0,0 +1,196 @@ +/* + Fosscord: A FOSS re-implementation and extension of the Discord.com backend. + Copyright (C) 2023 Fosscord and Fosscord Contributors + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +import { route } from "@fosscord/api"; +import { + CreateWebAuthnCredentialSchema, + DiscordApiErrors, + FieldErrors, + GenerateWebAuthnCredentialsSchema, + generateWebAuthnTicket, + SecurityKey, + User, + verifyWebAuthnToken, + WebAuthn, + WebAuthnPostSchema, +} from "@fosscord/util"; +import bcrypt from "bcrypt"; +import { Request, Response, Router } from "express"; +import { ExpectedAttestationResult } from "fido2-lib"; +import { HTTPError } from "lambert-server"; +const router = Router(); + +const isGenerateSchema = ( + body: WebAuthnPostSchema, +): body is GenerateWebAuthnCredentialsSchema => { + return "password" in body; +}; + +const isCreateSchema = ( + body: WebAuthnPostSchema, +): body is CreateWebAuthnCredentialSchema => { + return "credential" in body; +}; + +function toArrayBuffer(buf: Buffer) { + const ab = new ArrayBuffer(buf.length); + const view = new Uint8Array(ab); + for (let i = 0; i < buf.length; ++i) { + view[i] = buf[i]; + } + return ab; +} + +router.get("/", route({}), async (req: Request, res: Response) => { + const securityKeys = await SecurityKey.find({ + where: { + user_id: req.user_id, + }, + }); + + return res.json( + securityKeys.map((key) => ({ + id: key.id, + name: key.name, + })), + ); +}); + +router.post( + "/", + route({ body: "WebAuthnPostSchema" }), + async (req: Request, res: Response) => { + if (!WebAuthn.fido2) { + // TODO: I did this for typescript and I can't use ! + throw new Error("WebAuthn not enabled"); + } + + const user = await User.findOneOrFail({ + where: { + id: req.user_id, + }, + select: [ + "data", + "id", + "disabled", + "deleted", + "settings", + "totp_secret", + "mfa_enabled", + "username", + ], + }); + + if (isGenerateSchema(req.body)) { + const { password } = req.body; + const same_password = await bcrypt.compare( + password, + user.data.hash || "", + ); + if (!same_password) { + throw FieldErrors({ + password: { + message: req.t("auth:login.INVALID_PASSWORD"), + code: "INVALID_PASSWORD", + }, + }); + } + + const registrationOptions = + await WebAuthn.fido2.attestationOptions(); + const challenge = JSON.stringify({ + publicKey: { + ...registrationOptions, + challenge: Buffer.from( + registrationOptions.challenge, + ).toString("base64"), + user: { + id: user.id, + name: user.username, + displayName: user.username, + }, + }, + }); + + const ticket = await generateWebAuthnTicket(challenge); + + return res.json({ + ticket: ticket, + challenge, + }); + } else if (isCreateSchema(req.body)) { + const { credential, name, ticket } = req.body; + + const verified = await verifyWebAuthnToken(ticket); + if (!verified) throw new HTTPError("Invalid ticket", 400); + + const clientAttestationResponse = JSON.parse(credential); + + if (!clientAttestationResponse.rawId) + throw new HTTPError("Missing rawId", 400); + + const rawIdBuffer = Buffer.from( + clientAttestationResponse.rawId, + "base64", + ); + clientAttestationResponse.rawId = toArrayBuffer(rawIdBuffer); + + const attestationExpectations: ExpectedAttestationResult = + JSON.parse( + Buffer.from( + clientAttestationResponse.response.clientDataJSON, + "base64", + ).toString(), + ); + + const regResult = await WebAuthn.fido2.attestationResult( + clientAttestationResponse, + { + ...attestationExpectations, + factor: "second", + }, + ); + + const authnrData = regResult.authnrData; + const keyId = Buffer.from(authnrData.get("credId")).toString( + "base64", + ); + const counter = authnrData.get("counter"); + const publicKey = authnrData.get("credentialPublicKeyPem"); + + const securityKey = SecurityKey.create({ + name, + counter, + public_key: publicKey, + user_id: req.user_id, + key_id: keyId, + }); + + await securityKey.save(); + + return res.json({ + name, + id: securityKey.id, + }); + } else { + throw DiscordApiErrors.INVALID_AUTHENTICATION_TOKEN; + } + }, +); + +export default router; diff --git a/src/util/entities/SecurityKey.ts b/src/util/entities/SecurityKey.ts new file mode 100644 index 00000000..8f377d9d --- /dev/null +++ b/src/util/entities/SecurityKey.ts @@ -0,0 +1,46 @@ +/* + Fosscord: A FOSS re-implementation and extension of the Discord.com backend. + Copyright (C) 2023 Fosscord and Fosscord Contributors + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +import { Column, Entity, JoinColumn, ManyToOne, RelationId } from "typeorm"; +import { BaseClass } from "./BaseClass"; +import { User } from "./User"; + +@Entity("security_keys") +export class SecurityKey extends BaseClass { + @Column({ nullable: true }) + @RelationId((key: SecurityKey) => key.user) + user_id: string; + + @JoinColumn({ name: "user_id" }) + @ManyToOne(() => User, { + onDelete: "CASCADE", + }) + user: User; + + @Column() + key_id: string; + + @Column() + public_key: string; + + @Column() + counter: number; + + @Column() + name: string; +} diff --git a/src/util/entities/User.ts b/src/util/entities/User.ts index 658584c3..fa8c7aa7 100644 --- a/src/util/entities/User.ts +++ b/src/util/entities/User.ts @@ -33,6 +33,7 @@ import { UserSettings } from "./UserSettings"; import { Session } from "./Session"; import { Config, FieldErrors, Snowflake, trimSpecial, adjustEmail } from ".."; import { Request } from "express"; +import { SecurityKey } from "./SecurityKey"; export enum PublicUserEnum { username, @@ -138,6 +139,9 @@ export class User extends BaseClass { @Column({ select: false }) mfa_enabled: boolean = false; // if multi factor authentication is enabled + @Column({ select: false, default: false }) + webauthn_enabled: boolean = false; // if webauthn multi factor authentication is enabled + @Column({ select: false, nullable: true }) totp_secret?: string = ""; @@ -223,6 +227,9 @@ export class User extends BaseClass { @Column({ type: "simple-json", select: false }) extended_settings: string = "{}"; + @OneToMany(() => SecurityKey, (key: SecurityKey) => key.user) + security_keys: SecurityKey[]; + // TODO: I don't like this method? validate() { if (this.email) { diff --git a/src/util/entities/index.ts b/src/util/entities/index.ts index d856c41b..6dfbd822 100644 --- a/src/util/entities/index.ts +++ b/src/util/entities/index.ts @@ -23,8 +23,8 @@ export * from "./BackupCodes"; export * from "./Ban"; export * from "./BaseClass"; export * from "./Categories"; -export * from "./ClientRelease"; export * from "./Channel"; +export * from "./ClientRelease"; export * from "./Config"; export * from "./ConnectedAccount"; export * from "./EmbedCache"; @@ -41,6 +41,7 @@ export * from "./ReadState"; export * from "./Recipient"; export * from "./Relationship"; export * from "./Role"; +export * from "./SecurityKey"; export * from "./Session"; export * from "./Sticker"; export * from "./StickerPack"; diff --git a/src/util/migration/mariadb/1675045120206-webauthn.ts b/src/util/migration/mariadb/1675045120206-webauthn.ts new file mode 100644 index 00000000..e009fa0c --- /dev/null +++ b/src/util/migration/mariadb/1675045120206-webauthn.ts @@ -0,0 +1,27 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class webauthn1675045120206 implements MigrationInterface { + name = "webauthn1675045120206"; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `CREATE TABLE \`security_keys\` (\`id\` varchar(255) NOT NULL, \`user_id\` varchar(255) NULL, \`key_id\` varchar(255) NOT NULL, \`public_key\` varchar(255) NOT NULL, \`counter\` int NOT NULL, \`name\` varchar(255) NOT NULL, PRIMARY KEY (\`id\`)) ENGINE=InnoDB`, + ); + await queryRunner.query( + `ALTER TABLE \`users\` ADD \`webauthn_enabled\` tinyint NOT NULL DEFAULT 0`, + ); + await queryRunner.query( + `ALTER TABLE \`security_keys\` ADD CONSTRAINT \`FK_24c97d0771cafedce6d7163eaad\` FOREIGN KEY (\`user_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION`, + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE \`security_keys\` DROP FOREIGN KEY \`FK_24c97d0771cafedce6d7163eaad\``, + ); + await queryRunner.query( + `ALTER TABLE \`users\` DROP COLUMN \`webauthn_enabled\``, + ); + await queryRunner.query(`DROP TABLE \`security_keys\``); + } +} diff --git a/src/util/migration/mysql/1675045120206-webauthn.ts b/src/util/migration/mysql/1675045120206-webauthn.ts new file mode 100644 index 00000000..e009fa0c --- /dev/null +++ b/src/util/migration/mysql/1675045120206-webauthn.ts @@ -0,0 +1,27 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class webauthn1675045120206 implements MigrationInterface { + name = "webauthn1675045120206"; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `CREATE TABLE \`security_keys\` (\`id\` varchar(255) NOT NULL, \`user_id\` varchar(255) NULL, \`key_id\` varchar(255) NOT NULL, \`public_key\` varchar(255) NOT NULL, \`counter\` int NOT NULL, \`name\` varchar(255) NOT NULL, PRIMARY KEY (\`id\`)) ENGINE=InnoDB`, + ); + await queryRunner.query( + `ALTER TABLE \`users\` ADD \`webauthn_enabled\` tinyint NOT NULL DEFAULT 0`, + ); + await queryRunner.query( + `ALTER TABLE \`security_keys\` ADD CONSTRAINT \`FK_24c97d0771cafedce6d7163eaad\` FOREIGN KEY (\`user_id\`) REFERENCES \`users\`(\`id\`) ON DELETE CASCADE ON UPDATE NO ACTION`, + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE \`security_keys\` DROP FOREIGN KEY \`FK_24c97d0771cafedce6d7163eaad\``, + ); + await queryRunner.query( + `ALTER TABLE \`users\` DROP COLUMN \`webauthn_enabled\``, + ); + await queryRunner.query(`DROP TABLE \`security_keys\``); + } +} diff --git a/src/util/migration/postgresql/1675044825710-webauthn.ts b/src/util/migration/postgresql/1675044825710-webauthn.ts new file mode 100644 index 00000000..ac43c928 --- /dev/null +++ b/src/util/migration/postgresql/1675044825710-webauthn.ts @@ -0,0 +1,27 @@ +import { MigrationInterface, QueryRunner } from "typeorm"; + +export class webauthn1675044825710 implements MigrationInterface { + name = "webauthn1675044825710"; + + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `CREATE TABLE "security_keys" ("id" character varying NOT NULL, "user_id" character varying, "key_id" character varying NOT NULL, "public_key" character varying NOT NULL, "counter" integer NOT NULL, "name" character varying NOT NULL, CONSTRAINT "PK_6e95cdd91779e7cca06d1fff89c" PRIMARY KEY ("id"))`, + ); + await queryRunner.query( + `ALTER TABLE "users" ADD "webauthn_enabled" boolean NOT NULL DEFAULT false`, + ); + await queryRunner.query( + `ALTER TABLE "security_keys" ADD CONSTRAINT "FK_24c97d0771cafedce6d7163eaad" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE NO ACTION`, + ); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query( + `ALTER TABLE "security_keys" DROP CONSTRAINT "FK_24c97d0771cafedce6d7163eaad"`, + ); + await queryRunner.query( + `ALTER TABLE "users" DROP COLUMN "webauthn_enabled"`, + ); + await queryRunner.query(`DROP TABLE "security_keys"`); + } +} diff --git a/src/util/schemas/WebAuthnSchema.ts b/src/util/schemas/WebAuthnSchema.ts new file mode 100644 index 00000000..03e173a7 --- /dev/null +++ b/src/util/schemas/WebAuthnSchema.ts @@ -0,0 +1,38 @@ +/* + Fosscord: A FOSS re-implementation and extension of the Discord.com backend. + Copyright (C) 2023 Fosscord and Fosscord Contributors + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +// FIXME: better naming +export interface GenerateWebAuthnCredentialsSchema { + password: string; +} + +// FIXME: better naming +export interface CreateWebAuthnCredentialSchema { + credential: string; + name: string; + ticket: string; +} + +export type WebAuthnPostSchema = Partial< + GenerateWebAuthnCredentialsSchema | CreateWebAuthnCredentialSchema +>; + +export interface WebAuthnTotpSchema { + code: string; + ticket: string; +} diff --git a/src/util/schemas/index.ts b/src/util/schemas/index.ts index f49d2294..65e8b3cd 100644 --- a/src/util/schemas/index.ts +++ b/src/util/schemas/index.ts @@ -16,66 +16,59 @@ along with this program. If not, see . */ -export * from "./Validator"; -export * from "./SelectProtocolSchema"; -export * from "./LoginSchema"; -export * from "./RegisterSchema"; -export * from "./TotpSchema"; +export * from "./ActivitySchema"; +export * from "./ApplicationAuthorizeSchema"; +export * from "./ApplicationCreateSchema"; +export * from "./ApplicationModifySchema"; export * from "./BackupCodesChallengeSchema"; -export * from "./ChannelModifySchema"; -export * from "./InviteCreateSchema"; -export * from "./PurgeSchema"; -export * from "./WebhookCreateSchema"; -export * from "./MessageCreateSchema"; -export * from "./MessageAcknowledgeSchema"; -export * from "./GuildCreateSchema"; export * from "./BanCreateSchema"; export * from "./BanModeratorSchema"; export * from "./BanRegistrySchema"; +export * from "./BotModifySchema"; +export * from "./ChannelModifySchema"; +export * from "./ChannelPermissionOverwriteSchema"; +export * from "./ChannelReorderSchema"; +export * from "./CodesVerificationSchema"; +export * from "./DmChannelCreateSchema"; export * from "./EmojiCreateSchema"; export * from "./EmojiModifySchema"; -export * from "./ModifyGuildStickerSchema"; -export * from "./TemplateCreateSchema"; -export * from "./TemplateModifySchema"; -export * from "./VanityUrlSchema"; +export * from "./GatewayPayloadSchema"; +export * from "./GuildCreateSchema"; +export * from "./GuildTemplateCreateSchema"; +export * from "./GuildUpdateSchema"; export * from "./GuildUpdateWelcomeScreenSchema"; -export * from "./WidgetModifySchema"; export * from "./IdentifySchema"; export * from "./InviteCreateSchema"; export * from "./LazyRequestSchema"; export * from "./LoginSchema"; export * from "./MemberChangeProfileSchema"; export * from "./MemberChangeSchema"; -export * from "./RoleModifySchema"; -export * from "./GuildTemplateCreateSchema"; -export * from "./DmChannelCreateSchema"; -export * from "./UserModifySchema"; +export * from "./MessageAcknowledgeSchema"; +export * from "./MessageCreateSchema"; +export * from "./MfaCodesSchema"; +export * from "./ModifyGuildStickerSchema"; +export * from "./PurgeSchema"; +export * from "./RegisterSchema"; export * from "./RelationshipPostSchema"; export * from "./RelationshipPutSchema"; -export * from "./CodesVerificationSchema"; -export * from "./MfaCodesSchema"; +export * from "./RoleModifySchema"; +export * from "./RolePositionUpdateSchema"; +export * from "./SelectProtocolSchema"; +export * from "./TemplateCreateSchema"; +export * from "./TemplateModifySchema"; export * from "./TotpDisableSchema"; export * from "./TotpEnableSchema"; -export * from "./VoiceIdentifySchema"; export * from "./TotpSchema"; export * from "./UserDeleteSchema"; +export * from "./UserGuildSettingsSchema"; export * from "./UserModifySchema"; export * from "./UserProfileModifySchema"; export * from "./UserSettingsSchema"; +export * from "./Validator"; export * from "./VanityUrlSchema"; +export * from "./VoiceIdentifySchema"; export * from "./VoiceStateUpdateSchema"; export * from "./VoiceVideoSchema"; -export * from "./IdentifySchema"; -export * from "./ActivitySchema"; -export * from "./LazyRequestSchema"; -export * from "./GuildUpdateSchema"; -export * from "./ChannelPermissionOverwriteSchema"; -export * from "./UserGuildSettingsSchema"; -export * from "./GatewayPayloadSchema"; -export * from "./RolePositionUpdateSchema"; -export * from "./ChannelReorderSchema"; -export * from "./UserSettingsSchema"; -export * from "./BotModifySchema"; -export * from "./ApplicationModifySchema"; -export * from "./ApplicationCreateSchema"; -export * from "./ApplicationAuthorizeSchema"; +export * from "./WebAuthnSchema"; +export * from "./WebhookCreateSchema"; +export * from "./WidgetModifySchema"; diff --git a/src/util/util/WebAuthn.ts b/src/util/util/WebAuthn.ts new file mode 100644 index 00000000..1bac5b98 --- /dev/null +++ b/src/util/util/WebAuthn.ts @@ -0,0 +1,68 @@ +/* + Fosscord: A FOSS re-implementation and extension of the Discord.com backend. + Copyright (C) 2023 Fosscord and Fosscord Contributors + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +import { Fido2Lib } from "fido2-lib"; +import jwt from "jsonwebtoken"; +import { Config } from "./Config"; + +const JWTOptions: jwt.SignOptions = { + algorithm: "HS256", + expiresIn: "5m", +}; + +export const WebAuthn: { + fido2: Fido2Lib | null; + init: () => void; +} = { + fido2: null, + init: function () { + this.fido2 = new Fido2Lib({ + challengeSize: 128, + }); + }, +}; + +export async function generateWebAuthnTicket( + challenge: string, +): Promise { + return new Promise((res, rej) => { + jwt.sign( + { challenge }, + Config.get().security.jwtSecret, + JWTOptions, + (err, token) => { + if (err || !token) return rej(err || "no token"); + return res(token); + }, + ); + }); +} + +export async function verifyWebAuthnToken(token: string) { + return new Promise((res, rej) => { + jwt.verify( + token, + Config.get().security.jwtSecret, + JWTOptions, + async (err, decoded) => { + if (err) return rej(err); + return res(decoded); + }, + ); + }); +} diff --git a/src/util/util/index.ts b/src/util/util/index.ts index a195b99a..543a49a9 100644 --- a/src/util/util/index.ts +++ b/src/util/util/index.ts @@ -39,3 +39,4 @@ export * from "./Array"; export * from "./TraverseDirectory"; export * from "./InvisibleCharacters"; export * from "./Sentry"; +export * from "./WebAuthn";