Skip to content

Commit

Permalink
security: begin support for WebAuthn
Browse files Browse the repository at this point in the history
See: #153
  • Loading branch information
willbarkoff committed May 11, 2021
1 parent 388dd25 commit 14f6602
Show file tree
Hide file tree
Showing 7 changed files with 322 additions and 5 deletions.
22 changes: 22 additions & 0 deletions app/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,13 +64,35 @@ var rawRequest = function(path, method, data, callback) {
request.send(method == "POST" ? paramStr : undefined);
};

var jsonRequest = function(path, method, data, callback) {
var request = new XMLHttpRequest();

request.withCredentials = true;
request.open(method, buildURL(path, method, data), true);
request.onload = function() {
callback(JSON.parse(request.responseText), request);
};
request.onerror = function() {
callback({
status: "error",
error: "disconnected"
}, request);
};
request.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
request.send(data);
};

export default {
get: function(path, data, callback) {
return rawRequest(path, "GET", data, callback);
},
post: function(path, data, callback) {
return rawRequest(path, "POST", data, callback);
},
// Used only for _special_ requests
postJSON: function(path, data, callback) {
return jsonRequest(path, "POST", data, callback);
},
init: function(callback) {
rawRequest("auth/csrf", "GET", {}, function(data) {
csrfToken = data.token;
Expand Down
10 changes: 10 additions & 0 deletions app/auth/SecurityKeyPrompt.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { h } from "preact";
import LoadingIndicator from "ui/LoadingIndicator.jsx";

export default function SecurityKeyPrompt() {
return <div class="text-center">
<LoadingIndicator type="large" />
<h1>Authenticate now</h1>
<p>Insert and touch your security key to authenticate.</p>
</div>;
}
154 changes: 154 additions & 0 deletions app/base64.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
/**
The code in this file was modified from https://github.com/duo-labs/webauthn.io,
released under the following license.
The following modifications were made:
- Converted to JavaScript module
- Changed "let" to "let" and "const" in several places
- Adjusted formatting to conform with MyHomeworkSpace styles ("npm run lint:fix")
---
BSD 3-Clause License
Copyright (c) 2019, Duo Labs
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

const lookup = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";


const Arr = (typeof Uint8Array !== "undefined")
? Uint8Array
: Array;

const PLUS = "+".charCodeAt(0);
const SLASH = "/".charCodeAt(0);
const NUMBER = "0".charCodeAt(0);
const LOWER = "a".charCodeAt(0);
const UPPER = "A".charCodeAt(0);
const PLUS_URL_SAFE = "-".charCodeAt(0);
const SLASH_URL_SAFE = "_".charCodeAt(0);

function decode(elt) {
const code = elt.charCodeAt(0);
if (code === PLUS || code === PLUS_URL_SAFE) return 62; // '+'
if (code === SLASH || code === SLASH_URL_SAFE) return 63; // '/'
if (code < NUMBER) return -1; // no match
if (code < NUMBER + 10) return code - NUMBER + 26 + 26;
if (code < UPPER + 26) return code - UPPER;
if (code < LOWER + 26) return code - LOWER + 26;
}

export function base64ToByteArray(b64) {
let i, j, l, tmp, placeHolders, arr;

if (b64.length % 4 > 0) {
throw new Error("Invalid string. Length must be a multiple of 4");
}

// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
let len = b64.length;
placeHolders = b64.charAt(len - 2) === "=" ? 2 : b64.charAt(len - 1) === "=" ? 1 : 0;

// base64 is 4/3 + up to two characters of the original data
arr = new Arr(b64.length * 3 / 4 - placeHolders);

// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? b64.length - 4 : b64.length;

let L = 0;

function push(v) {
arr[L++] = v;
}

for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3));
push((tmp & 0xFF0000) >> 16);
push((tmp & 0xFF00) >> 8);
push(tmp & 0xFF);
}

if (placeHolders === 2) {
tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4);
push(tmp & 0xFF);
} else if (placeHolders === 1) {
tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2);
push((tmp >> 8) & 0xFF);
push(tmp & 0xFF);
}

return arr;
}

export function uint8ToBase64(uint8) {
let i;
let extraBytes = uint8.length % 3; // if we have 1 byte left, pad 2 bytes
let output = "";
let temp, length;

function encode(num) {
return lookup.charAt(num);
}

function tripletToBase64(num) {
return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F);
}

// go through the array every three bytes, we'll deal with trailing stuff later
for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
output += tripletToBase64(temp);
}

// pad the end with zeros, but make sure to not forget the extra bytes
switch (extraBytes) {
case 1:
temp = uint8[uint8.length - 1];
output += encode(temp >> 2);
output += encode((temp << 4) & 0x3F);
output += "==";
break;
case 2:
temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]);
output += encode(temp >> 10);
output += encode((temp >> 4) & 0x3F);
output += encode((temp << 2) & 0x3F);
output += "=";
break;
default:
break;
}

return output;
}
25 changes: 21 additions & 4 deletions app/settings/panes/account/TwoFactorInfo.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,25 @@ class TwoFactorInfo extends Component {
api.get("auth/2fa/status", {}, (data) => {
this.setState({
loading: false,
enrolled: data.enrolled
enrolledTOTP: data.enrolledTOTP,
enrolledWebAuthn: data.enrolledWebAuthn
});
});
}

manage2fa() {
this.props.openModal("twoFactor", {
enrolled: this.state.enrolled
enrolled: this.state.enrolledTOTP
});
}

manageWebAuthn() {
this.props.openModal("webAuthn", {});
}

render(props, state) {
const twofactorenabled = state.enrolledTOTP || state.enrolledWebAuthn;

if (state.loading) {
return <div class="twoFactorInfo">
<LoadingIndicator /> Loading, please wait...
Expand All @@ -37,9 +44,19 @@ class TwoFactorInfo extends Component {

return <div class="twoFactorInfo">
<p>
It's currently <strong>{state.enrolled ? "enabled" : "disabled"}</strong> on your account.
It's currently <strong>{twofactorenabled ? "enabled" : "disabled"}</strong> on your account.
</p>
<button class={`btn btn-${state.enrolled ? "danger" : "primary"}`} onClick={this.manage2fa.bind(this)}><i class="fa fa-fw fa-lock" /> {state.enrolled ? "Disable" : "Enable"} two-factor authentication</button>
{(state.enrolledTOTP || state.enrolledWebAuthn) && <p>
In addition to your password, you can log on to your account with a/an
<ul>
{state.enrolledTOTP && <li>Authenticator app</li>}
{state.enrolledWebAuthn && <li>Security key</li>}
</ul>
</p>}
<button class={`btn btn-${twofactorenabled ? "danger" : "primary"}`} onClick={this.manage2fa.bind(this)}><i class="fa fa-fw fa-lock" /> {twofactorenabled ? "Disable" : "Enable"} two-factor authentication</button>

{state.enrolledTOTP && !state.enrolledWebAuthn && <button class="btn btn-primary" onClick={this.manageWebAuthn.bind(this)}><i class="fa fa-fw fa-key" /> Add a security key</button>
}
</div>;
}
}
Expand Down
112 changes: 112 additions & 0 deletions app/settings/panes/account/WebAuthnModal.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { h, Fragment } from "preact";
import { useState } from "preact/hooks";

import { uint8ToBase64 } from "base64.js";
import api from "api.js";
import errors from "errors.js";

import Modal from "ui/Modal.jsx";
import SecurityKeyPrompt from "auth/SecurityKeyPrompt.jsx";
import LoadingIndicator from "ui/LoadingIndicator.jsx";



function bufferDecode(value) {
return Uint8Array.from(atob(value), c => c.charCodeAt(0));
}

function bufferEncode(value) {
return uint8ToBase64(value)
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=/g, "");
}



const Stage0 = () => <> <p>Security keys enable you to use a physical device for two factor authentication, rather than a software generated code.</p>
<p>MyHomeworkSpace currently allows you to add a security key that supports the <strong>FIDO2</strong> (WebAuthn) standard. This includes YubiKeys, Google Titan security keys, and others.</p>
</>;

const Stage2 = () => <>
<p>Your security key has been added successfully.</p>
</>;

export default function WebAuthnModal(props) {
const [err, setErr] = useState("");
const [loading, setLoading] = useState(false);
const [stage, setStage] = useState(0);
const [publicKeyData, setPublicKeyData] = useState(null);

const cancel = stage == 0 ? () => props.openModal("") : () => setStage(stage - 1);

const cont = () => {
if (stage == 0) {
setLoading(true);
api.post("auth/2fa/beginWebAuthn", {}, (data) => {
setPublicKeyData(data.publicKey);
setLoading(false);
setStage(1);
data.publicKey.challenge = bufferDecode(data.publicKey.challenge);
data.publicKey.user.id = bufferDecode(data.publicKey.user.id);
if (data.publicKey.excludeCredentials) {
for (var i = 0; i < data.publicKey.excludeCredentials.length; i++) {
data.publicKey.excludeCredentials[i].id = bufferDecode(data.publicKey.excludeCredentials[i].id);
}
}

navigator.credentials.create({
publicKey: data.publicKey
}).then((credential) => {
let attestationObject = new Uint8Array(credential.response.attestationObject);
let clientDataJSON = new Uint8Array(credential.response.clientDataJSON);
let rawId = new Uint8Array(credential.rawId);
const reqData = {
id: credential.id,
rawId: bufferEncode(rawId),
type: credential.type,
response: {
attestationObject: bufferEncode(attestationObject),
clientDataJSON: bufferEncode(clientDataJSON),
},
};

api.postJSON("auth/2fa/completeWebAuthn", JSON.stringify(reqData), (resp) => {
if (resp.status == "ok") {
setStage(2);
} else {
setErr(errors.getFriendlyString(resp.error));
setStage(1);
}
});
}).catch((err) => {
setStage(0);
setErr(err.toString());
});

});
}

if (stage == 2) {
window.location.reload();
}
};

return <Modal title="Add a security key" openModal={props.openModal} noClose class="webAuthnModal">
<div class="modal-body">
{err && <div class="alert alert-danger">{err}</div>}
{loading && <><LoadingIndicator type="inline" /> Loading, please wait...</>}
{!loading && (() => {
switch (stage) {
case 0: return <Stage0 />;
case 1: return <SecurityKeyPrompt />;
case 2: return <Stage2 />;
}
})()}
</div>
<div class="modal-footer">
{stage != 2 && <button disabled={loading} type="button" class="btn btn-default" onClick={cancel}>{stage == 0 ? "Cancel" : "Back"}</button>}
{stage != 1 && <button disabled={loading} type="button" class="btn btn-primary" onClick={cont}>{stage == 2 ? "Done" : "Continue"}</button>}
</div>
</Modal>;
};
2 changes: 1 addition & 1 deletion app/ui/LoadingIndicator.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ import { h, Component } from "preact";

export default class LoadingIndicator extends Component {
render(props, state) {
return <i class="fa fa-refresh fa-spin" />;
return <i class={`fa fa-refresh fa-spin ${props.type == "large" ? "fa-3x" : ""}`} />;
}
};
2 changes: 2 additions & 0 deletions app/ui/ModalManager.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import EnrollModal from "schools/EnrollModal.jsx";
import SchoolSettingsModal from "schools/SchoolSettingsModal.jsx";
import BackgroundModal from "settings/panes/account/BackgroundModal.jsx";
import TwoFactorModal from "settings/panes/account/TwoFactorModal.jsx";
import WebAuthnModal from "settings/panes/account/WebAuthnModal.jsx";
import ChangeNameModal from "settings/panes/account/ChangeNameModal.jsx";
import MyApplicationDeleteModal from "settings/panes/applications/MyApplicationDeleteModal.jsx";
import MyApplicationSettingsModal from "settings/panes/applications/MyApplicationSettingsModal.jsx";
Expand All @@ -37,6 +38,7 @@ export default class ModalManager extends Component {
enroll: EnrollModal,
background: BackgroundModal,
twoFactor: TwoFactorModal,
webAuthn: WebAuthnModal,
loading: LoadingModal,
changeEmail: ChangeEmailModal,
changePassword: ChangePasswordModal,
Expand Down

0 comments on commit 14f6602

Please sign in to comment.