From 5eefdd86327644598511adc3df075c2b0abb9f07 Mon Sep 17 00:00:00 2001 From: Matthew Miller Date: Thu, 14 Oct 2021 13:35:12 -0700 Subject: [PATCH 01/33] Delete flask_demo --- flask_demo/app.py | 249 -------------- flask_demo/context.py | 6 - flask_demo/create_db.py | 13 - flask_demo/db.py | 4 - flask_demo/models.py | 18 -- flask_demo/py_webauthn.env.example | 1 - flask_demo/requirements.txt | 11 - flask_demo/static/css/base.css | 3 - flask_demo/static/js/lib/base64.js | 118 ------- flask_demo/static/js/lib/jquery-3.2.1.min.js | 4 - flask_demo/static/js/webauthn.js | 305 ------------------ flask_demo/templates/index.html | 37 --- .../HyperFIDO_CA_Cert_V1.pem | 11 - .../HyperFIDO_CA_Cert_V2.pem | 12 - .../solokeys_u2f_device_attestation_ca.pem | 13 - .../yubico_u2f_device_attestation_ca.pem | 19 -- flask_demo/util.py | 68 ---- 17 files changed, 892 deletions(-) delete mode 100644 flask_demo/app.py delete mode 100644 flask_demo/context.py delete mode 100755 flask_demo/create_db.py delete mode 100644 flask_demo/db.py delete mode 100644 flask_demo/models.py delete mode 100644 flask_demo/py_webauthn.env.example delete mode 100644 flask_demo/requirements.txt delete mode 100644 flask_demo/static/css/base.css delete mode 100644 flask_demo/static/js/lib/base64.js delete mode 100644 flask_demo/static/js/lib/jquery-3.2.1.min.js delete mode 100644 flask_demo/static/js/webauthn.js delete mode 100644 flask_demo/templates/index.html delete mode 100644 flask_demo/trusted_attestation_roots/HyperFIDO_CA_Cert_V1.pem delete mode 100644 flask_demo/trusted_attestation_roots/HyperFIDO_CA_Cert_V2.pem delete mode 100644 flask_demo/trusted_attestation_roots/solokeys_u2f_device_attestation_ca.pem delete mode 100644 flask_demo/trusted_attestation_roots/yubico_u2f_device_attestation_ca.pem delete mode 100644 flask_demo/util.py diff --git a/flask_demo/app.py b/flask_demo/app.py deleted file mode 100644 index c0083fd..0000000 --- a/flask_demo/app.py +++ /dev/null @@ -1,249 +0,0 @@ -import os -import sys - -from flask import Flask -from flask import flash -from flask import jsonify -from flask import make_response -from flask import redirect -from flask import render_template -from flask import request -from flask import session -from flask import url_for -from flask_login import LoginManager -from flask_login import login_required -from flask_login import login_user -from flask_login import logout_user - -import util - -from db import db -from context import webauthn -from models import User - -app = Flask(__name__) -app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format( - os.path.join(os.path.dirname(os.path.abspath(__name__)), 'webauthn.db')) -app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False -sk = os.environ.get('FLASK_SECRET_KEY') -app.secret_key = sk if sk else os.urandom(40) -db.init_app(app) -login_manager = LoginManager() -login_manager.init_app(app) - -RP_ID = 'localhost' -RP_NAME = 'webauthn demo localhost' -ORIGIN = 'https://localhost:5000' - -# Trust anchors (trusted attestation roots) should be -# placed in TRUST_ANCHOR_DIR. -TRUST_ANCHOR_DIR = 'trusted_attestation_roots' - - -@login_manager.user_loader -def load_user(user_id): - try: - int(user_id) - except ValueError: - return None - - return User.query.get(int(user_id)) - - -@app.route('/') -def index(): - return render_template('index.html') - - -@app.route('/webauthn_begin_activate', methods=['POST']) -def webauthn_begin_activate(): - # MakeCredentialOptions - username = request.form.get('register_username') - display_name = request.form.get('register_display_name') - - if not util.validate_username(username): - return make_response(jsonify({'fail': 'Invalid username.'}), 401) - if not util.validate_display_name(display_name): - return make_response(jsonify({'fail': 'Invalid display name.'}), 401) - - if User.query.filter_by(username=username).first(): - return make_response(jsonify({'fail': 'User already exists.'}), 401) - - #clear session variables prior to starting a new registration - session.pop('register_ukey', None) - session.pop('register_username', None) - session.pop('register_display_name', None) - session.pop('challenge', None) - - session['register_username'] = username - session['register_display_name'] = display_name - - challenge = util.generate_challenge(32) - ukey = util.generate_ukey() - - # We strip the saved challenge of padding, so that we can do a byte - # comparison on the URL-safe-without-padding challenge we get back - # from the browser. - # We will still pass the padded version down to the browser so that the JS - # can decode the challenge into binary without too much trouble. - session['challenge'] = challenge.rstrip('=') - session['register_ukey'] = ukey - - make_credential_options = webauthn.WebAuthnMakeCredentialOptions( - challenge, RP_NAME, RP_ID, ukey, username, display_name, - 'https://example.com') - - return jsonify(make_credential_options.registration_dict) - - -@app.route('/webauthn_begin_assertion', methods=['POST']) -def webauthn_begin_assertion(): - username = request.form.get('login_username') - - if not util.validate_username(username): - return make_response(jsonify({'fail': 'Invalid username.'}), 401) - - user = User.query.filter_by(username=username).first() - - if not user: - return make_response(jsonify({'fail': 'User does not exist.'}), 401) - if not user.credential_id: - return make_response(jsonify({'fail': 'Unknown credential ID.'}), 401) - - session.pop('challenge', None) - - challenge = util.generate_challenge(32) - - # We strip the padding from the challenge stored in the session - # for the reasons outlined in the comment in webauthn_begin_activate. - session['challenge'] = challenge.rstrip('=') - - webauthn_user = webauthn.WebAuthnUser( - user.ukey, user.username, user.display_name, user.icon_url, - user.credential_id, user.pub_key, user.sign_count, user.rp_id) - - webauthn_assertion_options = webauthn.WebAuthnAssertionOptions( - webauthn_user, challenge) - - return jsonify(webauthn_assertion_options.assertion_dict) - - -@app.route('/verify_credential_info', methods=['POST']) -def verify_credential_info(): - challenge = session['challenge'] - username = session['register_username'] - display_name = session['register_display_name'] - ukey = session['register_ukey'] - - registration_response = request.form - trust_anchor_dir = os.path.join( - os.path.dirname(os.path.abspath(__file__)), TRUST_ANCHOR_DIR) - trusted_attestation_cert_required = True - self_attestation_permitted = True - none_attestation_permitted = True - - webauthn_registration_response = webauthn.WebAuthnRegistrationResponse( - RP_ID, - ORIGIN, - registration_response, - challenge, - trust_anchor_dir, - trusted_attestation_cert_required, - self_attestation_permitted, - none_attestation_permitted, - uv_required=False) # User Verification - - try: - webauthn_credential = webauthn_registration_response.verify() - except Exception as e: - return jsonify({'fail': 'Registration failed. Error: {}'.format(e)}) - - # Step 17. - # - # Check that the credentialId is not yet registered to any other user. - # If registration is requested for a credential that is already registered - # to a different user, the Relying Party SHOULD fail this registration - # ceremony, or it MAY decide to accept the registration, e.g. while deleting - # the older registration. - credential_id_exists = User.query.filter_by( - credential_id=webauthn_credential.credential_id).first() - if credential_id_exists: - return make_response( - jsonify({ - 'fail': 'Credential ID already exists.' - }), 401) - - existing_user = User.query.filter_by(username=username).first() - if not existing_user: - if sys.version_info >= (3, 0): - webauthn_credential.credential_id = str( - webauthn_credential.credential_id, "utf-8") - webauthn_credential.public_key = str( - webauthn_credential.public_key, "utf-8") - user = User( - ukey=ukey, - username=username, - display_name=display_name, - pub_key=webauthn_credential.public_key, - credential_id=webauthn_credential.credential_id, - sign_count=webauthn_credential.sign_count, - rp_id=RP_ID, - icon_url='https://example.com') - db.session.add(user) - db.session.commit() - else: - return make_response(jsonify({'fail': 'User already exists.'}), 401) - - flash('Successfully registered as {}.'.format(username)) - - return jsonify({'success': 'User successfully registered.'}) - - -@app.route('/verify_assertion', methods=['POST']) -def verify_assertion(): - challenge = session.get('challenge') - assertion_response = request.form - credential_id = assertion_response.get('id') - - user = User.query.filter_by(credential_id=credential_id).first() - if not user: - return make_response(jsonify({'fail': 'User does not exist.'}), 401) - - webauthn_user = webauthn.WebAuthnUser( - user.ukey, user.username, user.display_name, user.icon_url, - user.credential_id, user.pub_key, user.sign_count, user.rp_id) - - webauthn_assertion_response = webauthn.WebAuthnAssertionResponse( - webauthn_user, - assertion_response, - challenge, - ORIGIN, - uv_required=False) # User Verification - - try: - sign_count = webauthn_assertion_response.verify() - except Exception as e: - return jsonify({'fail': 'Assertion failed. Error: {}'.format(e)}) - - # Update counter. - user.sign_count = sign_count - db.session.add(user) - db.session.commit() - - login_user(user) - - return jsonify({ - 'success': - 'Successfully authenticated as {}'.format(user.username) - }) - - -@app.route('/logout') -@login_required -def logout(): - logout_user() - return redirect(url_for('index')) - - -if __name__ == '__main__': - app.run(host='0.0.0.0', ssl_context='adhoc', debug=True) diff --git a/flask_demo/context.py b/flask_demo/context.py deleted file mode 100644 index 4f4d1db..0000000 --- a/flask_demo/context.py +++ /dev/null @@ -1,6 +0,0 @@ -import os -import sys - -sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) - -import webauthn # NOQA diff --git a/flask_demo/create_db.py b/flask_demo/create_db.py deleted file mode 100755 index acb0b57..0000000 --- a/flask_demo/create_db.py +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env python - -from app import app -from db import db - - -def main(): - with app.app_context(): - db.create_all() - - -if __name__ == '__main__': - main() diff --git a/flask_demo/db.py b/flask_demo/db.py deleted file mode 100644 index f606adc..0000000 --- a/flask_demo/db.py +++ /dev/null @@ -1,4 +0,0 @@ -from flask_sqlalchemy import SQLAlchemy - - -db = SQLAlchemy() diff --git a/flask_demo/models.py b/flask_demo/models.py deleted file mode 100644 index 38eb675..0000000 --- a/flask_demo/models.py +++ /dev/null @@ -1,18 +0,0 @@ -from db import db -from flask_login import UserMixin - - -class User(db.Model, UserMixin): - id = db.Column(db.Integer, primary_key=True) - - ukey = db.Column(db.String(20), unique=True, nullable=False) - credential_id = db.Column(db.String(250), unique=True, nullable=False) - display_name = db.Column(db.String(160), unique=False, nullable=False) - pub_key = db.Column(db.String(65), unique=True, nullable=True) - sign_count = db.Column(db.Integer, default=0) - username = db.Column(db.String(80), unique=True, nullable=False) - rp_id = db.Column(db.String(253), nullable=False) - icon_url = db.Column(db.String(2083), nullable=False) - - def __repr__(self): - return '' % (self.display_name, self.username) diff --git a/flask_demo/py_webauthn.env.example b/flask_demo/py_webauthn.env.example deleted file mode 100644 index ccfe59e..0000000 --- a/flask_demo/py_webauthn.env.example +++ /dev/null @@ -1 +0,0 @@ -FLASK_SECRET_KEY="INSERT_YOUR_OWN" diff --git a/flask_demo/requirements.txt b/flask_demo/requirements.txt deleted file mode 100644 index 4ab34fe..0000000 --- a/flask_demo/requirements.txt +++ /dev/null @@ -1,11 +0,0 @@ -cbor2==4.0.1 -cryptography==2.3.1 -Flask==1.0.2 -Flask-Login==0.4.0 -Flask-SQLAlchemy>=2.3.2 -Flask-WTF==0.14.2 -future==0.17.1 -pyOpenSSL==17.5.0 -six==1.11.0 -SQLAlchemy>=1.3.3 -WTForms==2.1 diff --git a/flask_demo/static/css/base.css b/flask_demo/static/css/base.css deleted file mode 100644 index 3a247ce..0000000 --- a/flask_demo/static/css/base.css +++ /dev/null @@ -1,3 +0,0 @@ -.flash { - color: #63B246; -} diff --git a/flask_demo/static/js/lib/base64.js b/flask_demo/static/js/lib/base64.js deleted file mode 100644 index 3ebe0a9..0000000 --- a/flask_demo/static/js/lib/base64.js +++ /dev/null @@ -1,118 +0,0 @@ -var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - -;(function (exports) { - 'use strict' - - var Arr = (typeof Uint8Array !== 'undefined') - ? Uint8Array - : Array - - var PLUS = '+'.charCodeAt(0) - var SLASH = '/'.charCodeAt(0) - var NUMBER = '0'.charCodeAt(0) - var LOWER = 'a'.charCodeAt(0) - var UPPER = 'A'.charCodeAt(0) - var PLUS_URL_SAFE = '-'.charCodeAt(0) - var SLASH_URL_SAFE = '_'.charCodeAt(0) - - function decode (elt) { - var 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 - } - - function b64ToByteArray (b64) { - var 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 - var 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 - - var 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 - } - - function uint8ToBase64 (uint8) { - var i - var extraBytes = uint8.length % 3 // if we have 1 byte left, pad 2 bytes - var output = '' - var 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 - } - - exports.toByteArray = b64ToByteArray - exports.fromByteArray = uint8ToBase64 -}(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) \ No newline at end of file diff --git a/flask_demo/static/js/lib/jquery-3.2.1.min.js b/flask_demo/static/js/lib/jquery-3.2.1.min.js deleted file mode 100644 index 644d35e..0000000 --- a/flask_demo/static/js/lib/jquery-3.2.1.min.js +++ /dev/null @@ -1,4 +0,0 @@ -/*! jQuery v3.2.1 | (c) JS Foundation and other contributors | jquery.org/license */ -!function(a,b){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){"use strict";var c=[],d=a.document,e=Object.getPrototypeOf,f=c.slice,g=c.concat,h=c.push,i=c.indexOf,j={},k=j.toString,l=j.hasOwnProperty,m=l.toString,n=m.call(Object),o={};function p(a,b){b=b||d;var c=b.createElement("script");c.text=a,b.head.appendChild(c).parentNode.removeChild(c)}var q="3.2.1",r=function(a,b){return new r.fn.init(a,b)},s=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,t=/^-ms-/,u=/-([a-z])/g,v=function(a,b){return b.toUpperCase()};r.fn=r.prototype={jquery:q,constructor:r,length:0,toArray:function(){return f.call(this)},get:function(a){return null==a?f.call(this):a<0?this[a+this.length]:this[a]},pushStack:function(a){var b=r.merge(this.constructor(),a);return b.prevObject=this,b},each:function(a){return r.each(this,a)},map:function(a){return this.pushStack(r.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(f.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(a<0?b:0);return this.pushStack(c>=0&&c0&&b-1 in a)}var x=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=function(a,b){for(var c=0,d=a.length;c+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(N),U=new RegExp("^"+L+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L+"|[*])"),ATTR:new RegExp("^"+M),PSEUDO:new RegExp("^"+N),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),aa=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:d<0?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ba=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ca=function(a,b){return b?"\0"===a?"\ufffd":a.slice(0,-1)+"\\"+a.charCodeAt(a.length-1).toString(16)+" ":"\\"+a},da=function(){m()},ea=ta(function(a){return a.disabled===!0&&("form"in a||"label"in a)},{dir:"parentNode",next:"legend"});try{G.apply(D=H.call(v.childNodes),v.childNodes),D[v.childNodes.length].nodeType}catch(fa){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s=b&&b.ownerDocument,w=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==w&&9!==w&&11!==w)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==w&&(l=Z.exec(a)))if(f=l[1]){if(9===w){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(s&&(j=s.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(l[2])return G.apply(d,b.getElementsByTagName(a)),d;if((f=l[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==w)s=b,r=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(ba,ca):b.setAttribute("id",k=u),o=g(a),h=o.length;while(h--)o[h]="#"+k+" "+sa(o[h]);r=o.join(","),s=$.test(a)&&qa(b.parentNode)||b}if(r)try{return G.apply(d,s.querySelectorAll(r)),d}catch(x){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(P,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("fieldset");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&a.sourceIndex-b.sourceIndex;if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return function(b){return"form"in b?b.parentNode&&b.disabled===!1?"label"in b?"label"in b.parentNode?b.parentNode.disabled===a:b.disabled===a:b.isDisabled===a||b.isDisabled!==!a&&ea(b)===a:b.disabled===a:"label"in b&&b.disabled===a}}function pa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function qa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return!!b&&"HTML"!==b.nodeName},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),v!==n&&(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(n.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){return a.getAttribute("id")===b}},d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}}):(d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}},d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c,d,e,f=b.getElementById(a);if(f){if(c=f.getAttributeNode("id"),c&&c.value===a)return[f];e=b.getElementsByName(a),d=0;while(f=e[d++])if(c=f.getAttributeNode("id"),c&&c.value===a)return[f]}return[]}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){if("undefined"!=typeof b.getElementsByClassName&&p)return b.getElementsByClassName(a)},r=[],q=[],(c.qsa=Y.test(n.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){a.innerHTML="";var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+K+"*[*^$|!~]?="),2!==a.querySelectorAll(":enabled").length&&q.push(":enabled",":disabled"),o.appendChild(a).disabled=!0,2!==a.querySelectorAll(":disabled").length&&q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Y.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"*"),s.call(a,"[s!='']:x"),r.push("!=",N)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Y.test(o.compareDocumentPosition),t=b||Y.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?I(k,a)-I(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?I(k,a)-I(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?la(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(S,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.escape=function(a){return(a+"").replace(ba,ca)},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(_,aa),a[3]=(a[3]||a[4]||a[5]||"").replace(_,aa),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return V.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&T.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(_,aa).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:!b||(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(O," ")+" ").indexOf(c)>-1:"|="===b&&(e===c||e.slice(0,c.length+1)===c+"-"))}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(P,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(_,aa),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return U.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(_,aa).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:oa(!1),disabled:oa(!0),checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:pa(function(){return[0]}),last:pa(function(a,b){return[b-1]}),eq:pa(function(a,b,c){return[c<0?c+b:c]}),even:pa(function(a,b){for(var c=0;c=0;)a.push(d);return a}),gt:pa(function(a,b,c){for(var d=c<0?c+b:c;++d1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function va(a,b,c){for(var d=0,e=b.length;d-1&&(f[j]=!(g[j]=l))}}else r=wa(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ya(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ta(function(a){return a===b},h,!0),l=ta(function(a){return I(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];i1&&ua(m),i>1&&sa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(P,"$1"),c,i0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=E.call(i));u=wa(u)}G.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&ga.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=ya(b[c]),f[u]?d.push(f):e.push(f);f=A(a,za(e,d)),f.selector=a}return f},i=ga.select=function(a,b,c,e){var f,i,j,k,l,m="function"==typeof a&&a,n=!e&&g(a=m.selector||a);if(c=c||[],1===n.length){if(i=n[0]=n[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&9===b.nodeType&&p&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(_,aa),b)||[])[0],!b)return c;m&&(b=b.parentNode),a=a.slice(i.shift().value.length)}f=V.needsContext.test(a)?0:i.length;while(f--){if(j=i[f],d.relative[k=j.type])break;if((l=d.find[k])&&(e=l(j.matches[0].replace(_,aa),$.test(i[0].type)&&qa(b.parentNode)||b))){if(i.splice(f,1),a=e.length&&sa(i),!a)return G.apply(c,e),c;break}}}return(m||h(a,n))(e,b,!p,c,!b||$.test(a)&&qa(b.parentNode)||b),c},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("fieldset"))}),ja(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){if(!c)return a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){if(!c&&"input"===a.nodeName.toLowerCase())return a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(J,function(a,b,c){var d;if(!c)return a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);r.find=x,r.expr=x.selectors,r.expr[":"]=r.expr.pseudos,r.uniqueSort=r.unique=x.uniqueSort,r.text=x.getText,r.isXMLDoc=x.isXML,r.contains=x.contains,r.escapeSelector=x.escape;var y=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&r(a).is(c))break;d.push(a)}return d},z=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},A=r.expr.match.needsContext;function B(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()}var C=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i,D=/^.[^:#\[\.,]*$/;function E(a,b,c){return r.isFunction(b)?r.grep(a,function(a,d){return!!b.call(a,d,a)!==c}):b.nodeType?r.grep(a,function(a){return a===b!==c}):"string"!=typeof b?r.grep(a,function(a){return i.call(b,a)>-1!==c}):D.test(b)?r.filter(b,a,c):(b=r.filter(b,a),r.grep(a,function(a){return i.call(b,a)>-1!==c&&1===a.nodeType}))}r.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?r.find.matchesSelector(d,a)?[d]:[]:r.find.matches(a,r.grep(b,function(a){return 1===a.nodeType}))},r.fn.extend({find:function(a){var b,c,d=this.length,e=this;if("string"!=typeof a)return this.pushStack(r(a).filter(function(){for(b=0;b1?r.uniqueSort(c):c},filter:function(a){return this.pushStack(E(this,a||[],!1))},not:function(a){return this.pushStack(E(this,a||[],!0))},is:function(a){return!!E(this,"string"==typeof a&&A.test(a)?r(a):a||[],!1).length}});var F,G=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,H=r.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||F,"string"==typeof a){if(e="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:G.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof r?b[0]:b,r.merge(this,r.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),C.test(e[1])&&r.isPlainObject(b))for(e in b)r.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&(this[0]=f,this.length=1),this}return a.nodeType?(this[0]=a,this.length=1,this):r.isFunction(a)?void 0!==c.ready?c.ready(a):a(r):r.makeArray(a,this)};H.prototype=r.fn,F=r(d);var I=/^(?:parents|prev(?:Until|All))/,J={children:!0,contents:!0,next:!0,prev:!0};r.fn.extend({has:function(a){var b=r(a,this),c=b.length;return this.filter(function(){for(var a=0;a-1:1===c.nodeType&&r.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?r.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?i.call(r(a),this[0]):i.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(r.uniqueSort(r.merge(this.get(),r(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function K(a,b){while((a=a[b])&&1!==a.nodeType);return a}r.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return y(a,"parentNode")},parentsUntil:function(a,b,c){return y(a,"parentNode",c)},next:function(a){return K(a,"nextSibling")},prev:function(a){return K(a,"previousSibling")},nextAll:function(a){return y(a,"nextSibling")},prevAll:function(a){return y(a,"previousSibling")},nextUntil:function(a,b,c){return y(a,"nextSibling",c)},prevUntil:function(a,b,c){return y(a,"previousSibling",c)},siblings:function(a){return z((a.parentNode||{}).firstChild,a)},children:function(a){return z(a.firstChild)},contents:function(a){return B(a,"iframe")?a.contentDocument:(B(a,"template")&&(a=a.content||a),r.merge([],a.childNodes))}},function(a,b){r.fn[a]=function(c,d){var e=r.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=r.filter(d,e)),this.length>1&&(J[a]||r.uniqueSort(e),I.test(a)&&e.reverse()),this.pushStack(e)}});var L=/[^\x20\t\r\n\f]+/g;function M(a){var b={};return r.each(a.match(L)||[],function(a,c){b[c]=!0}),b}r.Callbacks=function(a){a="string"==typeof a?M(a):r.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=e||a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h-1)f.splice(c,1),c<=h&&h--}),this},has:function(a){return a?r.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=g=[],c||b||(f=c=""),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j};function N(a){return a}function O(a){throw a}function P(a,b,c,d){var e;try{a&&r.isFunction(e=a.promise)?e.call(a).done(b).fail(c):a&&r.isFunction(e=a.then)?e.call(a,b,c):b.apply(void 0,[a].slice(d))}catch(a){c.apply(void 0,[a])}}r.extend({Deferred:function(b){var c=[["notify","progress",r.Callbacks("memory"),r.Callbacks("memory"),2],["resolve","done",r.Callbacks("once memory"),r.Callbacks("once memory"),0,"resolved"],["reject","fail",r.Callbacks("once memory"),r.Callbacks("once memory"),1,"rejected"]],d="pending",e={state:function(){return d},always:function(){return f.done(arguments).fail(arguments),this},"catch":function(a){return e.then(null,a)},pipe:function(){var a=arguments;return r.Deferred(function(b){r.each(c,function(c,d){var e=r.isFunction(a[d[4]])&&a[d[4]];f[d[1]](function(){var a=e&&e.apply(this,arguments);a&&r.isFunction(a.promise)?a.promise().progress(b.notify).done(b.resolve).fail(b.reject):b[d[0]+"With"](this,e?[a]:arguments)})}),a=null}).promise()},then:function(b,d,e){var f=0;function g(b,c,d,e){return function(){var h=this,i=arguments,j=function(){var a,j;if(!(b=f&&(d!==O&&(h=void 0,i=[a]),c.rejectWith(h,i))}};b?k():(r.Deferred.getStackHook&&(k.stackTrace=r.Deferred.getStackHook()),a.setTimeout(k))}}return r.Deferred(function(a){c[0][3].add(g(0,a,r.isFunction(e)?e:N,a.notifyWith)),c[1][3].add(g(0,a,r.isFunction(b)?b:N)),c[2][3].add(g(0,a,r.isFunction(d)?d:O))}).promise()},promise:function(a){return null!=a?r.extend(a,e):e}},f={};return r.each(c,function(a,b){var g=b[2],h=b[5];e[b[1]]=g.add,h&&g.add(function(){d=h},c[3-a][2].disable,c[0][2].lock),g.add(b[3].fire),f[b[0]]=function(){return f[b[0]+"With"](this===f?void 0:this,arguments),this},f[b[0]+"With"]=g.fireWith}),e.promise(f),b&&b.call(f,f),f},when:function(a){var b=arguments.length,c=b,d=Array(c),e=f.call(arguments),g=r.Deferred(),h=function(a){return function(c){d[a]=this,e[a]=arguments.length>1?f.call(arguments):c,--b||g.resolveWith(d,e)}};if(b<=1&&(P(a,g.done(h(c)).resolve,g.reject,!b),"pending"===g.state()||r.isFunction(e[c]&&e[c].then)))return g.then();while(c--)P(e[c],h(c),g.reject);return g.promise()}});var Q=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;r.Deferred.exceptionHook=function(b,c){a.console&&a.console.warn&&b&&Q.test(b.name)&&a.console.warn("jQuery.Deferred exception: "+b.message,b.stack,c)},r.readyException=function(b){a.setTimeout(function(){throw b})};var R=r.Deferred();r.fn.ready=function(a){return R.then(a)["catch"](function(a){r.readyException(a)}),this},r.extend({isReady:!1,readyWait:1,ready:function(a){(a===!0?--r.readyWait:r.isReady)||(r.isReady=!0,a!==!0&&--r.readyWait>0||R.resolveWith(d,[r]))}}),r.ready.then=R.then;function S(){d.removeEventListener("DOMContentLoaded",S), -a.removeEventListener("load",S),r.ready()}"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(r.ready):(d.addEventListener("DOMContentLoaded",S),a.addEventListener("load",S));var T=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===r.type(c)){e=!0;for(h in c)T(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,r.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(r(a),c)})),b))for(;h1,null,!0)},removeData:function(a){return this.each(function(){X.remove(this,a)})}}),r.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=W.get(a,b),c&&(!d||Array.isArray(c)?d=W.access(a,b,r.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=r.queue(a,b),d=c.length,e=c.shift(),f=r._queueHooks(a,b),g=function(){r.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return W.get(a,c)||W.access(a,c,{empty:r.Callbacks("once memory").add(function(){W.remove(a,[b+"queue",c])})})}}),r.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length\x20\t\r\n\f]+)/i,la=/^$|\/(?:java|ecma)script/i,ma={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ma.optgroup=ma.option,ma.tbody=ma.tfoot=ma.colgroup=ma.caption=ma.thead,ma.th=ma.td;function na(a,b){var c;return c="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):[],void 0===b||b&&B(a,b)?r.merge([a],c):c}function oa(a,b){for(var c=0,d=a.length;c-1)e&&e.push(f);else if(j=r.contains(f.ownerDocument,f),g=na(l.appendChild(f),"script"),j&&oa(g),c){k=0;while(f=g[k++])la.test(f.type||"")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),o.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="",o.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var ra=d.documentElement,sa=/^key/,ta=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,ua=/^([^.]*)(?:\.(.+)|)/;function va(){return!0}function wa(){return!1}function xa(){try{return d.activeElement}catch(a){}}function ya(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)ya(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=wa;else if(!e)return a;return 1===f&&(g=e,e=function(a){return r().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=r.guid++)),a.each(function(){r.event.add(this,b,e,d,c)})}r.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=W.get(a);if(q){c.handler&&(f=c,c=f.handler,e=f.selector),e&&r.find.matchesSelector(ra,e),c.guid||(c.guid=r.guid++),(i=q.events)||(i=q.events={}),(g=q.handle)||(g=q.handle=function(b){return"undefined"!=typeof r&&r.event.triggered!==b.type?r.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(L)||[""],j=b.length;while(j--)h=ua.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n&&(l=r.event.special[n]||{},n=(e?l.delegateType:l.bindType)||n,l=r.event.special[n]||{},k=r.extend({type:n,origType:p,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&r.expr.match.needsContext.test(e),namespace:o.join(".")},f),(m=i[n])||(m=i[n]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,o,g)!==!1||a.addEventListener&&a.addEventListener(n,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),r.event.global[n]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=W.hasData(a)&&W.get(a);if(q&&(i=q.events)){b=(b||"").match(L)||[""],j=b.length;while(j--)if(h=ua.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n){l=r.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=i[n]||[],h=h[2]&&new RegExp("(^|\\.)"+o.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&p!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,o,q.handle)!==!1||r.removeEvent(a,n,q.handle),delete i[n])}else for(n in i)r.event.remove(a,n+b[j],c,d,!0);r.isEmptyObject(i)&&W.remove(a,"handle events")}},dispatch:function(a){var b=r.event.fix(a),c,d,e,f,g,h,i=new Array(arguments.length),j=(W.get(this,"events")||{})[b.type]||[],k=r.event.special[b.type]||{};for(i[0]=b,c=1;c=1))for(;j!==this;j=j.parentNode||this)if(1===j.nodeType&&("click"!==a.type||j.disabled!==!0)){for(f=[],g={},c=0;c-1:r.find(e,this,null,[j]).length),g[e]&&f.push(d);f.length&&h.push({elem:j,handlers:f})}return j=this,i\x20\t\r\n\f]*)[^>]*)\/>/gi,Aa=/\s*$/g;function Ea(a,b){return B(a,"table")&&B(11!==b.nodeType?b:b.firstChild,"tr")?r(">tbody",a)[0]||a:a}function Fa(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function Ga(a){var b=Ca.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ha(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(W.hasData(a)&&(f=W.access(a),g=W.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;c1&&"string"==typeof q&&!o.checkClone&&Ba.test(q))return a.each(function(e){var f=a.eq(e);s&&(b[0]=q.call(this,e,f.html())),Ja(f,b,c,d)});if(m&&(e=qa(b,a[0].ownerDocument,!1,a,d),f=e.firstChild,1===e.childNodes.length&&(e=f),f||d)){for(h=r.map(na(e,"script"),Fa),i=h.length;l")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=r.contains(a.ownerDocument,a);if(!(o.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||r.isXMLDoc(a)))for(g=na(h),f=na(a),d=0,e=f.length;d0&&oa(g,!i&&na(a,"script")),h},cleanData:function(a){for(var b,c,d,e=r.event.special,f=0;void 0!==(c=a[f]);f++)if(U(c)){if(b=c[W.expando]){if(b.events)for(d in b.events)e[d]?r.event.remove(c,d):r.removeEvent(c,d,b.handle);c[W.expando]=void 0}c[X.expando]&&(c[X.expando]=void 0)}}}),r.fn.extend({detach:function(a){return Ka(this,a,!0)},remove:function(a){return Ka(this,a)},text:function(a){return T(this,function(a){return void 0===a?r.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return Ja(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ea(this,a);b.appendChild(a)}})},prepend:function(){return Ja(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ea(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ja(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ja(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(r.cleanData(na(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null!=a&&a,b=null==b?a:b,this.map(function(){return r.clone(this,a,b)})},html:function(a){return T(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!Aa.test(a)&&!ma[(ka.exec(a)||["",""])[1].toLowerCase()]){a=r.htmlPrefilter(a);try{for(;c1)}});function _a(a,b,c,d,e){return new _a.prototype.init(a,b,c,d,e)}r.Tween=_a,_a.prototype={constructor:_a,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||r.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(r.cssNumber[c]?"":"px")},cur:function(){var a=_a.propHooks[this.prop];return a&&a.get?a.get(this):_a.propHooks._default.get(this)},run:function(a){var b,c=_a.propHooks[this.prop];return this.options.duration?this.pos=b=r.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):_a.propHooks._default.set(this),this}},_a.prototype.init.prototype=_a.prototype,_a.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=r.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){r.fx.step[a.prop]?r.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[r.cssProps[a.prop]]&&!r.cssHooks[a.prop]?a.elem[a.prop]=a.now:r.style(a.elem,a.prop,a.now+a.unit)}}},_a.propHooks.scrollTop=_a.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},r.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},r.fx=_a.prototype.init,r.fx.step={};var ab,bb,cb=/^(?:toggle|show|hide)$/,db=/queueHooks$/;function eb(){bb&&(d.hidden===!1&&a.requestAnimationFrame?a.requestAnimationFrame(eb):a.setTimeout(eb,r.fx.interval),r.fx.tick())}function fb(){return a.setTimeout(function(){ab=void 0}),ab=r.now()}function gb(a,b){var c,d=0,e={height:a};for(b=b?1:0;d<4;d+=2-b)c=ca[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function hb(a,b,c){for(var d,e=(kb.tweeners[b]||[]).concat(kb.tweeners["*"]),f=0,g=e.length;f1)},removeAttr:function(a){return this.each(function(){r.removeAttr(this,a)})}}),r.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?r.prop(a,b,c):(1===f&&r.isXMLDoc(a)||(e=r.attrHooks[b.toLowerCase()]||(r.expr.match.bool.test(b)?lb:void 0)),void 0!==c?null===c?void r.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=r.find.attr(a,b), -null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!o.radioValue&&"radio"===b&&B(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d=0,e=b&&b.match(L);if(e&&1===a.nodeType)while(c=e[d++])a.removeAttribute(c)}}),lb={set:function(a,b,c){return b===!1?r.removeAttr(a,c):a.setAttribute(c,c),c}},r.each(r.expr.match.bool.source.match(/\w+/g),function(a,b){var c=mb[b]||r.find.attr;mb[b]=function(a,b,d){var e,f,g=b.toLowerCase();return d||(f=mb[g],mb[g]=e,e=null!=c(a,b,d)?g:null,mb[g]=f),e}});var nb=/^(?:input|select|textarea|button)$/i,ob=/^(?:a|area)$/i;r.fn.extend({prop:function(a,b){return T(this,r.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[r.propFix[a]||a]})}}),r.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&r.isXMLDoc(a)||(b=r.propFix[b]||b,e=r.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=r.find.attr(a,"tabindex");return b?parseInt(b,10):nb.test(a.nodeName)||ob.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),o.optSelected||(r.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),r.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){r.propFix[this.toLowerCase()]=this});function pb(a){var b=a.match(L)||[];return b.join(" ")}function qb(a){return a.getAttribute&&a.getAttribute("class")||""}r.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).addClass(a.call(this,b,qb(this)))});if("string"==typeof a&&a){b=a.match(L)||[];while(c=this[i++])if(e=qb(c),d=1===c.nodeType&&" "+pb(e)+" "){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=pb(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).removeClass(a.call(this,b,qb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(L)||[];while(c=this[i++])if(e=qb(c),d=1===c.nodeType&&" "+pb(e)+" "){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=pb(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):r.isFunction(a)?this.each(function(c){r(this).toggleClass(a.call(this,c,qb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=r(this),f=a.match(L)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=qb(this),b&&W.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||a===!1?"":W.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+pb(qb(c))+" ").indexOf(b)>-1)return!0;return!1}});var rb=/\r/g;r.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=r.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,r(this).val()):a,null==e?e="":"number"==typeof e?e+="":Array.isArray(e)&&(e=r.map(e,function(a){return null==a?"":a+""})),b=r.valHooks[this.type]||r.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=r.valHooks[e.type]||r.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(rb,""):null==c?"":c)}}}),r.extend({valHooks:{option:{get:function(a){var b=r.find.attr(a,"value");return null!=b?b:pb(r.text(a))}},select:{get:function(a){var b,c,d,e=a.options,f=a.selectedIndex,g="select-one"===a.type,h=g?null:[],i=g?f+1:e.length;for(d=f<0?i:g?f:0;d-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),r.each(["radio","checkbox"],function(){r.valHooks[this]={set:function(a,b){if(Array.isArray(b))return a.checked=r.inArray(r(a).val(),b)>-1}},o.checkOn||(r.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var sb=/^(?:focusinfocus|focusoutblur)$/;r.extend(r.event,{trigger:function(b,c,e,f){var g,h,i,j,k,m,n,o=[e||d],p=l.call(b,"type")?b.type:b,q=l.call(b,"namespace")?b.namespace.split("."):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!sb.test(p+r.event.triggered)&&(p.indexOf(".")>-1&&(q=p.split("."),p=q.shift(),q.sort()),k=p.indexOf(":")<0&&"on"+p,b=b[r.expando]?b:new r.Event(p,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=q.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:r.makeArray(c,[b]),n=r.event.special[p]||{},f||!n.trigger||n.trigger.apply(e,c)!==!1)){if(!f&&!n.noBubble&&!r.isWindow(e)){for(j=n.delegateType||p,sb.test(j+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),i=h;i===(e.ownerDocument||d)&&o.push(i.defaultView||i.parentWindow||a)}g=0;while((h=o[g++])&&!b.isPropagationStopped())b.type=g>1?j:n.bindType||p,m=(W.get(h,"events")||{})[b.type]&&W.get(h,"handle"),m&&m.apply(h,c),m=k&&h[k],m&&m.apply&&U(h)&&(b.result=m.apply(h,c),b.result===!1&&b.preventDefault());return b.type=p,f||b.isDefaultPrevented()||n._default&&n._default.apply(o.pop(),c)!==!1||!U(e)||k&&r.isFunction(e[p])&&!r.isWindow(e)&&(i=e[k],i&&(e[k]=null),r.event.triggered=p,e[p](),r.event.triggered=void 0,i&&(e[k]=i)),b.result}},simulate:function(a,b,c){var d=r.extend(new r.Event,c,{type:a,isSimulated:!0});r.event.trigger(d,null,b)}}),r.fn.extend({trigger:function(a,b){return this.each(function(){r.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];if(c)return r.event.trigger(a,b,c,!0)}}),r.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(a,b){r.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),r.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),o.focusin="onfocusin"in a,o.focusin||r.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){r.event.simulate(b,a.target,r.event.fix(a))};r.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=W.access(d,b);e||d.addEventListener(a,c,!0),W.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=W.access(d,b)-1;e?W.access(d,b,e):(d.removeEventListener(a,c,!0),W.remove(d,b))}}});var tb=a.location,ub=r.now(),vb=/\?/;r.parseXML=function(b){var c;if(!b||"string"!=typeof b)return null;try{c=(new a.DOMParser).parseFromString(b,"text/xml")}catch(d){c=void 0}return c&&!c.getElementsByTagName("parsererror").length||r.error("Invalid XML: "+b),c};var wb=/\[\]$/,xb=/\r?\n/g,yb=/^(?:submit|button|image|reset|file)$/i,zb=/^(?:input|select|textarea|keygen)/i;function Ab(a,b,c,d){var e;if(Array.isArray(b))r.each(b,function(b,e){c||wb.test(a)?d(a,e):Ab(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==r.type(b))d(a,b);else for(e in b)Ab(a+"["+e+"]",b[e],c,d)}r.param=function(a,b){var c,d=[],e=function(a,b){var c=r.isFunction(b)?b():b;d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(null==c?"":c)};if(Array.isArray(a)||a.jquery&&!r.isPlainObject(a))r.each(a,function(){e(this.name,this.value)});else for(c in a)Ab(c,a[c],b,e);return d.join("&")},r.fn.extend({serialize:function(){return r.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=r.prop(this,"elements");return a?r.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!r(this).is(":disabled")&&zb.test(this.nodeName)&&!yb.test(a)&&(this.checked||!ja.test(a))}).map(function(a,b){var c=r(this).val();return null==c?null:Array.isArray(c)?r.map(c,function(a){return{name:b.name,value:a.replace(xb,"\r\n")}}):{name:b.name,value:c.replace(xb,"\r\n")}}).get()}});var Bb=/%20/g,Cb=/#.*$/,Db=/([?&])_=[^&]*/,Eb=/^(.*?):[ \t]*([^\r\n]*)$/gm,Fb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Gb=/^(?:GET|HEAD)$/,Hb=/^\/\//,Ib={},Jb={},Kb="*/".concat("*"),Lb=d.createElement("a");Lb.href=tb.href;function Mb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(L)||[];if(r.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nb(a,b,c,d){var e={},f=a===Jb;function g(h){var i;return e[h]=!0,r.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Ob(a,b){var c,d,e=r.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&r.extend(!0,a,d),a}function Pb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}if(f)return f!==i[0]&&i.unshift(f),c[f]}function Qb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}r.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:tb.href,type:"GET",isLocal:Fb.test(tb.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":r.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Ob(Ob(a,r.ajaxSettings),b):Ob(r.ajaxSettings,a)},ajaxPrefilter:Mb(Ib),ajaxTransport:Mb(Jb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var e,f,g,h,i,j,k,l,m,n,o=r.ajaxSetup({},c),p=o.context||o,q=o.context&&(p.nodeType||p.jquery)?r(p):r.event,s=r.Deferred(),t=r.Callbacks("once memory"),u=o.statusCode||{},v={},w={},x="canceled",y={readyState:0,getResponseHeader:function(a){var b;if(k){if(!h){h={};while(b=Eb.exec(g))h[b[1].toLowerCase()]=b[2]}b=h[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return k?g:null},setRequestHeader:function(a,b){return null==k&&(a=w[a.toLowerCase()]=w[a.toLowerCase()]||a,v[a]=b),this},overrideMimeType:function(a){return null==k&&(o.mimeType=a),this},statusCode:function(a){var b;if(a)if(k)y.always(a[y.status]);else for(b in a)u[b]=[u[b],a[b]];return this},abort:function(a){var b=a||x;return e&&e.abort(b),A(0,b),this}};if(s.promise(y),o.url=((b||o.url||tb.href)+"").replace(Hb,tb.protocol+"//"),o.type=c.method||c.type||o.method||o.type,o.dataTypes=(o.dataType||"*").toLowerCase().match(L)||[""],null==o.crossDomain){j=d.createElement("a");try{j.href=o.url,j.href=j.href,o.crossDomain=Lb.protocol+"//"+Lb.host!=j.protocol+"//"+j.host}catch(z){o.crossDomain=!0}}if(o.data&&o.processData&&"string"!=typeof o.data&&(o.data=r.param(o.data,o.traditional)),Nb(Ib,o,c,y),k)return y;l=r.event&&o.global,l&&0===r.active++&&r.event.trigger("ajaxStart"),o.type=o.type.toUpperCase(),o.hasContent=!Gb.test(o.type),f=o.url.replace(Cb,""),o.hasContent?o.data&&o.processData&&0===(o.contentType||"").indexOf("application/x-www-form-urlencoded")&&(o.data=o.data.replace(Bb,"+")):(n=o.url.slice(f.length),o.data&&(f+=(vb.test(f)?"&":"?")+o.data,delete o.data),o.cache===!1&&(f=f.replace(Db,"$1"),n=(vb.test(f)?"&":"?")+"_="+ub++ +n),o.url=f+n),o.ifModified&&(r.lastModified[f]&&y.setRequestHeader("If-Modified-Since",r.lastModified[f]),r.etag[f]&&y.setRequestHeader("If-None-Match",r.etag[f])),(o.data&&o.hasContent&&o.contentType!==!1||c.contentType)&&y.setRequestHeader("Content-Type",o.contentType),y.setRequestHeader("Accept",o.dataTypes[0]&&o.accepts[o.dataTypes[0]]?o.accepts[o.dataTypes[0]]+("*"!==o.dataTypes[0]?", "+Kb+"; q=0.01":""):o.accepts["*"]);for(m in o.headers)y.setRequestHeader(m,o.headers[m]);if(o.beforeSend&&(o.beforeSend.call(p,y,o)===!1||k))return y.abort();if(x="abort",t.add(o.complete),y.done(o.success),y.fail(o.error),e=Nb(Jb,o,c,y)){if(y.readyState=1,l&&q.trigger("ajaxSend",[y,o]),k)return y;o.async&&o.timeout>0&&(i=a.setTimeout(function(){y.abort("timeout")},o.timeout));try{k=!1,e.send(v,A)}catch(z){if(k)throw z;A(-1,z)}}else A(-1,"No Transport");function A(b,c,d,h){var j,m,n,v,w,x=c;k||(k=!0,i&&a.clearTimeout(i),e=void 0,g=h||"",y.readyState=b>0?4:0,j=b>=200&&b<300||304===b,d&&(v=Pb(o,y,d)),v=Qb(o,v,y,j),j?(o.ifModified&&(w=y.getResponseHeader("Last-Modified"),w&&(r.lastModified[f]=w),w=y.getResponseHeader("etag"),w&&(r.etag[f]=w)),204===b||"HEAD"===o.type?x="nocontent":304===b?x="notmodified":(x=v.state,m=v.data,n=v.error,j=!n)):(n=x,!b&&x||(x="error",b<0&&(b=0))),y.status=b,y.statusText=(c||x)+"",j?s.resolveWith(p,[m,x,y]):s.rejectWith(p,[y,x,n]),y.statusCode(u),u=void 0,l&&q.trigger(j?"ajaxSuccess":"ajaxError",[y,o,j?m:n]),t.fireWith(p,[y,x]),l&&(q.trigger("ajaxComplete",[y,o]),--r.active||r.event.trigger("ajaxStop")))}return y},getJSON:function(a,b,c){return r.get(a,b,c,"json")},getScript:function(a,b){return r.get(a,void 0,b,"script")}}),r.each(["get","post"],function(a,b){r[b]=function(a,c,d,e){return r.isFunction(c)&&(e=e||d,d=c,c=void 0),r.ajax(r.extend({url:a,type:b,dataType:e,data:c,success:d},r.isPlainObject(a)&&a))}}),r._evalUrl=function(a){return r.ajax({url:a,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},r.fn.extend({wrapAll:function(a){var b;return this[0]&&(r.isFunction(a)&&(a=a.call(this[0])),b=r(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this},wrapInner:function(a){return r.isFunction(a)?this.each(function(b){r(this).wrapInner(a.call(this,b))}):this.each(function(){var b=r(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=r.isFunction(a);return this.each(function(c){r(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(a){return this.parent(a).not("body").each(function(){r(this).replaceWith(this.childNodes)}),this}}),r.expr.pseudos.hidden=function(a){return!r.expr.pseudos.visible(a)},r.expr.pseudos.visible=function(a){return!!(a.offsetWidth||a.offsetHeight||a.getClientRects().length)},r.ajaxSettings.xhr=function(){try{return new a.XMLHttpRequest}catch(b){}};var Rb={0:200,1223:204},Sb=r.ajaxSettings.xhr();o.cors=!!Sb&&"withCredentials"in Sb,o.ajax=Sb=!!Sb,r.ajaxTransport(function(b){var c,d;if(o.cors||Sb&&!b.crossDomain)return{send:function(e,f){var g,h=b.xhr();if(h.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(g in b.xhrFields)h[g]=b.xhrFields[g];b.mimeType&&h.overrideMimeType&&h.overrideMimeType(b.mimeType),b.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");for(g in e)h.setRequestHeader(g,e[g]);c=function(a){return function(){c&&(c=d=h.onload=h.onerror=h.onabort=h.onreadystatechange=null,"abort"===a?h.abort():"error"===a?"number"!=typeof h.status?f(0,"error"):f(h.status,h.statusText):f(Rb[h.status]||h.status,h.statusText,"text"!==(h.responseType||"text")||"string"!=typeof h.responseText?{binary:h.response}:{text:h.responseText},h.getAllResponseHeaders()))}},h.onload=c(),d=h.onerror=c("error"),void 0!==h.onabort?h.onabort=d:h.onreadystatechange=function(){4===h.readyState&&a.setTimeout(function(){c&&d()})},c=c("abort");try{h.send(b.hasContent&&b.data||null)}catch(i){if(c)throw i}},abort:function(){c&&c()}}}),r.ajaxPrefilter(function(a){a.crossDomain&&(a.contents.script=!1)}),r.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return r.globalEval(a),a}}}),r.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),r.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(e,f){b=r(" - - - WebAuthn Test - -

WebAuthn Test

- {% with messages = get_flashed_messages() %} - {% if messages %} - {% for message in messages %} -

{{ message }} - {% endfor %} - {% endif %} - {% endwith %} - {% if current_user.is_authenticated %} -

Logged in as {{ current_user.username }} | Logout

- {% else %} -

Register

-
- - - - - -
- -
- -

Log In

-
- - - -
- {% endif %} - - diff --git a/flask_demo/trusted_attestation_roots/HyperFIDO_CA_Cert_V1.pem b/flask_demo/trusted_attestation_roots/HyperFIDO_CA_Cert_V1.pem deleted file mode 100644 index 3adb65f..0000000 --- a/flask_demo/trusted_attestation_roots/HyperFIDO_CA_Cert_V1.pem +++ /dev/null @@ -1,11 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIBjTCCATOgAwIBAgIBATAKBggqhkjOPQQDAjAXMRUwEwYDVQQDEwxGVCBGSURP -IDAxMDAwHhcNMTQwNzAxMTUzNjI2WhcNNDQwNzAzMTUzNjI2WjAXMRUwEwYDVQQD -EwxGVCBGSURPIDAxMDAwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASxdLxJx8ol -S3DS5cIHzunPF0gg69d+o8ZVCMJtpRtlfBzGuVL4YhaXk2SC2gptPTgmpZCV2vbN -fAPi5gOF0vbZo3AwbjAdBgNVHQ4EFgQUXt4jWlYDgwhaPU+EqLmeM9LoPRMwPwYD -VR0jBDgwNoAUXt4jWlYDgwhaPU+EqLmeM9LoPROhG6QZMBcxFTATBgNVBAMTDEZU -IEZJRE8gMDEwMIIBATAMBgNVHRMEBTADAQH/MAoGCCqGSM49BAMCA0gAMEUCIQC2 -D9o9cconKTo8+4GZPyZBJ3amc8F0/kzyidX9dhrAIAIgM9ocs5BW/JfmshVP9Mb+ -Joa/kgX4dWbZxrk0ioTfJZg= ------END CERTIFICATE----- diff --git a/flask_demo/trusted_attestation_roots/HyperFIDO_CA_Cert_V2.pem b/flask_demo/trusted_attestation_roots/HyperFIDO_CA_Cert_V2.pem deleted file mode 100644 index a3da385..0000000 --- a/flask_demo/trusted_attestation_roots/HyperFIDO_CA_Cert_V2.pem +++ /dev/null @@ -1,12 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIBxzCCAWygAwIBAgICEAswCgYIKoZIzj0EAwIwOjELMAkGA1UEBhMCQ0ExEjAQ -BgNVBAoMCUhZUEVSU0VDVTEXMBUGA1UEAwwOSFlQRVJGSURPIDAyMDAwIBcNMTgw -MTAxMDAwMDAwWhgPMjA0NzEyMzEyMzU5NTlaMDoxCzAJBgNVBAYTAkNBMRIwEAYD -VQQKDAlIWVBFUlNFQ1UxFzAVBgNVBAMMDkhZUEVSRklETyAwMjAwMFkwEwYHKoZI -zj0CAQYIKoZIzj0DAQcDQgAErKUI1G0S7a6IOLlmHipLlBuxTYjsEESQvzQh3dB7 -dvxxWWm7kWL91rq6S7ayZG0gZPR+zYqdFzwAYDcG4+aX66NgMF4wHQYDVR0OBBYE -FLZYcfMMwkQAGbt3ryzZFPFypmsIMB8GA1UdIwQYMBaAFLZYcfMMwkQAGbt3ryzZ -FPFypmsIMAwGA1UdEwQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMC -A0kAMEYCIQCG2/ppMGt7pkcRie5YIohS3uDPIrmiRcTjqDclKVWg0gIhANcPNDZH -E2/zZ+uB5ThG9OZus+xSb4knkrbAyXKX2zm/ ------END CERTIFICATE----- diff --git a/flask_demo/trusted_attestation_roots/solokeys_u2f_device_attestation_ca.pem b/flask_demo/trusted_attestation_roots/solokeys_u2f_device_attestation_ca.pem deleted file mode 100644 index 5343801..0000000 --- a/flask_demo/trusted_attestation_roots/solokeys_u2f_device_attestation_ca.pem +++ /dev/null @@ -1,13 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIB9DCCAZoCCQDER2OSj/S+jDAKBggqhkjOPQQDAjCBgDELMAkGA1UEBhMCVVMx -ETAPBgNVBAgMCE1hcnlsYW5kMRIwEAYDVQQKDAlTb2xvIEtleXMxEDAOBgNVBAsM -B1Jvb3QgQ0ExFTATBgNVBAMMDHNvbG9rZXlzLmNvbTEhMB8GCSqGSIb3DQEJARYS -aGVsbG9Ac29sb2tleXMuY29tMCAXDTE4MTExMTEyNTE0MloYDzIwNjgxMDI5MTI1 -MTQyWjCBgDELMAkGA1UEBhMCVVMxETAPBgNVBAgMCE1hcnlsYW5kMRIwEAYDVQQK -DAlTb2xvIEtleXMxEDAOBgNVBAsMB1Jvb3QgQ0ExFTATBgNVBAMMDHNvbG9rZXlz -LmNvbTEhMB8GCSqGSIb3DQEJARYSaGVsbG9Ac29sb2tleXMuY29tMFkwEwYHKoZI -zj0CAQYIKoZIzj0DAQcDQgAEWHAN0CCJVZdMs0oktZ5m93uxmB1iyq8ELRLtqVFL -SOiHQEab56qRTB/QzrpGAY++Y2mw+vRuQMNhBiU0KzwjBjAKBggqhkjOPQQDAgNI -ADBFAiEAz9SlrAXIlEu87vra54rICPs+4b0qhp3PdzcTg7rvnP0CIGjxzlteQQx+ -jQGd7rwSZuE5RWUPVygYhUstQO9zNUOs ------END CERTIFICATE----- diff --git a/flask_demo/trusted_attestation_roots/yubico_u2f_device_attestation_ca.pem b/flask_demo/trusted_attestation_roots/yubico_u2f_device_attestation_ca.pem deleted file mode 100644 index 15a1dc2..0000000 --- a/flask_demo/trusted_attestation_roots/yubico_u2f_device_attestation_ca.pem +++ /dev/null @@ -1,19 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDHjCCAgagAwIBAgIEG0BT9zANBgkqhkiG9w0BAQsFADAuMSwwKgYDVQQDEyNZ -dWJpY28gVTJGIFJvb3QgQ0EgU2VyaWFsIDQ1NzIwMDYzMTAgFw0xNDA4MDEwMDAw -MDBaGA8yMDUwMDkwNDAwMDAwMFowLjEsMCoGA1UEAxMjWXViaWNvIFUyRiBSb290 -IENBIFNlcmlhbCA0NTcyMDA2MzEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK -AoIBAQC/jwYuhBVlqaiYWEMsrWFisgJ+PtM91eSrpI4TK7U53mwCIawSDHy8vUmk -5N2KAj9abvT9NP5SMS1hQi3usxoYGonXQgfO6ZXyUA9a+KAkqdFnBnlyugSeCOep -8EdZFfsaRFtMjkwz5Gcz2Py4vIYvCdMHPtwaz0bVuzneueIEz6TnQjE63Rdt2zbw -nebwTG5ZybeWSwbzy+BJ34ZHcUhPAY89yJQXuE0IzMZFcEBbPNRbWECRKgjq//qT -9nmDOFVlSRCt2wiqPSzluwn+v+suQEBsUjTGMEd25tKXXTkNW21wIWbxeSyUoTXw -LvGS6xlwQSgNpk2qXYwf8iXg7VWZAgMBAAGjQjBAMB0GA1UdDgQWBBQgIvz0bNGJ -hjgpToksyKpP9xv9oDAPBgNVHRMECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIBBjAN -BgkqhkiG9w0BAQsFAAOCAQEAjvjuOMDSa+JXFCLyBKsycXtBVZsJ4Ue3LbaEsPY4 -MYN/hIQ5ZM5p7EjfcnMG4CtYkNsfNHc0AhBLdq45rnT87q/6O3vUEtNMafbhU6kt -hX7Y+9XFN9NpmYxr+ekVY5xOxi8h9JDIgoMP4VB1uS0aunL1IGqrNooL9mmFnL2k -LVVee6/VR6C5+KSTCMCWppMuJIZII2v9o4dkoZ8Y7QRjQlLfYzd3qGtKbw7xaF1U -sG/5xUb/Btwb2X2g4InpiB/yt/3CpQXpiWX/K4mBvUKiGn05ZsqeY1gx4g0xLBqc -U9psmyPzK+Vsgw2jeRQ5JlKDyqE0hebfC1tvFu0CCrJFcw== ------END CERTIFICATE----- diff --git a/flask_demo/util.py b/flask_demo/util.py deleted file mode 100644 index 0eaa601..0000000 --- a/flask_demo/util.py +++ /dev/null @@ -1,68 +0,0 @@ -import random -import six -import string -import os -import base64 - -CHALLENGE_DEFAULT_BYTE_LEN = 32 -UKEY_DEFAULT_BYTE_LEN = 20 -USERNAME_MAX_LENGTH = 32 -DISPLAY_NAME_MAX_LENGTH = 65 - -def validate_username(username): - if not isinstance(username, six.string_types): - return False - - if len(username) > USERNAME_MAX_LENGTH: - return False - - if not username.isalnum(): - return False - - return True - - -def validate_display_name(display_name): - if not isinstance(display_name, six.string_types): - return False - - if len(display_name) > DISPLAY_NAME_MAX_LENGTH: - return False - - if not display_name.replace(' ', '').isalnum(): - return False - - return True - - -def generate_challenge(challenge_len=CHALLENGE_DEFAULT_BYTE_LEN): - '''Generate a challenge of challenge_len bytes, Base64-encoded. - We use URL-safe base64, but we *don't* strip the padding, so that - the browser can decode it without too much hassle. - Note that if we are doing byte comparisons with the challenge in collectedClientData - later on, that value will not have padding, so we must remove the padding - before storing the value in the session. - ''' - # If we know Python 3.6 or greater is available, we could replace this with one - # call to secrets.token_urlsafe - challenge_bytes = os.urandom(challenge_len) - challenge_base64 = base64.urlsafe_b64encode(challenge_bytes) - # Python 2/3 compatibility: b64encode returns bytes only in newer Python versions - if not isinstance(challenge_base64, str): - challenge_base64 = challenge_base64.decode('utf-8') - return challenge_base64 - - -def generate_ukey(): - '''Its value's id member is required, and contains an identifier - for the account, specified by the Relying Party. This is not meant - to be displayed to the user, but is used by the Relying Party to - control the number of credentials - an authenticator will never - contain more than one credential for a given Relying Party under - the same id. - - A unique identifier for the entity. For a relying party entity, - sets the RP ID. For a user account entity, this will be an - arbitrary string specified by the relying party. - ''' - return generate_challenge(UKEY_DEFAULT_BYTE_LEN) From 05e955e8a405f5913783b5b142efecaeb197a4ff Mon Sep 17 00:00:00 2001 From: Matthew Miller Date: Thu, 14 Oct 2021 13:35:17 -0700 Subject: [PATCH 02/33] Clear out tests --- tests/test_util.py | 26 ------- tests/test_webauthn.py | 161 ----------------------------------------- 2 files changed, 187 deletions(-) delete mode 100644 tests/test_util.py delete mode 100644 tests/test_webauthn.py diff --git a/tests/test_util.py b/tests/test_util.py deleted file mode 100644 index f6a908a..0000000 --- a/tests/test_util.py +++ /dev/null @@ -1,26 +0,0 @@ -import unittest -import base64 -from flask_demo import util -import binascii -from unittest.mock import patch -import sys - -class EncodingTests(unittest.TestCase): - def test_confirm_padded(self): - '''Ensure that generate_challenge correctly generates *padded* URL-safe base64. - If a 32-byte challenge is requested, it will always have a single padding character, - so we can trust that the decode will fail if padding is omitted.''' - challenge_padded = util.generate_challenge() - try: - base64.urlsafe_b64decode(challenge_padded) # expects padded challenge - except binascii.Error: - self.fail("generate_challenge didn't produced padded base64") - - def test_confirm_byte_length(self): - '''Ensure that generate_challenge produces values of the proper byte length.''' - challenge_padded = util.generate_challenge() - challenge_bytes = base64.urlsafe_b64decode(challenge_padded) - self.assertEqual(len(challenge_bytes), util.CHALLENGE_DEFAULT_BYTE_LEN) - -if __name__ == '__main__': - unittest.main() \ No newline at end of file diff --git a/tests/test_webauthn.py b/tests/test_webauthn.py deleted file mode 100644 index 7f237bf..0000000 --- a/tests/test_webauthn.py +++ /dev/null @@ -1,161 +0,0 @@ -import os -import unittest -import struct -from copy import copy - -import webauthn -from webauthn import const - -HERE = os.path.abspath(os.path.dirname(__file__)) -TRUST_ANCHOR_DIR = "{}/../webauthn/trusted_attestation_roots".format(HERE) - - -class WebAuthnES256Test(unittest.TestCase): - REGISTRATION_RESPONSE_TMPL = { - 'clientData': b'eyJ0eXBlIjogIndlYmF1dGhuLmNyZWF0ZSIsICJjbGllbnRFeHRlbnNpb25zIjoge30sICJjaGFsbGVuZ2UiOiAiYlB6cFgzaEhRdHNwOWV2eUtZa2FadFZjOVVOMDdQVWRKMjJ2WlVkRHA5NCIsICJvcmlnaW4iOiAiaHR0cHM6Ly93ZWJhdXRobi5pbyJ9', # noqa - 'attObj': b'o2NmbXRoZmlkby11MmZnYXR0U3RtdKJjc2lnWEgwRgIhAI1qbvWibQos_t3zsTU05IXw1Ek3SDApATok09uc4UBwAiEAv0fB_lgb5Ot3zJ691Vje6iQLAtLhJDiA8zDxaGjcE3hjeDVjgVkCUzCCAk8wggE3oAMCAQICBDxoKU0wDQYJKoZIhvcNAQELBQAwLjEsMCoGA1UEAxMjWXViaWNvIFUyRiBSb290IENBIFNlcmlhbCA0NTcyMDA2MzEwIBcNMTQwODAxMDAwMDAwWhgPMjA1MDA5MDQwMDAwMDBaMDExLzAtBgNVBAMMJll1YmljbyBVMkYgRUUgU2VyaWFsIDIzOTI1NzM0ODExMTE3OTAxMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEvd9nk9t3lMNQMXHtLE1FStlzZnUaSLql2fm1ajoggXlrTt8rzXuSehSTEPvEaEdv_FeSqX22L6Aoa8ajIAIOY6M7MDkwIgYJKwYBBAGCxAoCBBUxLjMuNi4xLjQuMS40MTQ4Mi4xLjUwEwYLKwYBBAGC5RwCAQEEBAMCBSAwDQYJKoZIhvcNAQELBQADggEBAKrADVEJfuwVpIazebzEg0D4Z9OXLs5qZ_ukcONgxkRZ8K04QtP_CB5x6olTlxsj-SXArQDCRzEYUgbws6kZKfuRt2a1P-EzUiqDWLjRILSr-3_o7yR7ZP_GpiFKwdm-czb94POoGD-TS1IYdfXj94mAr5cKWx4EKjh210uovu_pLdLjc8xkQciUrXzZpPR9rT2k_q9HkZhHU-NaCJzky-PTyDbq0KKnzqVhWtfkSBCGw3ezZkTS-5lrvOKbIa24lfeTgu7FST5OwTPCFn8HcfWZMXMSD_KNU-iBqJdAwTLPPDRoLLvPTl29weCAIh-HUpmBQd0UltcPOrA_LFvAf61oYXV0aERhdGFYwnSm6pITyZwvdLIkkrMgz0AmKpTBqVCgOX8pJQtghB7wQQAAAAAAAAAAAAAAAAAAAAAAAAAAAECKU1ppjl9gmhHWyDkgHsUvZmhr6oF3_lD3llzLE2SaOSgOGIsIuAQqgp8JQSUu3r_oOaP8RS44dlQjrH-ALfYtpAECAyYhWCAxnqAfESXOYjKUc2WACuXZ3ch0JHxV0VFrrTyjyjIHXCJYIFnx8H87L4bApR4M-hPcV-fHehEOeW-KCyd0H-WGY8s6' # noqa - } - ASSERTION_RESPONSE_TMPL = { - 'authData': b'dKbqkhPJnC90siSSsyDPQCYqlMGpUKA5fyklC2CEHvABAAACfQ', - 'clientData': b'eyJjaGFsbGVuZ2UiOiJlLWctblhhUnhNYWdFaXFUSlN5RDgyUnNFYzVpZl82anlmSkR5OGJOS2x3Iiwib3JpZ2luIjoiaHR0cHM6Ly93ZWJhdXRobi5pbyIsInR5cGUiOiJ3ZWJhdXRobi5nZXQifQ', # noqa - 'signature': b'304502204a76f05cd52a778cdd4df1565e0004e5cc1ead360419d0f5c3a0143bf37e7f15022100932b5c308a560cfe4f244214843075b904b3eda64e85d64662a81198c386cdde', # noqa - } - CRED_KEY = {'alg': -7, 'type': 'public-key'} - REGISTRATION_CHALLENGE = 'bPzpX3hHQtsp9evyKYkaZtVc9UN07PUdJ22vZUdDp94' - ASSERTION_CHALLENGE = 'e-g-nXaRxMagEiqTJSyD82RsEc5if_6jyfJDy8bNKlw' - RP_ID = "webauthn.io" - ORIGIN = "https://webauthn.io" - USER_NAME = 'testuser' - ICON_URL = "https://example.com/icon.png" - USER_DISPLAY_NAME = "A Test User" - USER_ID = b'\x80\xf1\xdc\xec\xb5\x18\xb1\xc8b\x05\x886\xbc\xdfJ\xdf' - RP_NAME = "Web Authentication" - - def setUp(self): - self.options = webauthn.WebAuthnMakeCredentialOptions( - self.REGISTRATION_CHALLENGE, - self.RP_NAME, - self.RP_ID, - self.USER_ID, - self.USER_NAME, - self.USER_DISPLAY_NAME, - self.ICON_URL - ) - - def get_assertion_response(self): - credential = self.test_validate_registration() - webauthn_user = webauthn.WebAuthnUser( - self.USER_ID, - self.USER_NAME, - self.USER_DISPLAY_NAME, - self.ICON_URL, - credential.credential_id.decode(), - credential.public_key, - credential.sign_count, - credential.rp_id - ) - - webauthn_assertion_response = webauthn.WebAuthnAssertionResponse( - webauthn_user, - copy(self.ASSERTION_RESPONSE_TMPL), - self.ASSERTION_CHALLENGE, - self.ORIGIN, - uv_required=False, - ) - - return webauthn_assertion_response - - def test_create_options(self): - registration_dict = self.options.registration_dict - self.assertEqual(registration_dict['challenge'], self.REGISTRATION_CHALLENGE) - self.assertTrue(self.CRED_KEY in registration_dict['pubKeyCredParams']) - - def test_validate_registration(self): - registration_response = webauthn.WebAuthnRegistrationResponse( - self.RP_ID, - self.ORIGIN, - copy(self.REGISTRATION_RESPONSE_TMPL), - self.REGISTRATION_CHALLENGE, - TRUST_ANCHOR_DIR, - True, - True, - uv_required=False, - none_attestation_permitted=True, - ) - - return registration_response.verify() - - def test_registration_invalid_user_verification(self): - registration_response = webauthn.WebAuthnRegistrationResponse( - self.RP_ID, - self.ORIGIN, - copy(self.REGISTRATION_RESPONSE_TMPL), - self.REGISTRATION_CHALLENGE, - TRUST_ANCHOR_DIR, - True, - True, - uv_required=True - ) - - with self.assertRaises(webauthn.webauthn.RegistrationRejectedException): - registration_response.verify() - - def test_validate_assertion(self): - webauthn_assertion_response = self.get_assertion_response() - webauthn_assertion_response.verify() - - def test_invalid_signature_fail_assertion(self): - def mess_up(response): - response = copy(response) - response['signature'] = b'00' + response['signature'][2:] - return response - - webauthn_assertion_response = self.get_assertion_response() - webauthn_assertion_response.assertion_response = mess_up( - webauthn_assertion_response.assertion_response) - - with self.assertRaises(webauthn.webauthn.AuthenticationRejectedException): - webauthn_assertion_response.verify() - - def test_no_user_presence_fail_assertion(self): - webauthn_assertion_response = self.get_assertion_response() - auth_data = webauthn.webauthn._webauthn_b64_decode( - webauthn_assertion_response.assertion_response['authData']) - flags = struct.unpack('!B', auth_data[32:33])[0] - flags = flags & ~const.USER_PRESENT - auth_data = auth_data[:32] + struct.pack('!B', flags) + auth_data[33:] - webauthn_assertion_response.assertion_response[ - 'authData'] = webauthn.webauthn._webauthn_b64_encode(auth_data) - - # TODO: This *should* fail because UP=0, but will fail anyway later on because - # the signature is invalid. We should use a custom Authenticator implementation to - # sign over an authenticator data statement with UP=0 and test against that so that - # the signature is valid. - with self.assertRaises(webauthn.webauthn.AuthenticationRejectedException): - webauthn_assertion_response.verify() - - -class WebAuthnRS256Test(WebAuthnES256Test): - REGISTRATION_RESPONSE_TMPL = { - 'clientData': b'ew0KCSJ0eXBlIiA6ICJ3ZWJhdXRobi5jcmVhdGUiLA0KCSJjaGFsbGVuZ2UiIDogIkJHN1RoNG40aU5VbU51UnFNakk4TlVoRmdjTlBXbXFQIiwNCgkib3JpZ2luIiA6ICJodHRwczovLzNmYWRmZDEzLm5ncm9rLmlvIiwNCgkidG9rZW5CaW5kaW5nIiA6IA0KCXsNCgkJInN0YXR1cyIgOiAic3VwcG9ydGVkIg0KCX0NCn0', # noqa - 'attObj': b'o2NmbXRkbm9uZWhhdXRoRGF0YVkBZ8-CnWXgcASczJuZcxGxAUOJ7xA1fHeCSAxHxXqSqlMsRQAAAABgKLAXsdRMArSzr82vyWuyACCgTbLFqUdf_NegYeOYWcLCYBXlUddoptLz2eQO5DHa4qQBAwM5AQAgWQEAyo6eM5iARhHve7LwTvbhxT39qHviHjC1tzauY5BFnqAqYsj6m5Hl6NdyGQEDI-NLrm9kGKlxGLoDUZLoQlUVL0W2oltsLPYtgKLpAoEf6QfQx51j86NZiRClNERVKsQ-CtceQl_ic7zvK7HTMQQM_yWtaYjGo9t2IDPVgrkVnoSzuz_N-9ylCgjCm23-sllb6XhgvpXj44TDpiZFOhJDhYQksuqTjA1s08eXrPDwvc1Bcq5N8lJIc3eva07vecuZB53ywY0oZRWZ58aV035jjjPd-Kxp5JGi3H03ErvnHJCVxv64d-ngx7WvnqwsEvGVG3nauadeGzYWuGkgsxddeSFDAQABZ2F0dFN0bXSg' # noqa - } - ASSERTION_RESPONSE_TMPL = { - 'authData': b'z4KdZeBwBJzMm5lzEbEBQ4nvEDV8d4JIDEfFepKqUywFAAAAAQ', - 'clientData': b'ew0KCSJ0eXBlIiA6ICJ3ZWJhdXRobi5nZXQiLA0KCSJjaGFsbGVuZ2UiIDogImJyS2xZNXFYTEx1bUdoYUdiSGxndlNUeUZJNEVIcnZQIiwNCgkib3JpZ2luIiA6ICJodHRwczovLzNmYWRmZDEzLm5ncm9rLmlvIiwNCgkidG9rZW5CaW5kaW5nIiA6IA0KCXsNCgkJInN0YXR1cyIgOiAic3VwcG9ydGVkIg0KCX0NCn0', # noqa - 'signature': b'65d05b43495d4babc0388e6d530d7b0d676b0c29ddab4dce2445ebd053cc77ce43acc6d820c0d8491a0bae7beb98de8751d7497e07e061b7d26f4e490cd64b8bcd0628e1f50848d12b43f17493c9baf02bd4250a92c5d095d85faf7152a5132cd5f27c8223e61e683885021678a5156a955970d574926c52eec63b3bd25a205c4b51cb15c34c92ddd25b0ad370de96423e4b3edf5876963392f2ac889953f166669b96d16f894ef88e347484ab3cc81bc2814fbaf4b13dd1d483038bc4fb1354d564bc5aa944139ce6408e9078eddb6abef3a8ef4a77bcf74296ffd14c66223131d905f81cd149e1b8979c1bd87a036fca68f166e0644539b180d44f82fd7ed7', # noqa - } - CRED_KEY = {'alg': -257, 'type': 'public-key'} - REGISTRATION_CHALLENGE = 'BG7Th4n4iNUmNuRqMjI8NUhFgcNPWmqP' - ASSERTION_CHALLENGE = 'brKlY5qXLLumGhaGbHlgvSTyFI4EHrvP' - RP_NAME = "Web Authentication" - RP_ID = "3fadfd13.ngrok.io" - ORIGIN = "https://3fadfd13.ngrok.io" - USER_NAME = "testuser" - USER_DISPLAY_NAME = "A Test User" - ICON_URL = "https://example.com/icon.png" - USER_ID = b'\x80\xf1\xdc\xec\xb5\x18\xb1\xc8b\x05\x886\xbc\xdfJ\xdf' - - -if __name__ == '__main__': - unittest.main() From 5cfd4cc202a946d7df25bfc438bef3ed42b73315 Mon Sep 17 00:00:00 2001 From: Matthew Miller Date: Thu, 14 Oct 2021 13:35:24 -0700 Subject: [PATCH 03/33] Rename tox.ini --- tox.ini => .flake8 | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tox.ini => .flake8 (100%) diff --git a/tox.ini b/.flake8 similarity index 100% rename from tox.ini rename to .flake8 From 35bb0c43e506db5df1cc2766323c56f2190b4e7a Mon Sep 17 00:00:00 2001 From: Matthew Miller Date: Thu, 14 Oct 2021 13:35:34 -0700 Subject: [PATCH 04/33] Tweak license date --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index c989345..dca67f4 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2017 Duo Security, Inc. All rights reserved. +Copyright (c) 2017-2021 Duo Security, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions From 39e70fca02f7e2e897e56b28cc4f9f13c6ee81d7 Mon Sep 17 00:00:00 2001 From: Matthew Miller Date: Thu, 14 Oct 2021 13:35:45 -0700 Subject: [PATCH 05/33] Ignore macOS files --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index ca32077..b07cd61 100644 --- a/.gitignore +++ b/.gitignore @@ -107,3 +107,4 @@ venv.bak/ # PyWebAuthn py_webauthn.env webauthn.db +.DS_Store From 91452882f8b3088800cb30dc87e28fb4e09ec0e9 Mon Sep 17 00:00:00 2001 From: Matthew Miller Date: Thu, 14 Oct 2021 13:35:51 -0700 Subject: [PATCH 06/33] Delete lib files --- webauthn/__init__.py | 6 - webauthn/const.py | 6 - .../solokeys_u2f_device_attestation_ca.pem | 13 - .../yubico_u2f_device_attestation_ca.pem | 19 - webauthn/webauthn.py | 1373 ----------------- 5 files changed, 1417 deletions(-) delete mode 100644 webauthn/const.py delete mode 100644 webauthn/trusted_attestation_roots/solokeys_u2f_device_attestation_ca.pem delete mode 100644 webauthn/trusted_attestation_roots/yubico_u2f_device_attestation_ca.pem delete mode 100644 webauthn/webauthn.py diff --git a/webauthn/__init__.py b/webauthn/__init__.py index 712a879..419aa28 100644 --- a/webauthn/__init__.py +++ b/webauthn/__init__.py @@ -1,9 +1,3 @@ # flake8: noqa -from .webauthn import WebAuthnAssertionOptions -from .webauthn import WebAuthnAssertionResponse -from .webauthn import WebAuthnCredential -from .webauthn import WebAuthnMakeCredentialOptions -from .webauthn import WebAuthnRegistrationResponse -from .webauthn import WebAuthnUser __version__ = '0.4.7' diff --git a/webauthn/const.py b/webauthn/const.py deleted file mode 100644 index b89e64c..0000000 --- a/webauthn/const.py +++ /dev/null @@ -1,6 +0,0 @@ -# Authenticator data flags. -# https://www.w3.org/TR/webauthn/#authenticator-data -USER_PRESENT = 1 << 0 -USER_VERIFIED = 1 << 2 -ATTESTATION_DATA_INCLUDED = 1 << 6 -EXTENSION_DATA_INCLUDED = 1 << 7 diff --git a/webauthn/trusted_attestation_roots/solokeys_u2f_device_attestation_ca.pem b/webauthn/trusted_attestation_roots/solokeys_u2f_device_attestation_ca.pem deleted file mode 100644 index 5343801..0000000 --- a/webauthn/trusted_attestation_roots/solokeys_u2f_device_attestation_ca.pem +++ /dev/null @@ -1,13 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIB9DCCAZoCCQDER2OSj/S+jDAKBggqhkjOPQQDAjCBgDELMAkGA1UEBhMCVVMx -ETAPBgNVBAgMCE1hcnlsYW5kMRIwEAYDVQQKDAlTb2xvIEtleXMxEDAOBgNVBAsM -B1Jvb3QgQ0ExFTATBgNVBAMMDHNvbG9rZXlzLmNvbTEhMB8GCSqGSIb3DQEJARYS -aGVsbG9Ac29sb2tleXMuY29tMCAXDTE4MTExMTEyNTE0MloYDzIwNjgxMDI5MTI1 -MTQyWjCBgDELMAkGA1UEBhMCVVMxETAPBgNVBAgMCE1hcnlsYW5kMRIwEAYDVQQK -DAlTb2xvIEtleXMxEDAOBgNVBAsMB1Jvb3QgQ0ExFTATBgNVBAMMDHNvbG9rZXlz -LmNvbTEhMB8GCSqGSIb3DQEJARYSaGVsbG9Ac29sb2tleXMuY29tMFkwEwYHKoZI -zj0CAQYIKoZIzj0DAQcDQgAEWHAN0CCJVZdMs0oktZ5m93uxmB1iyq8ELRLtqVFL -SOiHQEab56qRTB/QzrpGAY++Y2mw+vRuQMNhBiU0KzwjBjAKBggqhkjOPQQDAgNI -ADBFAiEAz9SlrAXIlEu87vra54rICPs+4b0qhp3PdzcTg7rvnP0CIGjxzlteQQx+ -jQGd7rwSZuE5RWUPVygYhUstQO9zNUOs ------END CERTIFICATE----- diff --git a/webauthn/trusted_attestation_roots/yubico_u2f_device_attestation_ca.pem b/webauthn/trusted_attestation_roots/yubico_u2f_device_attestation_ca.pem deleted file mode 100644 index 15a1dc2..0000000 --- a/webauthn/trusted_attestation_roots/yubico_u2f_device_attestation_ca.pem +++ /dev/null @@ -1,19 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDHjCCAgagAwIBAgIEG0BT9zANBgkqhkiG9w0BAQsFADAuMSwwKgYDVQQDEyNZ -dWJpY28gVTJGIFJvb3QgQ0EgU2VyaWFsIDQ1NzIwMDYzMTAgFw0xNDA4MDEwMDAw -MDBaGA8yMDUwMDkwNDAwMDAwMFowLjEsMCoGA1UEAxMjWXViaWNvIFUyRiBSb290 -IENBIFNlcmlhbCA0NTcyMDA2MzEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK -AoIBAQC/jwYuhBVlqaiYWEMsrWFisgJ+PtM91eSrpI4TK7U53mwCIawSDHy8vUmk -5N2KAj9abvT9NP5SMS1hQi3usxoYGonXQgfO6ZXyUA9a+KAkqdFnBnlyugSeCOep -8EdZFfsaRFtMjkwz5Gcz2Py4vIYvCdMHPtwaz0bVuzneueIEz6TnQjE63Rdt2zbw -nebwTG5ZybeWSwbzy+BJ34ZHcUhPAY89yJQXuE0IzMZFcEBbPNRbWECRKgjq//qT -9nmDOFVlSRCt2wiqPSzluwn+v+suQEBsUjTGMEd25tKXXTkNW21wIWbxeSyUoTXw -LvGS6xlwQSgNpk2qXYwf8iXg7VWZAgMBAAGjQjBAMB0GA1UdDgQWBBQgIvz0bNGJ -hjgpToksyKpP9xv9oDAPBgNVHRMECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIBBjAN -BgkqhkiG9w0BAQsFAAOCAQEAjvjuOMDSa+JXFCLyBKsycXtBVZsJ4Ue3LbaEsPY4 -MYN/hIQ5ZM5p7EjfcnMG4CtYkNsfNHc0AhBLdq45rnT87q/6O3vUEtNMafbhU6kt -hX7Y+9XFN9NpmYxr+ekVY5xOxi8h9JDIgoMP4VB1uS0aunL1IGqrNooL9mmFnL2k -LVVee6/VR6C5+KSTCMCWppMuJIZII2v9o4dkoZ8Y7QRjQlLfYzd3qGtKbw7xaF1U -sG/5xUb/Btwb2X2g4InpiB/yt/3CpQXpiWX/K4mBvUKiGn05ZsqeY1gx4g0xLBqc -U9psmyPzK+Vsgw2jeRQ5JlKDyqE0hebfC1tvFu0CCrJFcw== ------END CERTIFICATE----- diff --git a/webauthn/webauthn.py b/webauthn/webauthn.py deleted file mode 100644 index 3685fdc..0000000 --- a/webauthn/webauthn.py +++ /dev/null @@ -1,1373 +0,0 @@ -# -*- coding: utf-8 -*- - -from __future__ import print_function -from __future__ import absolute_import - -import base64 -import hashlib -import json -import os -import struct -import sys -import binascii -import codecs - -from builtins import bytes, int - -import cbor2 -import six - -from cryptography import x509 -from cryptography.exceptions import InvalidSignature -from cryptography.hazmat.backends import default_backend -from cryptography.hazmat.primitives import constant_time -from cryptography.hazmat.primitives.asymmetric.ec import ( - ECDSA, EllipticCurvePublicNumbers, SECP256R1) -from cryptography.hazmat.primitives.asymmetric.padding import (MGF1, PKCS1v15, - PSS) -from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicNumbers -from cryptography.hazmat.primitives.hashes import SHA256 -from cryptography.x509 import load_der_x509_certificate -from OpenSSL import crypto - -from . import const - -# Only supporting 'None', 'Basic', and 'Self Attestation' attestation types for now. -AT_BASIC = 'Basic' -AT_ECDAA = 'ECDAA' -AT_NONE = 'None' -AT_ATTESTATION_CA = 'AttCA' -AT_SELF_ATTESTATION = 'Self' - -SUPPORTED_ATTESTATION_TYPES = (AT_BASIC, AT_NONE, AT_SELF_ATTESTATION) - -AT_FMT_FIDO_U2F = 'fido-u2f' -AT_FMT_PACKED = 'packed' -AT_FMT_NONE = 'none' - -# Only supporting 'fido-u2f', 'packed', and 'none' attestation formats for now. -SUPPORTED_ATTESTATION_FORMATS = (AT_FMT_FIDO_U2F, AT_FMT_PACKED, AT_FMT_NONE) - -COSE_ALG_ES256 = -7 -COSE_ALG_PS256 = -37 -COSE_ALG_RS256 = -257 - -# Trust anchors (trusted attestation roots directory). -DEFAULT_TRUST_ANCHOR_DIR = 'trusted_attestation_roots' - -# Client data type. -TYPE_CREATE = 'webauthn.create' -TYPE_GET = 'webauthn.get' - -# Default client extensions -DEFAULT_CLIENT_EXTENSIONS = {'appid': None, 'loc': None} - -# Default authenticator extensions -DEFAULT_AUTHENTICATOR_EXTENSIONS = {} - - -class COSEKeyException(Exception): - pass - - -class AuthenticationRejectedException(Exception): - pass - - -class RegistrationRejectedException(Exception): - pass - - -class WebAuthnUserDataMissing(Exception): - pass - - -class WebAuthnMakeCredentialOptions(object): - - _attestation_forms = {'none', 'indirect', 'direct'} - _user_verification = {'required', 'preferred', 'discouraged'} - - def __init__(self, challenge, rp_name, rp_id, user_id, username, - display_name, icon_url, timeout=60000, attestation='direct', - user_verification=None): - self.challenge = challenge - self.rp_name = rp_name - self.rp_id = rp_id - self.user_id = user_id - self.username = username - self.display_name = display_name - self.icon_url = icon_url - self.timeout = timeout - - attestation = str(attestation).lower() - if attestation not in self._attestation_forms: - raise ValueError('Attestation must be a string and one of ' + - ', '.join(self._attestation_forms)) - self.attestation = attestation - - if user_verification is not None: - user_verification = str(user_verification).lower() - if user_verification not in self._user_verification: - raise ValueError('user_verification must be a string and one of ' + - ', '.join(self._user_verification)) - self.user_verification = user_verification - - @property - def registration_dict(self): - registration_dict = { - 'challenge': self.challenge, - 'rp': { - 'name': self.rp_name, - 'id': self.rp_id - }, - 'user': { - 'id': self.user_id, - 'name': self.username, - 'displayName': self.display_name - }, - 'pubKeyCredParams': [{ - 'alg': COSE_ALG_ES256, - 'type': 'public-key', - }, { - 'alg': COSE_ALG_RS256, - 'type': 'public-key', - }, { - 'alg': COSE_ALG_PS256, - 'type': 'public-key', - }], - 'timeout': self.timeout, - 'excludeCredentials': [], - # Relying Parties may use AttestationConveyancePreference to specify their - # preference regarding attestation conveyance during credential generation. - 'attestation': self.attestation, - 'extensions': { - # Include location information in attestation. - 'webauthn.loc': True - } - } - - if self.user_verification is not None: - registration_dict['authenticatorSelection'] = { - 'userVerification': self.user_verification - } - - if self.icon_url: - registration_dict['user']['icon'] = self.icon_url - - return registration_dict - - @property - def json(self): - return json.dumps(self.registration_dict) - - -class WebAuthnAssertionOptions(object): - def __init__(self, webauthn_user, challenge, timeout=60000, userVerification='discouraged'): - if isinstance(webauthn_user, list): - self.webauthn_users = webauthn_user - else: - self.webauthn_users = [webauthn_user] - self.challenge = challenge - self.timeout = timeout - self.userVerification = userVerification - - @property - def assertion_dict(self): - if not isinstance(self.webauthn_users, list) or len(self.webauthn_users) < 1: - raise AuthenticationRejectedException('Invalid user list.') - if len(set([u.rp_id for u in self.webauthn_users])) != 1: - raise AuthenticationRejectedException('Invalid (mutliple) RP IDs in user list.') - for user in self.webauthn_users: - if not isinstance(user, WebAuthnUser): - raise AuthenticationRejectedException('Invalid user type.') - if not user.credential_id: - raise AuthenticationRejectedException('Invalid credential ID.') - if not self.challenge: - raise AuthenticationRejectedException('Invalid challenge.') - - acceptable_credentials = [] - for user in self.webauthn_users: - acceptable_credentials.append({ - 'type': 'public-key', - 'id': user.credential_id, - 'transports': ['usb', 'nfc', 'ble', 'internal'], - }) - - assertion_dict = { - 'challenge': self.challenge, - 'allowCredentials': acceptable_credentials, - 'rpId': self.webauthn_users[0].rp_id, - 'timeout': self.timeout, - 'userVerification': self.userVerification, - # 'extensions': {} - } - - return assertion_dict - - @property - def json(self): - return json.dumps(self.assertion_dict) - - -class WebAuthnUser(object): - def __init__(self, user_id, username, display_name, icon_url, - credential_id, public_key, sign_count, rp_id): - - if not credential_id: - raise WebAuthnUserDataMissing("credential_id missing") - - if not rp_id: - raise WebAuthnUserDataMissing("rp_id missing") - - self.user_id = user_id - self.username = username - self.display_name = display_name - self.icon_url = icon_url - self.credential_id = credential_id - self.public_key = public_key - self.sign_count = sign_count - self.rp_id = rp_id - - def __str__(self): - return '{} ({}, {}, {})'.format(self.user_id, self.username, - self.display_name, self.sign_count) - - -class WebAuthnCredential(object): - def __init__(self, rp_id, origin, credential_id, public_key, sign_count): - self.rp_id = rp_id - self.origin = origin - self.credential_id = credential_id - self.public_key = public_key - self.sign_count = sign_count - - def __str__(self): - return '{} ({}, {}, {})'.format(self.credential_id, self.rp_id, - self.origin, self.sign_count) - - -class WebAuthnRegistrationResponse(object): - def __init__(self, - rp_id, - origin, - registration_response, - challenge, - trust_anchor_dir=DEFAULT_TRUST_ANCHOR_DIR, - trusted_attestation_cert_required=False, - self_attestation_permitted=False, - none_attestation_permitted=False, - uv_required=False, - expected_registration_client_extensions=DEFAULT_CLIENT_EXTENSIONS, - expected_registration_authenticator_extensions=DEFAULT_AUTHENTICATOR_EXTENSIONS): - self.rp_id = rp_id - self.origin = origin - self.registration_response = registration_response - self.challenge = challenge - self.trust_anchor_dir = trust_anchor_dir - self.trusted_attestation_cert_required = trusted_attestation_cert_required - self.uv_required = uv_required - self.expected_registration_client_extensions = expected_registration_client_extensions - self.expected_registration_authenticator_extensions = \ - expected_registration_authenticator_extensions - - # With self attestation, the credential public key is - # also used as the attestation public key. - self.self_attestation_permitted = self_attestation_permitted - - # `none` AttestationConveyancePreference - # Replace potentially uniquely identifying information - # (such as AAGUID and attestation certificates) in the - # attested credential data and attestation statement, - # respectively, with blinded versions of the same data. - # **Note**: If True, authenticator attestation will not - # be performed. - self.none_attestation_permitted = none_attestation_permitted - - def _verify_attestation_statement(self, fmt, att_stmt, auth_data, - client_data_hash): - '''Verification procedure: The procedure for verifying an attestation statement, - which takes the following verification procedure inputs: - - * attStmt: The attestation statement structure - * authenticatorData: The authenticator data claimed to have been used for - the attestation - * clientDataHash: The hash of the serialized client data - - The procedure returns either: - - * An error indicating that the attestation is invalid, or - * The attestation type, and the trust path. This attestation trust path is - either empty (in case of self attestation), an identifier of an ECDAA-Issuer - public key (in the case of ECDAA), or a set of X.509 certificates. - - TODO: - Verification of attestation objects requires that the Relying Party has a trusted - method of determining acceptable trust anchors in step 15 above. Also, if - certificates are being used, the Relying Party MUST have access to certificate - status information for the intermediate CA certificates. The Relying Party MUST - also be able to build the attestation certificate chain if the client did not - provide this chain in the attestation information. - ''' - - attestation_data = auth_data[37:] - aaguid = attestation_data[:16] - credential_id_len = struct.unpack('!H', attestation_data[16:18])[0] - cred_id = attestation_data[18:18 + credential_id_len] - credential_pub_key = attestation_data[18 + credential_id_len:] - - if fmt == AT_FMT_FIDO_U2F: - # Step 1. - # - # Verify that attStmt is valid CBOR conforming to the syntax - # defined above and perform CBOR decoding on it to extract the - # contained fields. - if 'x5c' not in att_stmt or 'sig' not in att_stmt: - raise RegistrationRejectedException( - 'Attestation statement must be a valid CBOR object.') - - # Step 2. - # - # Let attCert be the value of the first element of x5c. Let certificate - # public key be the public key conveyed by attCert. If certificate public - # key is not an Elliptic Curve (EC) public key over the P-256 curve, - # terminate this algorithm and return an appropriate error. - att_cert = att_stmt.get('x5c')[0] - x509_att_cert = load_der_x509_certificate(att_cert, - default_backend()) - certificate_public_key = x509_att_cert.public_key() - if not isinstance(certificate_public_key.curve, SECP256R1): - raise RegistrationRejectedException( - 'Bad certificate public key.') - - # Step 3. - # - # Extract the claimed rpIdHash from authenticatorData, and the - # claimed credentialId and credentialPublicKey from - # authenticatorData.attestedCredentialData. - - # The credential public key encoded in COSE_Key format, as defined in Section 7 - # of [RFC8152], using the CTAP2 canonical CBOR encoding form. The COSE_Key-encoded - # credential public key MUST contain the optional "alg" parameter and MUST NOT - # contain any other optional parameters. The "alg" parameter MUST contain a - # COSEAlgorithmIdentifier value. The encoded credential public key MUST also - # contain any additional required parameters stipulated by the relevant key type - # specification, i.e., required for the key type "kty" and algorithm "alg" (see - # Section 8 of [RFC8152]). - try: - public_key_alg, credential_public_key = _load_cose_public_key( - credential_pub_key) - except COSEKeyException as e: - raise RegistrationRejectedException(str(e)) - - public_key_u2f = _encode_public_key(credential_public_key) - - # Step 5. - # - # Let verificationData be the concatenation of (0x00 || rpIdHash || - # clientDataHash || credentialId || publicKeyU2F) (see Section 4.3 - # of [FIDO-U2F-Message-Formats]). - auth_data_rp_id_hash = _get_auth_data_rp_id_hash(auth_data) - alg = COSE_ALG_ES256 - signature = att_stmt['sig'] - verification_data = b''.join([ - b'\0', auth_data_rp_id_hash, client_data_hash, cred_id, - public_key_u2f - ]) - - # Step 6. - # - # Verify the sig using verificationData and certificate public - # key per [SEC1]. - try: - _verify_signature(certificate_public_key, alg, - verification_data, signature) - except InvalidSignature: - raise RegistrationRejectedException( - 'Invalid signature received.') - except NotImplementedError: - raise RegistrationRejectedException('Unsupported algorithm.') - - # Step 7. - # - # If successful, return attestation type Basic with the - # attestation trust path set to x5c. - attestation_type = AT_BASIC - trust_path = [x509_att_cert] - - return (attestation_type, trust_path, credential_pub_key, cred_id) - elif fmt == AT_FMT_PACKED: - attestation_syntaxes = { - AT_BASIC: set(['alg', 'x5c', 'sig']), - AT_ECDAA: set(['alg', 'sig', 'ecdaaKeyId']), - AT_SELF_ATTESTATION: set(['alg', 'sig']) - } - - # Step 1. - # - # Verify that attStmt is valid CBOR conforming to the syntax - # defined above and perform CBOR decoding on it to extract the - # contained fields. - if set(att_stmt.keys()) not in attestation_syntaxes.values(): - raise RegistrationRejectedException( - 'Attestation statement must be a valid CBOR object.') - - alg = att_stmt['alg'] - signature = att_stmt['sig'] - verification_data = b''.join([auth_data, client_data_hash]) - - if 'x5c' in att_stmt: - # Step 2. - # - # If x5c is present, this indicates that the attestation - # type is not ECDAA. In this case: - att_cert = att_stmt['x5c'][0] - x509_att_cert = load_der_x509_certificate( - att_cert, default_backend()) - certificate_public_key = x509_att_cert.public_key() - - # * Verify that sig is a valid signature over the - # concatenation of authenticatorData and clientDataHash - # using the attestation public key in attestnCert with - # the algorithm specified in alg. - try: - _verify_signature(certificate_public_key, alg, - verification_data, signature) - except InvalidSignature: - raise RegistrationRejectedException( - 'Invalid signature received.') - except NotImplementedError: - raise RegistrationRejectedException( - 'Unsupported algorithm.') - - # * Verify that attestnCert meets the requirements in - # §8.2.1 Packed attestation statement certificate - # requirements. - - # The attestation certificate MUST have the following - # fields/extensions: - # * Version MUST be set to 3 (which is indicated by an - # ASN.1 INTEGER with value 2). - if x509_att_cert.version != x509.Version.v3: - raise RegistrationRejectedException( - 'Invalid attestation certificate version.') - - # * Subject field MUST be set to: - subject = x509_att_cert.subject - COUNTRY_NAME = x509.NameOID.COUNTRY_NAME - ORGANIZATION_NAME = x509.NameOID.ORGANIZATION_NAME - ORG_UNIT_NAME = x509.NameOID.ORGANIZATIONAL_UNIT_NAME - COMMON_NAME = x509.NameOID.COMMON_NAME - - # * Subject-C: ISO 3166 code specifying the country - # where the Authenticator vendor is - # incorporated - if not subject.get_attributes_for_oid(COUNTRY_NAME): - raise RegistrationRejectedException( - 'Attestation certificate must have subject-C.') - - # * Subject-O: Legal name of the Authenticator vendor - if not subject.get_attributes_for_oid(ORGANIZATION_NAME): - raise RegistrationRejectedException( - 'Attestation certificate must have subject-O.') - - # * Subject-OU: Literal string - # “Authenticator Attestation” - ou = subject.get_attributes_for_oid(ORG_UNIT_NAME) - if not ou or ou[0].value != 'Authenticator Attestation': - raise RegistrationRejectedException( - "Attestation certificate must have subject-OU set to " - "'Authenticator Attestation'.") - - # * Subject-CN: A UTF8String of the vendor’s choosing - if not subject.get_attributes_for_oid(COMMON_NAME): - raise RegistrationRejectedException( - 'Attestation certificate must have subject-CN.') - - extensions = x509_att_cert.extensions - - # * If the related attestation root certificate is used - # for multiple authenticator models, the Extension OID - # 1.3.6.1.4.1.45724.1.1.4 (id-fido-gen-ce-aaguid) MUST - # be present, containing the AAGUID as a 16-byte OCTET - # STRING. The extension MUST NOT be marked as critical. - try: - oid = x509.ObjectIdentifier('1.3.6.1.4.1.45724.1.1.4') - aaguid_ext = extensions.get_extension_for_oid(oid) - if aaguid_ext.value.value[2:] != aaguid: - raise RegistrationRejectedException( - 'Attestation certificate AAGUID must match ' - 'authenticator data.') - if aaguid_ext.critical: - raise RegistrationRejectedException( - "Attestation certificate's " - "'id-fido-gen-ce-aaguid' extension must not be " - "marked critical.") - except x509.ExtensionNotFound: - pass # Optional extension - - # * The Basic Constraints extension MUST have the CA - # component set to false. - bc_extension = extensions.get_extension_for_class( - x509.BasicConstraints) - if not bc_extension or bc_extension.value.ca: - raise RegistrationRejectedException( - 'Attestation certificate must have Basic Constraints ' - 'extension with CA=false.') - - # * If successful, return attestation type Basic and - # attestation trust path x5c. - attestation_type = AT_BASIC - trust_path = [x509_att_cert] - elif 'ecdaaKeyId' in att_stmt: - # Step 3. - # - # If ecdaaKeyId is present, then the attestation type is - # ECDAA. In this case: - # * Verify that sig is a valid signature over the - # concatenation of authenticatorData and clientDataHash - # using ECDAA-Verify with ECDAA-Issuer public key - # identified by ecdaaKeyId (see [FIDOEcdaaAlgorithm]). - # * If successful, return attestation type ECDAA and - # attestation trust path ecdaaKeyId. - raise RegistrationRejectedException( - 'ECDAA attestation type is not currently supported.') - else: - # Step 4. - # - # If neither x5c nor ecdaaKeyId is present, self - # attestation is in use. - # * Validate that alg matches the algorithm of the - # credentialPublicKey in authenticatorData. - try: - public_key_alg, credential_public_key = _load_cose_public_key( - credential_pub_key) - except COSEKeyException as e: - raise RegistrationRejectedException(str(e)) - - if public_key_alg != alg: - raise RegistrationRejectedException( - 'Public key algorithm does not match.') - - # * Verify that sig is a valid signature over the - # concatenation of authenticatorData and clientDataHash - # using the credential public key with alg. - try: - _verify_signature(credential_public_key, alg, - verification_data, signature) - except InvalidSignature: - raise RegistrationRejectedException( - 'Invalid signature received.') - except NotImplementedError: - raise RegistrationRejectedException( - 'Unsupported algorithm.') - - # * If successful, return attestation type Self and empty - # attestation trust path. - attestation_type = AT_SELF_ATTESTATION - trust_path = [] - - return (attestation_type, trust_path, credential_pub_key, cred_id) - elif fmt == AT_FMT_NONE: - # `none` - indicates that the Relying Party is not interested in - # authenticator attestation. - if not self.none_attestation_permitted: - raise RegistrationRejectedException( - 'Authenticator attestation is required.') - - # Step 1. - # - # Return attestation type None with an empty trust path. - attestation_type = AT_NONE - trust_path = [] - return (attestation_type, trust_path, credential_pub_key, cred_id) - else: - raise RegistrationRejectedException('Invalid format.') - - def verify(self): - try: - # Step 1. - # - # Let JSONtext be the result of running UTF-8 decode on the value of - # response.clientDataJSON. - - json_text = self.registration_response.get('clientData', '') - if sys.version_info < (3, 0): # if python2 - json_text = json_text.decode('utf-8') - - # Step 2. - # - # Let C, the client data claimed as collected during the credential - # creation, be the result of running an implementation-specific JSON - # parser on JSONtext. - decoded_cd = _webauthn_b64_decode(json_text) - - if sys.version_info < (3, 6): # if json.loads doesn't support bytes - c = json.loads(decoded_cd.decode('utf-8')) - else: - c = json.loads(decoded_cd) - - attestation_object = self.registration_response.get('attObj') - - # Step 3. - # - # Verify that the value of C.type is webauthn.create. - received_type = c.get('type') - if not _verify_type(received_type, TYPE_CREATE): - raise RegistrationRejectedException('Invalid type.') - - # Step 4. - # - # Verify that the value of C.challenge matches the challenge that was sent - # to the authenticator in the create() call. - received_challenge = c.get('challenge') - if not _verify_challenge(received_challenge, self.challenge): - raise RegistrationRejectedException( - 'Unable to verify challenge.') - - # Step 5. - # - # Verify that the value of C.origin matches the Relying Party's origin. - if not _verify_origin(c, self.origin): - raise RegistrationRejectedException('Unable to verify origin.') - - # Step 6. - # - # Verify that the value of C.tokenBinding.status matches the state of - # Token Binding for the TLS connection over which the assertion was - # obtained. If Token Binding was used on that TLS connection, also verify - # that C.tokenBinding.id matches the base64url encoding of the Token - # Binding ID for the connection. - - # XXX: Chrome does not currently supply token binding in the clientDataJSON - # if not _verify_token_binding_id(c): - # raise RegistrationRejectedException('Unable to verify token binding ID.') - - # Step 7. - # - # Compute the hash of response.clientDataJSON using SHA-256. - client_data_hash = _get_client_data_hash(decoded_cd) - - # Step 8. - # - # Perform CBOR decoding on the attestationObject field of - # the AuthenticatorAttestationResponse structure to obtain - # the attestation statement format fmt, the authenticator - # data authData, and the attestation statement attStmt. - att_obj = cbor2.loads(_webauthn_b64_decode(attestation_object)) - att_stmt = att_obj.get('attStmt') - auth_data = att_obj.get('authData') - fmt = att_obj.get('fmt') - if not auth_data or len(auth_data) < 37: - raise RegistrationRejectedException( - 'Auth data must be at least 37 bytes.') - - # Step 9. - # - # Verify that the RP ID hash in authData is indeed the - # SHA-256 hash of the RP ID expected by the RP. - auth_data_rp_id_hash = _get_auth_data_rp_id_hash(auth_data) - # NOTE: In Python 3, `auth_data_rp_id_hash` will be bytes, - # which is expected in `_verify_rp_id_hash()`. - if not _verify_rp_id_hash(auth_data_rp_id_hash, self.rp_id): - raise RegistrationRejectedException( - 'Unable to verify RP ID hash.') - - # Step 10. - # - # Verify that the User Present bit of the flags in authData - # is set. - - # Authenticator data flags. - # https://www.w3.org/TR/webauthn/#authenticator-data - flags = struct.unpack('!B', auth_data[32:33])[0] - - if (flags & const.USER_PRESENT) != 0x01: - raise RegistrationRejectedException( - 'Malformed request received.') - - # Step 11. - # - # If user verification is required for this registration, verify - # that the User Verified bit of the flags in authData is set. - if (self.uv_required and (flags & const.USER_VERIFIED) != 0x04): - raise RegistrationRejectedException( - 'Malformed request received.') - - # Step 12. - # - # Verify that the values of the client extension outputs in - # clientExtensionResults and the authenticator extension outputs - # in the extensions in authData are as expected, considering the - # client extension input values that were given as the extensions - # option in the create() call. In particular, any extension - # identifier values in the clientExtensionResults and the extensions - # in authData MUST be also be present as extension identifier values - # in the extensions member of options, i.e., no extensions are - # present that were not requested. In the general case, the meaning - # of "are as expected" is specific to the Relying Party and which - # extensions are in use. - registration_client_extensions = self.registration_response.get( - 'registrationClientExtensions') - if registration_client_extensions: - rce = json.loads(registration_client_extensions) - if not _verify_client_extensions(rce, self.expected_registration_client_extensions): - raise RegistrationRejectedException( - 'Unable to verify client extensions.') - if not _verify_authenticator_extensions( - c, self.expected_registration_authenticator_extensions): - raise RegistrationRejectedException( - 'Unable to verify authenticator extensions.') - - # Step 13. - # - # Determine the attestation statement format by performing - # a USASCII case-sensitive match on fmt against the set of - # supported WebAuthn Attestation Statement Format Identifier - # values. The up-to-date list of registered WebAuthn - # Attestation Statement Format Identifier values is maintained - # in the in the IANA registry of the same name - # [WebAuthn-Registries]. - if not _verify_attestation_statement_format(fmt): - raise RegistrationRejectedException( - 'Unable to verify attestation statement format.') - - # Step 14. - # - # Verify that attStmt is a correct attestation statement, conveying - # a valid attestation signature, by using the attestation statement - # format fmt's verification procedure given attStmt, authData and - # the hash of the serialized client data computed in step 7. - (attestation_type, trust_path, credential_public_key, - cred_id) = self._verify_attestation_statement( - fmt, att_stmt, auth_data, client_data_hash) - - # Step 15. - # - # If validation is successful, obtain a list of acceptable trust - # anchors (attestation root certificates or ECDAA-Issuer public - # keys) for that attestation type and attestation statement format - # fmt, from a trusted source or from policy. For example, the FIDO - # Metadata Service [FIDOMetadataService] provides one way to obtain - # such information, using the aaguid in the attestedCredentialData - # in authData. - trust_anchors = _get_trust_anchors(attestation_type, fmt, - self.trust_anchor_dir) - if not trust_anchors and self.trusted_attestation_cert_required: - raise RegistrationRejectedException( - 'No trust anchors available to verify attestation certificate.' - ) - - # Step 16. - # - # Assess the attestation trustworthiness using the outputs of the - # verification procedure in step 14, as follows: - # - # * If self attestation was used, check if self attestation is - # acceptable under Relying Party policy. - # * If ECDAA was used, verify that the identifier of the - # ECDAA-Issuer public key used is included in the set of - # acceptable trust anchors obtained in step 15. - # * Otherwise, use the X.509 certificates returned by the - # verification procedure to verify that the attestation - # public key correctly chains up to an acceptable root - # certificate. - if attestation_type == AT_SELF_ATTESTATION: - if not self.self_attestation_permitted: - raise RegistrationRejectedException( - 'Self attestation is not permitted.') - elif attestation_type == AT_ATTESTATION_CA: - raise NotImplementedError( - 'Attestation CA attestation type is not currently supported.' - ) - elif attestation_type == AT_ECDAA: - raise NotImplementedError( - 'ECDAA attestation type is not currently supported.') - elif attestation_type == AT_BASIC: - if self.trusted_attestation_cert_required: - if not _is_trusted_attestation_cert( - trust_path, trust_anchors): - raise RegistrationRejectedException( - 'Untrusted attestation certificate.') - elif attestation_type == AT_NONE: - pass - else: - raise RegistrationRejectedException( - 'Unknown attestation type.') - - # Step 17. - # - # Check that the credentialId is not yet registered to any other user. - # If registration is requested for a credential that is already registered - # to a different user, the Relying Party SHOULD fail this registration - # ceremony, or it MAY decide to accept the registration, e.g. while deleting - # the older registration. - # - # NOTE: This needs to be done by the Relying Party by checking the - # `credential_id` property of `WebAuthnCredential` against their - # database. See `flask_demo/app.py`. - - # Step 18. - # - # If the attestation statement attStmt verified successfully and is - # found to be trustworthy, then register the new credential with the - # account that was denoted in the options.user passed to create(), - # by associating it with the credentialId and credentialPublicKey in - # the attestedCredentialData in authData, as appropriate for the - # Relying Party's system. - - # Step 19. - # - # If the attestation statement attStmt successfully verified but is - # not trustworthy per step 16 above, the Relying Party SHOULD fail - # the registration ceremony. - # - # NOTE: However, if permitted by policy, the Relying Party MAY - # register the credential ID and credential public key but - # treat the credential as one with self attestation (see - # 6.3.3 Attestation Types). If doing so, the Relying Party - # is asserting there is no cryptographic proof that the - # public key credential has been generated by a particular - # authenticator model. See [FIDOSecRef] and [UAFProtocol] - # for a more detailed discussion. - - sc = auth_data[33:37] - sign_count = struct.unpack('!I', sc)[0] - - credential = WebAuthnCredential( - self.rp_id, self.origin, _webauthn_b64_encode(cred_id), - _webauthn_b64_encode(credential_public_key), sign_count) - - return credential - - except Exception as e: - raise RegistrationRejectedException( - 'Registration rejected. Error: {}.'.format(e)) - - -class WebAuthnAssertionResponse(object): - def __init__(self, - webauthn_user, - assertion_response, - challenge, - origin, - allow_credentials=None, - uv_required=False, - expected_assertion_client_extensions=DEFAULT_CLIENT_EXTENSIONS, - expected_assertion_authenticator_extensions=DEFAULT_AUTHENTICATOR_EXTENSIONS): - self.webauthn_user = webauthn_user - self.assertion_response = assertion_response - self.challenge = challenge - self.origin = origin - self.allow_credentials = allow_credentials - self.uv_required = uv_required - self.expected_assertion_client_extensions = expected_assertion_client_extensions - self.expected_assertion_authenticator_extensions = \ - expected_assertion_authenticator_extensions - - def verify(self): - try: - # Step 1. - # - # If the allowCredentials option was given when this authentication - # ceremony was initiated, verify that credential.id identifies one - # of the public key credentials that were listed in allowCredentials. - cid = self.assertion_response.get('id') - if self.allow_credentials: - if cid not in self.allow_credentials: - raise AuthenticationRejectedException( - 'Invalid credential.') - - # Step 2. - # - # If credential.response.userHandle is present, verify that the user - # identified by this value is the owner of the public key credential - # identified by credential.id. - if not self.webauthn_user.username: - raise WebAuthnUserDataMissing("username missing") - - user_handle = self.assertion_response.get('userHandle') - if user_handle: - if not user_handle == self.webauthn_user.username: - raise AuthenticationRejectedException( - 'Invalid credential.') - - # Step 3. - # - # Using credential's id attribute (or the corresponding rawId, if - # base64url encoding is inappropriate for your use case), look up - # the corresponding credential public key. - if not _validate_credential_id(self.webauthn_user.credential_id): - raise AuthenticationRejectedException('Invalid credential ID.') - - if not isinstance(self.webauthn_user, WebAuthnUser): - raise AuthenticationRejectedException('Invalid user type.') - - if not self.webauthn_user.public_key: - raise WebAuthnUserDataMissing("public_key missing") - - credential_public_key = self.webauthn_user.public_key - public_key_alg, user_pubkey = _load_cose_public_key( - _webauthn_b64_decode(credential_public_key)) - - # Step 4. - # - # Let cData, aData and sig denote the value of credential's - # response's clientDataJSON, authenticatorData, and signature - # respectively. - c_data = self.assertion_response.get('clientData') - a_data = self.assertion_response.get('authData') - decoded_a_data = _webauthn_b64_decode(a_data) - sig = binascii.unhexlify(self.assertion_response.get('signature')) - - # Step 5. - # - # Let JSONtext be the result of running UTF-8 decode on the - # value of cData. - if sys.version_info < (3, 0): # if python2 - json_text = c_data.decode('utf-8') - else: - json_text = c_data - - # Step 6. - # - # Let C, the client data claimed as used for the signature, - # be the result of running an implementation-specific JSON - # parser on JSONtext. - decoded_cd = _webauthn_b64_decode(json_text) - - if sys.version_info < (3, 6): # if json.loads doesn't support bytes - c = json.loads(decoded_cd.decode('utf-8')) - else: - c = json.loads(decoded_cd) - - # Step 7. - # - # Verify that the value of C.type is the string webauthn.get. - received_type = c.get('type') - if not _verify_type(received_type, TYPE_GET): - raise RegistrationRejectedException('Invalid type.') - - # Step 8. - # - # Verify that the value of C.challenge matches the challenge - # that was sent to the authenticator in the - # PublicKeyCredentialRequestOptions passed to the get() call. - received_challenge = c.get('challenge') - if not _verify_challenge(received_challenge, self.challenge): - raise AuthenticationRejectedException( - 'Unable to verify challenge.') - - # Step 9. - # - # Verify that the value of C.origin matches the Relying - # Party's origin. - if not _verify_origin(c, self.origin): - raise AuthenticationRejectedException( - 'Unable to verify origin.') - - # Step 10. - # - # Verify that the value of C.tokenBinding.status matches - # the state of Token Binding for the TLS connection over - # which the attestation was obtained. If Token Binding was - # used on that TLS connection, also verify that - # C.tokenBinding.id matches the base64url encoding of the - # Token Binding ID for the connection. - - # XXX: Chrome does not currently supply token binding in the clientDataJSON - # if not _verify_token_binding_id(c): - # raise AuthenticationRejectedException('Unable to verify token binding ID.') - - # Step 11. - # - # Verify that the rpIdHash in aData is the SHA-256 hash of - # the RP ID expected by the Relying Party. - auth_data_rp_id_hash = _get_auth_data_rp_id_hash(decoded_a_data) - if not _verify_rp_id_hash(auth_data_rp_id_hash, - self.webauthn_user.rp_id): - raise AuthenticationRejectedException( - 'Unable to verify RP ID hash.') - - # Step 12. - # - # Verify that the User Present bit of the flags in authData - # is set. - - # Authenticator data flags. - # https://www.w3.org/TR/webauthn/#authenticator-data - flags = struct.unpack('!B', decoded_a_data[32:33])[0] - - if (flags & const.USER_PRESENT) != 0x01: - raise AuthenticationRejectedException( - 'Malformed request received.') - - # Step 13. - # - # If user verification is required for this assertion, verify that - # the User Verified bit of the flags in authData is set. - if (self.uv_required and (flags & const.USER_VERIFIED) != 0x04): - raise RegistrationRejectedException( - 'Malformed request received.') - - # Step 14. - # - # Verify that the values of the client extension outputs in - # clientExtensionResults and the authenticator extension outputs - # in the extensions in authData are as expected, considering the - # client extension input values that were given as the extensions - # option in the get() call. In particular, any extension identifier - # values in the clientExtensionResults and the extensions in - # authData MUST be also be present as extension identifier values - # in the extensions member of options, i.e., no extensions are - # present that were not requested. In the general case, the meaning - # of "are as expected" is specific to the Relying Party and which - # extensions are in use. - assertion_client_extensions = self.assertion_response.get( - 'assertionClientExtensions') - if assertion_client_extensions: - ace = json.loads(assertion_client_extensions) - if not _verify_client_extensions(ace, self.expected_assertion_client_extensions): - raise AuthenticationRejectedException( - 'Unable to verify client extensions.') - if not _verify_authenticator_extensions( - c, self.expected_assertion_authenticator_extensions): - raise AuthenticationRejectedException( - 'Unable to verify authenticator extensions.') - - # Step 15. - # - # Let hash be the result of computing a hash over the cData - # using SHA-256. - client_data_hash = _get_client_data_hash(decoded_cd) - - # Step 16. - # - # Using the credential public key looked up in step 3, verify - # that sig is a valid signature over the binary concatenation - # of aData and hash. - bytes_to_verify = b''.join([decoded_a_data, client_data_hash]) - - try: - _verify_signature(user_pubkey, public_key_alg, bytes_to_verify, - sig) - except InvalidSignature: - raise AuthenticationRejectedException( - 'Invalid signature received.') - except NotImplementedError: - raise AuthenticationRejectedException('Unsupported algorithm.') - - # Step 17. - # - # If the signature counter value adata.signCount is nonzero or - # the value stored in conjunction with credential's id attribute - # is nonzero, then run the following sub-step: - # If the signature counter value adata.signCount is - # greater than the signature counter value stored in - # conjunction with credential's id attribute. - # Update the stored signature counter value, - # associated with credential's id attribute, - # to be the value of adata.signCount. - # less than or equal to the signature counter value - # stored in conjunction with credential's id attribute. - # This is a signal that the authenticator may be - # cloned, i.e. at least two copies of the credential - # private key may exist and are being used in parallel. - # Relying Parties should incorporate this information - # into their risk scoring. Whether the Relying Party - # updates the stored signature counter value in this - # case, or not, or fails the authentication ceremony - # or not, is Relying Party-specific. - sc = decoded_a_data[33:37] - sign_count = struct.unpack('!I', sc)[0] - - if sign_count == 0 and self.webauthn_user.sign_count == 0: - return 0 - - if not sign_count: - raise AuthenticationRejectedException('Unable to parse sign_count.') - - if (isinstance(self.webauthn_user.sign_count, int) and - self.webauthn_user.sign_count < 0) or not isinstance( - self.webauthn_user.sign_count, int): - raise WebAuthnUserDataMissing('sign_count missing from WebAuthnUser.') - - if sign_count <= self.webauthn_user.sign_count: - raise AuthenticationRejectedException( - 'Duplicate authentication detected.') - - # Step 18. - # - # If all the above steps are successful, continue with the - # authentication ceremony as appropriate. Otherwise, fail the - # authentication ceremony. - return sign_count - - except Exception as e: - raise AuthenticationRejectedException( - 'Authentication rejected. Error: {}.'.format(e)) - - -def _encode_public_key(public_key): - '''Extracts the x, y coordinates from a public point on a Cryptography elliptic - curve, packs them into a standard byte string representation, and returns - them - :param public_key: an EllipticCurvePublicKey object - :return: a 65-byte string. decode_public_key().public_key() can invert this - function. - ''' - numbers = public_key.public_numbers() - return b'\x04' + binascii.unhexlify('{:064x}{:064x}'.format( - numbers.x, numbers.y)) - - -def _load_cose_public_key(key_bytes): - ALG_KEY = 3 - - cose_public_key = cbor2.loads(key_bytes) - - if ALG_KEY not in cose_public_key: - raise COSEKeyException( - 'Public key missing required algorithm parameter.') - - alg = cose_public_key[ALG_KEY] - - if alg == COSE_ALG_ES256: - X_KEY = -2 - Y_KEY = -3 - - required_keys = {ALG_KEY, X_KEY, Y_KEY} - - if not set(cose_public_key.keys()).issuperset(required_keys): - raise COSEKeyException('Public key must match COSE_Key spec.') - - if len(cose_public_key[X_KEY]) != 32: - raise RegistrationRejectedException('Bad public key.') - x = int(codecs.encode(cose_public_key[X_KEY], 'hex'), 16) - - if len(cose_public_key[Y_KEY]) != 32: - raise RegistrationRejectedException('Bad public key.') - y = int(codecs.encode(cose_public_key[Y_KEY], 'hex'), 16) - - return alg, EllipticCurvePublicNumbers( - x, y, SECP256R1()).public_key(backend=default_backend()) - elif alg in (COSE_ALG_PS256, COSE_ALG_RS256): - E_KEY = -2 - N_KEY = -1 - - required_keys = {ALG_KEY, E_KEY, N_KEY} - - if not set(cose_public_key.keys()).issuperset(required_keys): - raise COSEKeyException('Public key must match COSE_Key spec.') - - if len(cose_public_key[E_KEY]) != 3 or len(cose_public_key[N_KEY]) != 256: - raise COSEKeyException('Bad public key.') - - e = int(codecs.encode(cose_public_key[E_KEY], 'hex'), 16) - n = int(codecs.encode(cose_public_key[N_KEY], 'hex'), 16) - - return alg, RSAPublicNumbers(e, - n).public_key(backend=default_backend()) - else: - raise COSEKeyException('Unsupported algorithm.') - - -def _webauthn_b64_decode(encoded): - '''WebAuthn specifies web-safe base64 encoding *without* padding. - Python implementation requires padding. We'll add it and then - decode''' - if sys.version_info < (3, 0): # if python2 - # Ensure that this is encoded as ascii, not unicode. - encoded = encoded.encode('ascii') - else: - if isinstance(encoded, bytes): - encoded = str(encoded, 'utf-8') - # Add '=' until length is a multiple of 4 bytes, then decode. - padding_len = (-len(encoded) % 4) - encoded += '=' * padding_len - return base64.urlsafe_b64decode(encoded) - - -def _webauthn_b64_encode(raw): - return base64.urlsafe_b64encode(raw).rstrip(b'=') - - -def _get_trust_anchors(attestation_type, attestation_fmt, trust_anchor_dir): - '''Return a list of trusted attestation root certificates. - ''' - if attestation_type not in SUPPORTED_ATTESTATION_TYPES: - return [] - if attestation_fmt not in SUPPORTED_ATTESTATION_FORMATS: - return [] - - if trust_anchor_dir == DEFAULT_TRUST_ANCHOR_DIR: - ta_dir = os.path.join( - os.path.dirname(os.path.abspath(__file__)), trust_anchor_dir) - else: - ta_dir = trust_anchor_dir - - trust_anchors = [] - - if os.path.isdir(ta_dir): - for ta_name in os.listdir(ta_dir): - ta_path = os.path.join(ta_dir, ta_name) - if os.path.isfile(ta_path): - with open(ta_path, 'rb') as f: - pem_data = f.read().strip() - try: - pem = crypto.load_certificate(crypto.FILETYPE_PEM, - pem_data) - trust_anchors.append(pem) - except Exception: - pass - - return trust_anchors - - -def _is_trusted_attestation_cert(trust_path, trust_anchors): - if not trust_path or not isinstance(trust_path, list): - return False - # NOTE: Only using the first attestation cert in the - # attestation trust path for now, but should be - # able to build a chain. - attestation_cert = trust_path[0] - store = crypto.X509Store() - for _ta in trust_anchors: - store.add_cert(_ta) - store_ctx = crypto.X509StoreContext(store, attestation_cert) - - try: - store_ctx.verify_certificate() - return True - except Exception as e: - print('Unable to verify certificate: {}.'.format(e), file=sys.stderr) - - return False - - -def _verify_type(received_type, expected_type): - if received_type == expected_type: - return True - - return False - - -def _verify_challenge(received_challenge, sent_challenge): - if not isinstance(received_challenge, six.string_types): - return False - if not isinstance(sent_challenge, six.string_types): - return False - if not received_challenge: - return False - if not sent_challenge: - return False - if not constant_time.bytes_eq( - bytes(sent_challenge, encoding='utf-8'), - bytes(received_challenge, encoding='utf-8')): - return False - - return True - - -def _verify_origin(client_data, origin): - if not isinstance(client_data, dict): - return False - - client_data_origin = client_data.get('origin') - - if not client_data_origin: - return False - if client_data_origin != origin: - return False - - return True - - -def _verify_token_binding_id(client_data): - '''The tokenBinding member contains information about the state of the - Token Binding protocol used when communicating with the Relying Party. - The status member is one of: - - not-supported: when the client does not support token binding. - - supported: the client supports token binding, but it was not - negotiated when communicating with the Relying - Party. - - present: token binding was used when communicating with the - Relying Party. In this case, the id member MUST be - present and MUST be a base64url encoding of the - Token Binding ID that was used. - ''' - # TODO: Add support for verifying token binding ID. - token_binding_status = client_data['tokenBinding']['status'] - token_binding_id = client_data['tokenBinding'].get('id', '') - if token_binding_status in ('supported', 'not-supported'): - return True - return False - - -def _verify_client_extensions(client_extensions, expected_client_extensions): - if set(expected_client_extensions.keys()).issuperset( - client_extensions.keys()): - return True - return False - - -def _verify_authenticator_extensions(client_data, expected_authenticator_extensions): - # TODO - return True - - -def _verify_rp_id_hash(auth_data_rp_id_hash, rp_id): - if sys.version_info < (3, 0): # if python2 - rp_id_hash = hashlib.sha256(rp_id).digest() - return constant_time.bytes_eq( - bytes(auth_data_rp_id_hash, encoding='utf-8'), - bytes(rp_id_hash, encoding='utf-8')) - else: - rp_id_hash = hashlib.sha256(bytes(rp_id, "utf-8")).digest() - return constant_time.bytes_eq(auth_data_rp_id_hash, rp_id_hash) - - -def _verify_attestation_statement_format(fmt): - # TODO: Handle other attestation statement formats. - '''Verify the attestation statement format.''' - if not isinstance(fmt, six.string_types): - return False - - return fmt in SUPPORTED_ATTESTATION_FORMATS - - -def _get_auth_data_rp_id_hash(auth_data): - if not isinstance(auth_data, six.binary_type): - return False - - auth_data_rp_id_hash = auth_data[:32] - - return auth_data_rp_id_hash - - -def _get_client_data_hash(decoded_client_data): - if not isinstance(decoded_client_data, six.binary_type): - return '' - - return hashlib.sha256(decoded_client_data).digest() - - -def _validate_credential_id(credential_id): - if not isinstance(credential_id, six.string_types): - return False - - return True - - -def _verify_signature(public_key, alg, data, signature): - if alg == COSE_ALG_ES256: - public_key.verify(signature, data, ECDSA(SHA256())) - elif alg == COSE_ALG_RS256: - public_key.verify(signature, data, PKCS1v15(), SHA256()) - elif alg == COSE_ALG_PS256: - padding = PSS(mgf=MGF1(SHA256()), salt_length=32) - public_key.verify(signature, data, padding, SHA256()) - else: - raise NotImplementedError() From 036998c8d6fdc59e25ae0a0e3fbf401c776aa3d9 Mon Sep 17 00:00:00 2001 From: Matthew Miller Date: Thu, 14 Oct 2021 13:36:37 -0700 Subject: [PATCH 07/33] Update VERSION to 1.0.0 --- webauthn/__init__.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/webauthn/__init__.py b/webauthn/__init__.py index 419aa28..1f356cc 100644 --- a/webauthn/__init__.py +++ b/webauthn/__init__.py @@ -1,3 +1 @@ -# flake8: noqa - -__version__ = '0.4.7' +__version__ = '1.0.0' From e11fa36bddb18e10c4aafcb813d2bc56160833c6 Mon Sep 17 00:00:00 2001 From: Matthew Miller Date: Thu, 14 Oct 2021 14:08:13 -0700 Subject: [PATCH 08/33] Support last three versions of Python --- .github/workflows/build_and_test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build_and_test.yml b/.github/workflows/build_and_test.yml index 9da8354..95838fb 100644 --- a/.github/workflows/build_and_test.yml +++ b/.github/workflows/build_and_test.yml @@ -15,7 +15,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: [2.7, 3.5, 3.6, 3.7, 3.8] + python-version: [3.7, 3.8, 3.9] steps: - uses: actions/checkout@v2 From 133662a134153a9b9b804c651f7e662555ae04a0 Mon Sep 17 00:00:00 2001 From: Matthew Miller Date: Thu, 14 Oct 2021 14:08:37 -0700 Subject: [PATCH 09/33] Add .vscode --- .vscode/settings.json | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..00b174d --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,6 @@ +{ + "python.pythonPath": "venv/bin/python", + "python.linting.mypyEnabled": false, + "python.linting.flake8Enabled": true, + "python.linting.enabled": true +} From 3b557c54828fd48db5a398ccde87515116793114 Mon Sep 17 00:00:00 2001 From: Matthew Miller Date: Thu, 14 Oct 2021 14:08:44 -0700 Subject: [PATCH 10/33] Add requirements.txt --- requirements.txt | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 requirements.txt diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..9fa1760 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,9 @@ +asn1crypto==0.24.0 +cbor2==4.0.1 +cffi==1.15.0 +cryptography==3.4.7 +pycparser==2.20 +pydantic==1.8.2 +pyOpenSSL==20.0.1 +six==1.16.0 +typing-extensions==3.10.0.2 From 69893d7d31d0f6f1fe3100711bbb596be3e299cc Mon Sep 17 00:00:00 2001 From: Matthew Miller Date: Thu, 14 Oct 2021 14:16:22 -0700 Subject: [PATCH 11/33] Migrate examples --- examples/options.py | 78 ++++++++++++++++++++++++++++++++++++++ examples/verification.py | 81 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 159 insertions(+) create mode 100644 examples/options.py create mode 100644 examples/verification.py diff --git a/examples/options.py b/examples/options.py new file mode 100644 index 0000000..1d5e4a9 --- /dev/null +++ b/examples/options.py @@ -0,0 +1,78 @@ +from webauthn.authentication import generate_authentication_options +from webauthn.helpers import options_to_json +from webauthn.helpers.cose import COSEAlgorithmIdentifier +from webauthn.helpers.structs import ( + AttestationConveyancePreference, + AuthenticatorAttachment, + AuthenticatorSelectionCriteria, + PublicKeyCredentialDescriptor, + ResidentKeyRequirement, + UserVerificationRequirement, +) +from webauthn.registration import generate_registration_options + +################ +# +# Examples of using webauthn to generate registration options +# +# See these in action by executing this file from the root of this project: +# +# `python -m examples.options` +# +################ + +# Simple +simple_registration_options = generate_registration_options( + rp_id="example.com", + rp_name="Example Co", + user_id="12345", + user_name="bob", +) + +print("\n[Registration Options - Simple]") +print(options_to_json(simple_registration_options)) + +# Complex +complex_registration_options = generate_registration_options( + rp_id="example.com", + rp_name="Example Co", + user_id="ABAV6QWPBEY9WOTOA1A4", + user_name="lee", + user_display_name="Lee", + attestation=AttestationConveyancePreference.DIRECT, + authenticator_selection=AuthenticatorSelectionCriteria( + authenticator_attachment=AuthenticatorAttachment.PLATFORM, + resident_key=ResidentKeyRequirement.REQUIRED, + ), + challenge=b"1234567890", + exclude_credentials=[ + PublicKeyCredentialDescriptor(id=b"1234567890"), + ], + supported_pub_key_algs=[COSEAlgorithmIdentifier.ECDSA_SHA_512], + timeout=12000, +) + +print("\n[Registration Options - Complex]") +print(options_to_json(complex_registration_options)) + +################ +# +# Examples of using webauthn to generate authentication options +# +################ + +simple_authentication_options = generate_authentication_options(rp_id="example.com") + +print("\n[Authentication Options - Simple]") +print(options_to_json(simple_authentication_options)) + +complex_authentication_options = generate_authentication_options( + rp_id="example.com", + challenge=b"1234567890", + timeout=12000, + allow_credentials=[PublicKeyCredentialDescriptor(id=b"1234567890")], + user_verification=UserVerificationRequirement.REQUIRED, +) + +print("\n[Authentication Options - Complex]") +print(options_to_json(complex_authentication_options)) diff --git a/examples/verification.py b/examples/verification.py new file mode 100644 index 0000000..8c99653 --- /dev/null +++ b/examples/verification.py @@ -0,0 +1,81 @@ +from webauthn.authentication import verify_authentication_response +from webauthn.helpers import base64url_to_bytes +from webauthn.helpers.structs import ( + AuthenticationCredential, + RegistrationCredential, +) +from webauthn.registration import verify_registration_response + +################ +# +# Examples of using webauthn to verify responses +# +# Registrations and authentications are representative of WebAuthn credential responses +# as they would be encoded for transmission from the browser to the RP as JSON. This +# primarily means byte arrays are encoded as Base64URL on the client. +# +# See these in action by executing this file from the root of this project: +# +# `python -m examples.verification` +# +################ + +# Registration +registration_verification = verify_registration_response( + credential=RegistrationCredential.parse_raw( + """{ + "id": "ZoIKP1JQvKdrYj1bTUPJ2eTUsbLeFkv-X5xJQNr4k6s", + "rawId": "ZoIKP1JQvKdrYj1bTUPJ2eTUsbLeFkv-X5xJQNr4k6s", + "response": { + "attestationObject": "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YVkBZ0mWDeWIDoxodDQXD2R2YFuP5K65ooYyx5lc87qDHZdjRQAAAAAAAAAAAAAAAAAAAAAAAAAAACBmggo_UlC8p2tiPVtNQ8nZ5NSxst4WS_5fnElA2viTq6QBAwM5AQAgWQEA31dtHqc70D_h7XHQ6V_nBs3Tscu91kBL7FOw56_VFiaKYRH6Z4KLr4J0S12hFJ_3fBxpKfxyMfK66ZMeAVbOl_wemY4S5Xs4yHSWy21Xm_dgWhLJjZ9R1tjfV49kDPHB_ssdvP7wo3_NmoUPYMgK-edgZ_ehttp_I6hUUCnVaTvn_m76b2j9yEPReSwl-wlGsabYG6INUhTuhSOqG-UpVVQdNJVV7GmIPHCA2cQpJBDZBohT4MBGme_feUgm4sgqVCWzKk6CzIKIz5AIVnspLbu05SulAVnSTB3NxTwCLNJR_9v9oSkvphiNbmQBVQH1tV_psyi9HM1Jtj9VJVKMeyFDAQAB", + "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiQ2VUV29nbWcwY2NodWlZdUZydjhEWFhkTVpTSVFSVlpKT2dhX3hheVZWRWNCajBDdzN5NzN5aEQ0RmtHU2UtUnJQNmhQSkpBSW0zTFZpZW40aFhFTGciLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjUwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9" + }, + "type": "public-key", + "clientExtensionResults": {}, + "transports": ["internal"] + }""" + ), + expected_challenge=base64url_to_bytes( + "CeTWogmg0cchuiYuFrv8DXXdMZSIQRVZJOga_xayVVEcBj0Cw3y73yhD4FkGSe-RrP6hPJJAIm3LVien4hXELg" + ), + expected_origin="http://localhost:5000", + expected_rp_id="localhost", + require_user_verification=True, +) + +print("\n[Registration Verification - None]") +print(registration_verification.json(indent=2)) +assert registration_verification.credential_id == base64url_to_bytes( + "ZoIKP1JQvKdrYj1bTUPJ2eTUsbLeFkv-X5xJQNr4k6s" +) + +# Authentication +authentication_verification = verify_authentication_response( + credential=AuthenticationCredential.parse_raw( + """{ + "id": "ZoIKP1JQvKdrYj1bTUPJ2eTUsbLeFkv-X5xJQNr4k6s", + "rawId": "ZoIKP1JQvKdrYj1bTUPJ2eTUsbLeFkv-X5xJQNr4k6s", + "response": { + "authenticatorData": "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAAAQ", + "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiaVBtQWkxUHAxWEw2b0FncTNQV1p0WlBuWmExekZVRG9HYmFRMF9LdlZHMWxGMnMzUnRfM280dVN6Y2N5MHRtY1RJcFRUVDRCVTFULUk0bWFhdm5kalEiLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjUwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9", + "signature": "iOHKX3erU5_OYP_r_9HLZ-CexCE4bQRrxM8WmuoKTDdhAnZSeTP0sjECjvjfeS8MJzN1ArmvV0H0C3yy_FdRFfcpUPZzdZ7bBcmPh1XPdxRwY747OrIzcTLTFQUPdn1U-izCZtP_78VGw9pCpdMsv4CUzZdJbEcRtQuRS03qUjqDaovoJhOqEBmxJn9Wu8tBi_Qx7A33RbYjlfyLm_EDqimzDZhyietyop6XUcpKarKqVH0M6mMrM5zTjp8xf3W7odFCadXEJg-ERZqFM0-9Uup6kJNLbr6C5J4NDYmSm3HCSA6lp2iEiMPKU8Ii7QZ61kybXLxsX4w4Dm3fOLjmDw", + "userHandle": "T1RWa1l6VXdPRFV0WW1NNVlTMDBOVEkxTFRnd056Z3RabVZpWVdZNFpEVm1ZMk5p" + }, + "type": "public-key", + "clientExtensionResults": {} + }""" + ), + expected_challenge=base64url_to_bytes( + "iPmAi1Pp1XL6oAgq3PWZtZPnZa1zFUDoGbaQ0_KvVG1lF2s3Rt_3o4uSzccy0tmcTIpTTT4BU1T-I4maavndjQ" + ), + expected_rp_id="localhost", + expected_origin="http://localhost:5000", + credential_public_key=base64url_to_bytes( + "pAEDAzkBACBZAQDfV20epzvQP-HtcdDpX-cGzdOxy73WQEvsU7Dnr9UWJophEfpngouvgnRLXaEUn_d8HGkp_HIx8rrpkx4BVs6X_B6ZjhLlezjIdJbLbVeb92BaEsmNn1HW2N9Xj2QM8cH-yx28_vCjf82ahQ9gyAr552Bn96G22n8jqFRQKdVpO-f-bvpvaP3IQ9F5LCX7CUaxptgbog1SFO6FI6ob5SlVVB00lVXsaYg8cIDZxCkkENkGiFPgwEaZ7995SCbiyCpUJbMqToLMgojPkAhWeyktu7TlK6UBWdJMHc3FPAIs0lH_2_2hKS-mGI1uZAFVAfW1X-mzKL0czUm2P1UlUox7IUMBAAE" + ), + credential_current_sign_count=0, + require_user_verification=True, +) +print("\n[Authentication Verification]") +print(authentication_verification.json(indent=2)) +assert authentication_verification.new_sign_count == 1 From fe889eb0f0a2899c16262d0b48c9188b7ba69d56 Mon Sep 17 00:00:00 2001 From: Matthew Miller Date: Thu, 14 Oct 2021 15:07:34 -0700 Subject: [PATCH 12/33] Migrate primary functionality --- webauthn/__init__.py | 2 +- webauthn/authentication/__init__.py | 4 + .../generate_authentication_options.py | 48 ++ .../verify_authentication_response.py | 163 ++++++ webauthn/helpers/__init__.py | 16 + webauthn/helpers/aaguid_to_string.py | 27 + webauthn/helpers/algorithms.py | 91 ++++ webauthn/helpers/asn1/__init__.py | 0 webauthn/helpers/asn1/android_key.py | 131 +++++ webauthn/helpers/base64url_to_bytes.py | 12 + webauthn/helpers/bytes_to_base64url.py | 8 + webauthn/helpers/cose.py | 79 +++ .../helpers/decode_credential_public_key.py | 116 ++++ .../decoded_public_key_to_cryptography.py | 71 +++ webauthn/helpers/exceptions.py | 50 ++ webauthn/helpers/generate_challenge.py | 8 + webauthn/helpers/generate_user_handle.py | 17 + webauthn/helpers/hash_by_alg.py | 41 ++ .../helpers/json_loads_base64url_to_bytes.py | 39 ++ webauthn/helpers/known_root_certs.py | 199 +++++++ webauthn/helpers/options_to_json.py | 22 + webauthn/helpers/parse_attestation_object.py | 25 + .../helpers/parse_attestation_statement.py | 26 + webauthn/helpers/parse_authenticator_data.py | 66 +++ webauthn/helpers/parse_client_data_json.py | 73 +++ .../pem_cert_bytes_to_open_ssl_x509.py | 12 + webauthn/helpers/snake_case_to_camel_case.py | 14 + webauthn/helpers/structs.py | 514 ++++++++++++++++++ webauthn/helpers/tpm/__init__.py | 2 + webauthn/helpers/tpm/parse_cert_info.py | 74 +++ webauthn/helpers/tpm/parse_pub_area.py | 60 ++ webauthn/helpers/tpm/structs.py | 409 ++++++++++++++ .../helpers/validate_certificate_chain.py | 77 +++ webauthn/helpers/verify_signature.py | 72 +++ webauthn/registration/__init__.py | 2 + webauthn/registration/formats/__init__.py | 0 webauthn/registration/formats/android_key.py | 186 +++++++ .../registration/formats/android_safetynet.py | 195 +++++++ webauthn/registration/formats/apple.py | 125 +++++ webauthn/registration/formats/fido_u2f.py | 129 +++++ webauthn/registration/formats/packed.py | 107 ++++ webauthn/registration/formats/tpm.py | 312 +++++++++++ .../generate_registration_options.py | 129 +++++ .../verify_registration_response.py | 275 ++++++++++ 44 files changed, 4027 insertions(+), 1 deletion(-) create mode 100644 webauthn/authentication/__init__.py create mode 100644 webauthn/authentication/generate_authentication_options.py create mode 100644 webauthn/authentication/verify_authentication_response.py create mode 100644 webauthn/helpers/__init__.py create mode 100644 webauthn/helpers/aaguid_to_string.py create mode 100644 webauthn/helpers/algorithms.py create mode 100644 webauthn/helpers/asn1/__init__.py create mode 100644 webauthn/helpers/asn1/android_key.py create mode 100644 webauthn/helpers/base64url_to_bytes.py create mode 100644 webauthn/helpers/bytes_to_base64url.py create mode 100644 webauthn/helpers/cose.py create mode 100644 webauthn/helpers/decode_credential_public_key.py create mode 100644 webauthn/helpers/decoded_public_key_to_cryptography.py create mode 100644 webauthn/helpers/exceptions.py create mode 100644 webauthn/helpers/generate_challenge.py create mode 100644 webauthn/helpers/generate_user_handle.py create mode 100644 webauthn/helpers/hash_by_alg.py create mode 100644 webauthn/helpers/json_loads_base64url_to_bytes.py create mode 100644 webauthn/helpers/known_root_certs.py create mode 100644 webauthn/helpers/options_to_json.py create mode 100644 webauthn/helpers/parse_attestation_object.py create mode 100644 webauthn/helpers/parse_attestation_statement.py create mode 100644 webauthn/helpers/parse_authenticator_data.py create mode 100644 webauthn/helpers/parse_client_data_json.py create mode 100644 webauthn/helpers/pem_cert_bytes_to_open_ssl_x509.py create mode 100644 webauthn/helpers/snake_case_to_camel_case.py create mode 100644 webauthn/helpers/structs.py create mode 100644 webauthn/helpers/tpm/__init__.py create mode 100644 webauthn/helpers/tpm/parse_cert_info.py create mode 100644 webauthn/helpers/tpm/parse_pub_area.py create mode 100644 webauthn/helpers/tpm/structs.py create mode 100644 webauthn/helpers/validate_certificate_chain.py create mode 100644 webauthn/helpers/verify_signature.py create mode 100644 webauthn/registration/__init__.py create mode 100644 webauthn/registration/formats/__init__.py create mode 100644 webauthn/registration/formats/android_key.py create mode 100644 webauthn/registration/formats/android_safetynet.py create mode 100644 webauthn/registration/formats/apple.py create mode 100644 webauthn/registration/formats/fido_u2f.py create mode 100644 webauthn/registration/formats/packed.py create mode 100644 webauthn/registration/formats/tpm.py create mode 100644 webauthn/registration/generate_registration_options.py create mode 100644 webauthn/registration/verify_registration_response.py diff --git a/webauthn/__init__.py b/webauthn/__init__.py index 1f356cc..5becc17 100644 --- a/webauthn/__init__.py +++ b/webauthn/__init__.py @@ -1 +1 @@ -__version__ = '1.0.0' +__version__ = "1.0.0" diff --git a/webauthn/authentication/__init__.py b/webauthn/authentication/__init__.py new file mode 100644 index 0000000..2218d69 --- /dev/null +++ b/webauthn/authentication/__init__.py @@ -0,0 +1,4 @@ +from .generate_authentication_options import ( # noqa: F401 + generate_authentication_options, +) +from .verify_authentication_response import verify_authentication_response # noqa: F401 diff --git a/webauthn/authentication/generate_authentication_options.py b/webauthn/authentication/generate_authentication_options.py new file mode 100644 index 0000000..4b0c3bd --- /dev/null +++ b/webauthn/authentication/generate_authentication_options.py @@ -0,0 +1,48 @@ +from typing import List, Optional + +from ..helpers import generate_challenge +from ..helpers.structs import ( + PublicKeyCredentialDescriptor, + PublicKeyCredentialRequestOptions, + UserVerificationRequirement, +) + + +def generate_authentication_options( + *, + rp_id: str, + challenge: Optional[bytes] = None, + timeout: int = 60000, + allow_credentials: Optional[List[PublicKeyCredentialDescriptor]] = None, + user_verification: UserVerificationRequirement = UserVerificationRequirement.PREFERRED, +) -> PublicKeyCredentialRequestOptions: + """Generate options for retrieving a credential via navigator.credentials.get() + + Args: + `rp_id`: The Relying Party's unique identifier as specified in attestations. + (optional) `challenge`: A byte sequence for the authenticator to return back in its response. If no value is specified then a sequence of random bytes will be generated. + (optional) `timeout`: How long in milliseconds the browser should give the user to choose an authenticator. This value is a *hint* and may be ignored by the browser. + (optional) `allow_credentials`: A list of credentials registered to the user. + (optional) `user_verification`: The RP's preference for the authenticator's enforcement of the "user verified" flag. + + Returns: + Authentication options ready for the browser. Consider using `helpers.options_to_json()` in this library to quickly convert the options to JSON. + """ + + ######## + # Set defaults for required values + ######## + + if not challenge: + challenge = generate_challenge() + + if not allow_credentials: + allow_credentials = [] + + return PublicKeyCredentialRequestOptions( + rp_id=rp_id, + challenge=challenge, + timeout=timeout, + allow_credentials=allow_credentials, + user_verification=user_verification, + ) diff --git a/webauthn/authentication/verify_authentication_response.py b/webauthn/authentication/verify_authentication_response.py new file mode 100644 index 0000000..27ec18b --- /dev/null +++ b/webauthn/authentication/verify_authentication_response.py @@ -0,0 +1,163 @@ +import hashlib +from typing import List, Union + +from cryptography.exceptions import InvalidSignature + +from ..helpers import ( + bytes_to_base64url, + decode_credential_public_key, + decoded_public_key_to_cryptography, + parse_authenticator_data, + parse_client_data_json, + verify_signature, +) +from ..helpers.exceptions import InvalidAuthenticationResponse +from ..helpers.structs import ( + AuthenticationCredential, + ClientDataType, + PublicKeyCredentialType, + TokenBindingStatus, + WebAuthnBaseModel, +) + + +class VerifiedAuthentication(WebAuthnBaseModel): + """ + Information about a verified authentication of which an RP can make use + """ + + credential_id: bytes + new_sign_count: int + + +expected_token_binding_statuses = [ + TokenBindingStatus.SUPPORTED, + TokenBindingStatus.PRESENT, +] + + +def verify_authentication_response( + *, + credential: AuthenticationCredential, + expected_challenge: bytes, + expected_rp_id: str, + expected_origin: Union[str, List[str]], + credential_public_key: bytes, + credential_current_sign_count: int, + require_user_verification: bool = False, +) -> VerifiedAuthentication: + """Verify a response from navigator.credentials.get() + + Args: + `credential`: The value returned from `navigator.credentials.create()`. + `expected_challenge`: The challenge passed to the authenticator within the preceding authentication options. + `expected_rp_id`: The Relying Party's unique identifier as specified in the precending authentication options. + `expected_origin`: The domain, with HTTP protocol (e.g. "https://domain.here"), on which the authentication ceremony should have occurred. + `credential_public_key`: The public key for the credential's ID as provided in a preceding authenticator registration ceremony. + `credential_current_sign_count`: The current known number of times the authenticator was used. + (optional) `require_user_verification`: Whether or not to require that the authenticator verified the user. + + Returns: + Information about the authenticator + + Raises: + `helpers.exceptions.InvalidAuthenticationResponse` if the response cannot be verified + """ + + # FIDO-specific check + if bytes_to_base64url(credential.raw_id) != credential.id: + raise InvalidAuthenticationResponse("id and raw_id were not equivalent") + + # FIDO-specific check + if credential.type != PublicKeyCredentialType.PUBLIC_KEY: + raise InvalidAuthenticationResponse( + f'Unexpected credential type "{credential.type}", expected "public-key"' + ) + + response = credential.response + + client_data = parse_client_data_json(response.client_data_json) + + if client_data.type != ClientDataType.WEBAUTHN_GET: + raise InvalidAuthenticationResponse( + f'Unexpected client data type "{client_data.type}", expected "{ClientDataType.WEBAUTHN_GET}"' + ) + + if expected_challenge != client_data.challenge: + raise InvalidAuthenticationResponse( + "Client data challenge was not expected challenge" + ) + + if isinstance(expected_origin, str): + if expected_origin != client_data.origin: + raise InvalidAuthenticationResponse( + f'Unexpected client data origin "{client_data.origin}", expected "{expected_origin}"' + ) + else: + try: + expected_origin.index(client_data.origin) + except ValueError: + raise InvalidAuthenticationResponse( + f'Unexpected client data origin "{client_data.origin}", expected one of {expected_origin}' + ) + + if client_data.token_binding: + status = client_data.token_binding.status + if status not in expected_token_binding_statuses: + raise InvalidAuthenticationResponse( + f'Unexpected token_binding status of "{status}", expected one of "{",".join(expected_token_binding_statuses)}"' + ) + + auth_data = parse_authenticator_data(response.authenticator_data) + + # Generate a hash of the expected RP ID for comparison + expected_rp_id_hash = hashlib.sha256() + expected_rp_id_hash.update(expected_rp_id.encode("utf-8")) + expected_rp_id_hash = expected_rp_id_hash.digest() + + if auth_data.rp_id_hash != expected_rp_id_hash: + raise InvalidAuthenticationResponse("Unexpected RP ID hash") + + if not auth_data.flags.up: + raise InvalidAuthenticationResponse( + "User was not present during authentication" + ) + + if require_user_verification and not auth_data.flags.uv: + raise InvalidAuthenticationResponse( + "User verification is required but user was not verified during authentication" + ) + + if ( + auth_data.sign_count > 0 or credential_current_sign_count > 0 + ) and auth_data.sign_count <= credential_current_sign_count: + # Require the sign count to have been incremented over what was reported by the + # authenticator the last time this credential was used, otherwise this might be + # a replay attack + raise InvalidAuthenticationResponse( + f"Response sign count of {auth_data.sign_count} was not greater than current count of {credential_current_sign_count}" + ) + + client_data_hash = hashlib.sha256() + client_data_hash.update(response.client_data_json) + client_data_hash = client_data_hash.digest() + + signature_base = response.authenticator_data + client_data_hash + + try: + decoded_public_key = decode_credential_public_key(credential_public_key) + crypto_public_key = decoded_public_key_to_cryptography(decoded_public_key) + + verify_signature( + public_key=crypto_public_key, + signature_alg=decoded_public_key.alg, + signature=response.signature, + data=signature_base, + ) + except InvalidSignature: + raise InvalidAuthenticationResponse("Could not verify authentication signature") + + return VerifiedAuthentication( + credential_id=credential.raw_id, + new_sign_count=auth_data.sign_count, + ) diff --git a/webauthn/helpers/__init__.py b/webauthn/helpers/__init__.py new file mode 100644 index 0000000..c7c9ef8 --- /dev/null +++ b/webauthn/helpers/__init__.py @@ -0,0 +1,16 @@ +from .aaguid_to_string import aaguid_to_string # noqa: F401 +from .base64url_to_bytes import base64url_to_bytes # noqa: F401 +from .bytes_to_base64url import bytes_to_base64url # noqa: F401 +from .decode_credential_public_key import decode_credential_public_key # noqa: F401 +from .decoded_public_key_to_cryptography import ( # noqa: F401 + decoded_public_key_to_cryptography, +) +from .generate_challenge import generate_challenge # noqa: F401 +from .generate_user_handle import generate_user_handle # noqa: F401 +from .hash_by_alg import hash_by_alg # noqa: F401 +from .options_to_json import options_to_json # noqa: F401 +from .parse_attestation_object import parse_attestation_object # noqa: F401 +from .parse_authenticator_data import parse_authenticator_data # noqa: F401 +from .parse_client_data_json import parse_client_data_json # noqa: F401 +from .validate_certificate_chain import validate_certificate_chain # noqa: F401 +from .verify_signature import verify_signature # noqa: F401 diff --git a/webauthn/helpers/aaguid_to_string.py b/webauthn/helpers/aaguid_to_string.py new file mode 100644 index 0000000..ef93cb2 --- /dev/null +++ b/webauthn/helpers/aaguid_to_string.py @@ -0,0 +1,27 @@ +import codecs + + +def aaguid_to_string(val: bytes) -> str: + """ + Take aaguid bytes and convert them to a GUID string + """ + if len(val) != 16: + raise ValueError(f"AAGUID was {len(val)} bytes, expected 16 bytes") + + # Convert to a hexadecimal string representation + to_hex = codecs.encode(val, encoding="hex").decode("utf-8") + + # Split up the hex string into segments + # 8 chars + seg_1 = to_hex[0:8] + # 4 chars + seg_2 = to_hex[8:12] + # 4 chars + seg_3 = to_hex[12:16] + # 4 chars + seg_4 = to_hex[16:20] + # 12 chars + seg_5 = to_hex[20:32] + + # "00000000-0000-0000-0000-000000000000" + return f"{seg_1}-{seg_2}-{seg_3}-{seg_4}-{seg_5}" diff --git a/webauthn/helpers/algorithms.py b/webauthn/helpers/algorithms.py new file mode 100644 index 0000000..9d2b88a --- /dev/null +++ b/webauthn/helpers/algorithms.py @@ -0,0 +1,91 @@ +from cryptography.hazmat.primitives.asymmetric.ec import ( + ECDSA, + SECP256R1, + SECP384R1, + SECP521R1, + EllipticCurve, + EllipticCurveSignatureAlgorithm, +) +from cryptography.hazmat.primitives.hashes import ( + SHA1, + SHA256, + SHA384, + SHA512, + HashAlgorithm, +) + +from .cose import COSECRV, COSEAlgorithmIdentifier +from .exceptions import UnsupportedAlgorithm, UnsupportedEC2Curve + + +def is_rsa_pkcs(alg_id: COSEAlgorithmIdentifier) -> bool: + """Determine if the specified COSE algorithm ID denotes an RSA PKCSv1 public key""" + return alg_id in ( + COSEAlgorithmIdentifier.RSASSA_PKCS1_v1_5_SHA_1, + COSEAlgorithmIdentifier.RSASSA_PKCS1_v1_5_SHA_256, + COSEAlgorithmIdentifier.RSASSA_PKCS1_v1_5_SHA_384, + COSEAlgorithmIdentifier.RSASSA_PKCS1_v1_5_SHA_512, + ) + + +def is_rsa_pss(alg_id: COSEAlgorithmIdentifier) -> bool: + """Determine if the specified COSE algorithm ID denotes an RSA PSS public key""" + return alg_id in ( + COSEAlgorithmIdentifier.RSASSA_PSS_SHA_256, + COSEAlgorithmIdentifier.RSASSA_PSS_SHA_384, + COSEAlgorithmIdentifier.RSASSA_PSS_SHA_512, + ) + + +def get_ec2_sig_alg(alg_id: COSEAlgorithmIdentifier) -> EllipticCurveSignatureAlgorithm: + """Turn an "ECDSA" COSE algorithm identifier into a corresponding signature + algorithm + """ + if alg_id == COSEAlgorithmIdentifier.ECDSA_SHA_256: + return ECDSA(SHA256()) + if alg_id == COSEAlgorithmIdentifier.ECDSA_SHA_512: + return ECDSA(SHA512()) + + raise UnsupportedAlgorithm(f"Unrecognized EC2 signature alg {alg_id}") + + +def get_ec2_curve(crv_id: COSECRV) -> EllipticCurve: + """Turn an EC2 COSE crv identifier into a corresponding curve""" + if crv_id == COSECRV.P256: + return SECP256R1() + elif crv_id == COSECRV.P384: + return SECP384R1() + elif crv_id == COSECRV.P521: + return SECP521R1() + + raise UnsupportedEC2Curve(f"Unrecognized EC2 curve {crv_id}") + + +def get_rsa_pkcs1_sig_alg(alg_id: COSEAlgorithmIdentifier) -> HashAlgorithm: + """Turn an "RSASSA_PKCS1" COSE algorithm identifier into a corresponding signature + algorithm + """ + if alg_id == COSEAlgorithmIdentifier.RSASSA_PKCS1_v1_5_SHA_1: + return SHA1() + if alg_id == COSEAlgorithmIdentifier.RSASSA_PKCS1_v1_5_SHA_256: + return SHA256() + if alg_id == COSEAlgorithmIdentifier.RSASSA_PKCS1_v1_5_SHA_384: + return SHA384() + if alg_id == COSEAlgorithmIdentifier.RSASSA_PKCS1_v1_5_SHA_512: + return SHA512() + + raise UnsupportedAlgorithm(f"Unrecognized RSA PKCS1 signature alg {alg_id}") + + +def get_rsa_pss_sig_alg(alg_id: COSEAlgorithmIdentifier) -> HashAlgorithm: + """Turn an "RSASSA_PSS" COSE algorithm identifier into a corresponding signature + algorithm + """ + if alg_id == COSEAlgorithmIdentifier.RSASSA_PSS_SHA_256: + return SHA256() + if alg_id == COSEAlgorithmIdentifier.RSASSA_PSS_SHA_384: + return SHA384() + if alg_id == COSEAlgorithmIdentifier.RSASSA_PSS_SHA_512: + return SHA512() + + raise UnsupportedAlgorithm(f"Unrecognized RSA PSS signature alg {alg_id}") diff --git a/webauthn/helpers/asn1/__init__.py b/webauthn/helpers/asn1/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/webauthn/helpers/asn1/android_key.py b/webauthn/helpers/asn1/android_key.py new file mode 100644 index 0000000..647a48d --- /dev/null +++ b/webauthn/helpers/asn1/android_key.py @@ -0,0 +1,131 @@ +from enum import Enum + +from asn1crypto.core import ( + Boolean, + Enumerated, + Integer, + Null, + OctetString, + Sequence, + SetOf, +) + + +class Integers(SetOf): + _child_spec = Integer + + +class SecurityLevel(Enumerated): + _map = { + 0: "Software", + 1: "TrustedEnvironment", + 2: "StrongBox", + } + + +class VerifiedBootState(Enumerated): + _map = { + 0: "Verified", + 1: "SelfSigned", + 2: "Unverified", + 3: "Failed", + } + + +class RootOfTrust(Sequence): + _fields = [ + ("verifiedBootKey", OctetString), + ("deviceLocked", Boolean), + ("verifiedBootState", VerifiedBootState), + ("verifiedBootHash", OctetString), + ] + + +class AuthorizationList(Sequence): + _fields = [ + ("purpose", Integers, {"explicit": 1, "optional": True}), + ("algorithm", Integer, {"explicit": 2, "optional": True}), + ("keySize", Integer, {"explicit": 3, "optional": True}), + ("digest", Integers, {"explicit": 5, "optional": True}), + ("padding", Integers, {"explicit": 6, "optional": True}), + ("ecCurve", Integer, {"explicit": 10, "optional": True}), + ("rsaPublicExponent", Integer, {"explicit": 200, "optional": True}), + ("rollbackResistance", Null, {"explicit": 303, "optional": True}), + ("activeDateTime", Integer, {"explicit": 400, "optional": True}), + ("originationExpireDateTime", Integer, {"explicit": 401, "optional": True}), + ("usageExpireDateTime", Integer, {"explicit": 402, "optional": True}), + ("noAuthRequired", Null, {"explicit": 503, "optional": True}), + ("userAuthType", Integer, {"explicit": 504, "optional": True}), + ("authTimeout", Integer, {"explicit": 505, "optional": True}), + ("allowWhileOnBody", Null, {"explicit": 506, "optional": True}), + ("trustedUserPresenceRequired", Null, {"explicit": 507, "optional": True}), + ("trustedConfirmationRequired", Null, {"explicit": 508, "optional": True}), + ("unlockedDeviceRequired", Null, {"explicit": 509, "optional": True}), + ("allApplications", Null, {"explicit": 600, "optional": True}), + ("applicationId", OctetString, {"explicit": 601, "optional": True}), + ("creationDateTime", Integer, {"explicit": 701, "optional": True}), + ("origin", Integer, {"explicit": 702, "optional": True}), + ("rollbackResistant", Null, {"explicit": 703, "optional": True}), + ("rootOfTrust", RootOfTrust, {"explicit": 704, "optional": True}), + ("osVersion", Integer, {"explicit": 705, "optional": True}), + ("osPatchLevel", Integer, {"explicit": 706, "optional": True}), + ("attestationApplicationId", OctetString, {"explicit": 709, "optional": True}), + ("attestationIdBrand", OctetString, {"explicit": 710, "optional": True}), + ("attestationIdDevice", OctetString, {"explicit": 711, "optional": True}), + ("attestationIdProduct", OctetString, {"explicit": 712, "optional": True}), + ("attestationIdSerial", OctetString, {"explicit": 713, "optional": True}), + ("attestationIdImei", OctetString, {"explicit": 714, "optional": True}), + ("attestationIdMeid", OctetString, {"explicit": 715, "optional": True}), + ("attestationIdManufacturer", OctetString, {"explicit": 716, "optional": True}), + ("attestationIdModel", OctetString, {"explicit": 717, "optional": True}), + ("vendorPatchLevel", Integer, {"explicit": 718, "optional": True}), + ("bootPatchLevel", Integer, {"explicit": 719, "optional": True}), + ] + + +class KeyDescription(Sequence): + """Attestation extension content as ASN.1 schema (DER-encoded) + + Corresponds to X.509 certificate extension with the following OID: + + `1.3.6.1.4.1.11129.2.1.17` + + See https://source.android.com/security/keystore/attestation#schema + """ + + _fields = [ + ("attestationVersion", Integer), + ("attestationSecurityLevel", SecurityLevel), + ("keymasterVersion", Integer), + ("keymasterSecurityLevel", SecurityLevel), + ("attestationChallenge", OctetString), + ("uniqueId", OctetString), + ("softwareEnforced", AuthorizationList), + ("teeEnforced", AuthorizationList), + ] + + +class KeyOrigin(int, Enum): + """`Tag::ORIGIN` + + See https://source.android.com/security/keystore/tags#origin + """ + + GENERATED = 0 + DERIVED = 1 + IMPORTED = 2 + UNKNOWN = 3 + + +class KeyPurpose(int, Enum): + """`Tag::PURPOSE` + + See https://source.android.com/security/keystore/tags#purpose + """ + + ENCRYPT = 0 + DECRYPT = 1 + SIGN = 2 + VERIFY = 3 + DERIVE_KEY = 4 + WRAP_KEY = 5 diff --git a/webauthn/helpers/base64url_to_bytes.py b/webauthn/helpers/base64url_to_bytes.py new file mode 100644 index 0000000..a4343ff --- /dev/null +++ b/webauthn/helpers/base64url_to_bytes.py @@ -0,0 +1,12 @@ +from base64 import urlsafe_b64decode + + +def base64url_to_bytes(val: str) -> bytes: + """ + Convert a Base64URL-encoded string to bytes. + """ + # Padding is optional in Base64URL. Unfortunately, Python's decoder requires the + # padding. Given the fact that urlsafe_b64decode will ignore too _much_ padding, + # we can tack on a constant amount of padding to ensure encoded values can always be + # decoded. + return urlsafe_b64decode(f"{val}===") diff --git a/webauthn/helpers/bytes_to_base64url.py b/webauthn/helpers/bytes_to_base64url.py new file mode 100644 index 0000000..ab7eeff --- /dev/null +++ b/webauthn/helpers/bytes_to_base64url.py @@ -0,0 +1,8 @@ +from base64 import urlsafe_b64encode + + +def bytes_to_base64url(val: bytes) -> str: + """ + Base64URL-encode the provided bytes + """ + return urlsafe_b64encode(val).decode("utf-8").replace("=", "") diff --git a/webauthn/helpers/cose.py b/webauthn/helpers/cose.py new file mode 100644 index 0000000..7c4e6b4 --- /dev/null +++ b/webauthn/helpers/cose.py @@ -0,0 +1,79 @@ +from enum import Enum + + +class COSEAlgorithmIdentifier(int, Enum): + """Various registered values indicating cryptographic algorithms that may be used in credential responses + + Members: + `ECDSA_SHA_256` + `EDDSA` + `ECDSA_SHA_512` + `RSASSA_PSS_SHA_256` + `RSASSA_PSS_SHA_384` + `RSASSA_PSS_SHA_512` + `RSASSA_PKCS1_v1_5_SHA_256` + `RSASSA_PKCS1_v1_5_SHA_384` + `RSASSA_PKCS1_v1_5_SHA_512` + `RSASSA_PKCS1_v1_5_SHA_1` + + https://www.w3.org/TR/webauthn-2/#sctn-alg-identifier + https://www.iana.org/assignments/cose/cose.xhtml#algorithms + """ + + ECDSA_SHA_256 = -7 + EDDSA = -8 + ECDSA_SHA_512 = -36 + RSASSA_PSS_SHA_256 = -37 + RSASSA_PSS_SHA_384 = -38 + RSASSA_PSS_SHA_512 = -39 + RSASSA_PKCS1_v1_5_SHA_256 = -257 + RSASSA_PKCS1_v1_5_SHA_384 = -258 + RSASSA_PKCS1_v1_5_SHA_512 = -259 + RSASSA_PKCS1_v1_5_SHA_1 = -65535 # Deprecated; here for legacy support + + +class COSEKTY(int, Enum): + """ + Possible values for COSEKey.KTY representing a public key's key type + + https://tools.ietf.org/html/rfc8152#section-13 + https://www.iana.org/assignments/cose/cose.xhtml#table-key-type + """ + + OKP = 1 + EC2 = 2 + RSA = 3 + + +class COSECRV(int, Enum): + """Possible values for COSEKey.CRV representing an EC2 public key's curve + + https://tools.ietf.org/html/rfc8152#section-13.1 + https://www.iana.org/assignments/cose/cose.xhtml#table-elliptic-curves + """ + + P256 = 1 # EC2, NIST P-256 also known as secp256r1 + P384 = 2 # EC2, NIST P-384 also known as secp384r1 + P521 = 3 # EC2, NIST P-521 also known as secp521r1 + ED25519 = 6 # OKP, Ed25519 for use w/ EdDSA only + + +class COSEKey(int, Enum): + """ + COSE keys for public keys + + https://tools.ietf.org/html/rfc8152 + https://www.iana.org/assignments/cose/cose.xhtml#table-key-common-parameters + https://www.iana.org/assignments/cose/cose.xhtml#table-key-type-parameters + """ + + KTY = 1 + ALG = 3 + # EC2, OKP + CRV = -1 + X = -2 + # EC2 + Y = -3 + # RSA + N = -1 + E = -2 diff --git a/webauthn/helpers/decode_credential_public_key.py b/webauthn/helpers/decode_credential_public_key.py new file mode 100644 index 0000000..15ed499 --- /dev/null +++ b/webauthn/helpers/decode_credential_public_key.py @@ -0,0 +1,116 @@ +from typing import Union + +from cbor2 import decoder +from pydantic import BaseModel + +from .cose import COSECRV, COSEKTY, COSEAlgorithmIdentifier, COSEKey +from .exceptions import InvalidPublicKeyStructure, UnsupportedPublicKeyType + + +class DecodedOKPPublicKey(BaseModel): + kty: COSEKTY + alg: COSEAlgorithmIdentifier + crv: COSECRV + x: bytes + + +class DecodedEC2PublicKey(BaseModel): + kty: COSEKTY + alg: COSEAlgorithmIdentifier + crv: COSECRV + x: bytes + y: bytes + + +class DecodedRSAPublicKey(BaseModel): + kty: COSEKTY + alg: COSEAlgorithmIdentifier + n: bytes + e: bytes + + +def decode_credential_public_key( + key: bytes, +) -> Union[DecodedOKPPublicKey, DecodedEC2PublicKey, DecodedRSAPublicKey]: + """ + Decode a CBOR-encoded public key and turn it into a data structure. + + Supports OKP, EC2, and RSA public keys + """ + # Occassionally we might be given a public key in an "uncompressed" format, + # typically from older U2F security keys. As per the FIDO spec this is indicated by + # a leading 0x04 "uncompressed point compression method" format byte. In that case + # we need to fill in some blanks to turn it into a full EC2 key for signature + # verification + # + # See https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-registry-v2.0-id-20180227.html#public-key-representation-formats + if key[0] == 0x04: + return DecodedEC2PublicKey( + kty=COSEKTY.EC2, + alg=COSEAlgorithmIdentifier.ECDSA_SHA_256, + crv=COSECRV.P256, + x=key[1:33], + y=key[33:65], + ) + + decoded_key: dict = decoder.loads(key) + + kty = decoded_key[COSEKey.KTY] + alg = decoded_key[COSEKey.ALG] + + if not kty: + raise InvalidPublicKeyStructure("Credential public key missing kty") + if not alg: + raise InvalidPublicKeyStructure("Credential public key missing alg") + + if kty == COSEKTY.OKP: + crv = decoded_key[COSEKey.CRV] + x = decoded_key[COSEKey.X] + + if not crv: + raise InvalidPublicKeyStructure("OKP credential public key missing crv") + if not x: + raise InvalidPublicKeyStructure("OKP credential public key missing x") + + return DecodedOKPPublicKey( + kty=kty, + alg=alg, + crv=crv, + x=x, + ) + elif kty == COSEKTY.EC2: + crv = decoded_key[COSEKey.CRV] + x = decoded_key[COSEKey.X] + y = decoded_key[COSEKey.Y] + + if not crv: + raise InvalidPublicKeyStructure("EC2 credential public key missing crv") + if not x: + raise InvalidPublicKeyStructure("EC2 credential public key missing x") + if not y: + raise InvalidPublicKeyStructure("EC2 credential public key missing y") + + return DecodedEC2PublicKey( + kty=kty, + alg=alg, + crv=crv, + x=x, + y=y, + ) + elif kty == COSEKTY.RSA: + n = decoded_key[COSEKey.N] + e = decoded_key[COSEKey.E] + + if not n: + raise InvalidPublicKeyStructure("RSA credential public key missing n") + if not e: + raise InvalidPublicKeyStructure("RSA credential public key missing e") + + return DecodedRSAPublicKey( + kty=kty, + alg=alg, + n=n, + e=e, + ) + + raise UnsupportedPublicKeyType(f'Unsupported credential public key type "{kty}"') diff --git a/webauthn/helpers/decoded_public_key_to_cryptography.py b/webauthn/helpers/decoded_public_key_to_cryptography.py new file mode 100644 index 0000000..e07d38d --- /dev/null +++ b/webauthn/helpers/decoded_public_key_to_cryptography.py @@ -0,0 +1,71 @@ +import codecs +from typing import Union + +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives.asymmetric.ec import ( + EllipticCurvePublicKey, + EllipticCurvePublicNumbers, +) +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey, RSAPublicNumbers + +from .algorithms import get_ec2_curve +from .cose import COSECRV, COSEAlgorithmIdentifier +from .decode_credential_public_key import ( + DecodedEC2PublicKey, + DecodedOKPPublicKey, + DecodedRSAPublicKey, +) +from .exceptions import UnsupportedPublicKey + + +def decoded_public_key_to_cryptography( + public_key: Union[DecodedOKPPublicKey, DecodedEC2PublicKey, DecodedRSAPublicKey] +) -> Union[Ed25519PublicKey, EllipticCurvePublicKey, RSAPublicKey]: + """Convert raw decoded public key parameters (crv, x, y, n, e, etc...) into + public keys using primitives from the cryptography.io library + """ + if isinstance(public_key, DecodedEC2PublicKey): + """ + alg is -7 (ES256), where kty is 2 (with uncompressed points) and + crv is 1 (P-256). + https://www.w3.org/TR/webauthn-2/#sctn-public-key-easy + """ + x = int(codecs.encode(public_key.x, "hex"), 16) + y = int(codecs.encode(public_key.y, "hex"), 16) + curve = get_ec2_curve(public_key.crv) + + ecc_pub_key = EllipticCurvePublicNumbers(x, y, curve).public_key( + default_backend() + ) + + return ecc_pub_key + elif isinstance(public_key, DecodedRSAPublicKey): + """ + alg is -257 (RS256) + https://www.w3.org/TR/webauthn-2/#sctn-public-key-easy + """ + e = int(codecs.encode(public_key.e, "hex"), 16) + n = int(codecs.encode(public_key.n, "hex"), 16) + + rsa_pub_key = RSAPublicNumbers(e, n).public_key(default_backend()) + + return rsa_pub_key + elif isinstance(public_key, DecodedOKPPublicKey): + """ + -8 (EdDSA), where crv is 6 (Ed25519). + https://www.w3.org/TR/webauthn-2/#sctn-public-key-easy + """ + if ( + public_key.alg != COSEAlgorithmIdentifier.EDDSA + or public_key.crv != COSECRV.ED25519 + ): + raise UnsupportedPublicKey( + f"OKP public key with alg {public_key.alg} and crv {public_key.crv} is not supported" + ) + + okp_pub_key = Ed25519PublicKey.from_public_bytes(public_key.x) + + return okp_pub_key + else: + raise UnsupportedPublicKey(f"Unrecognized decoded public key: {public_key}") diff --git a/webauthn/helpers/exceptions.py b/webauthn/helpers/exceptions.py new file mode 100644 index 0000000..394c627 --- /dev/null +++ b/webauthn/helpers/exceptions.py @@ -0,0 +1,50 @@ +class InvalidRegistrationResponse(Exception): + pass + + +class InvalidAuthenticationResponse(Exception): + pass + + +class InvalidPublicKeyStructure(Exception): + pass + + +class UnsupportedPublicKeyType(Exception): + pass + + +class InvalidClientDataJSONStructure(Exception): + pass + + +class InvalidAuthenticatorDataStructure(Exception): + pass + + +class SignatureVerificationException(Exception): + pass + + +class UnsupportedAlgorithm(Exception): + pass + + +class UnsupportedPublicKey(Exception): + pass + + +class UnsupportedEC2Curve(Exception): + pass + + +class InvalidTPMPubAreaStructure(Exception): + pass + + +class InvalidTPMCertInfoStructure(Exception): + pass + + +class InvalidCertificateChain(Exception): + pass diff --git a/webauthn/helpers/generate_challenge.py b/webauthn/helpers/generate_challenge.py new file mode 100644 index 0000000..2d679a9 --- /dev/null +++ b/webauthn/helpers/generate_challenge.py @@ -0,0 +1,8 @@ +import secrets + + +def generate_challenge(length: int = 64) -> bytes: + """ + Generate a random authenticator challenge + """ + return secrets.token_bytes(length) diff --git a/webauthn/helpers/generate_user_handle.py b/webauthn/helpers/generate_user_handle.py new file mode 100644 index 0000000..08bad5b --- /dev/null +++ b/webauthn/helpers/generate_user_handle.py @@ -0,0 +1,17 @@ +import secrets + + +def generate_user_handle() -> bytes: + """ + Convenience method RP's can use to generate a privacy-preserving random sequence of + bytes as per best practices defined in the WebAuthn spec. This value is intended to + be used as the value of `user_id` when calling `generate_registration_options()`, + and can then be used during authentication verification to match the credential to + a user. + + See https://www.w3.org/TR/webauthn-2/#sctn-user-handle-privacy: + + "It is RECOMMENDED to let the user handle be 64 random bytes, and store this value + in the user’s account." + """ + return secrets.token_bytes(64) diff --git a/webauthn/helpers/hash_by_alg.py b/webauthn/helpers/hash_by_alg.py new file mode 100644 index 0000000..0b65ffa --- /dev/null +++ b/webauthn/helpers/hash_by_alg.py @@ -0,0 +1,41 @@ +import hashlib +from typing import Optional + +from .cose import COSEAlgorithmIdentifier + +SHA_256 = [ + COSEAlgorithmIdentifier.ECDSA_SHA_256, + COSEAlgorithmIdentifier.RSASSA_PSS_SHA_256, + COSEAlgorithmIdentifier.RSASSA_PKCS1_v1_5_SHA_256, +] +SHA_384 = [ + COSEAlgorithmIdentifier.RSASSA_PSS_SHA_384, + COSEAlgorithmIdentifier.RSASSA_PKCS1_v1_5_SHA_384, +] +SHA_512 = [ + COSEAlgorithmIdentifier.ECDSA_SHA_512, + COSEAlgorithmIdentifier.RSASSA_PSS_SHA_512, + COSEAlgorithmIdentifier.RSASSA_PKCS1_v1_5_SHA_512, +] +SHA_1 = [ + COSEAlgorithmIdentifier.RSASSA_PKCS1_v1_5_SHA_1, +] + + +def hash_by_alg(to_hash: bytes, alg: Optional[COSEAlgorithmIdentifier] = None) -> bytes: + """ + Generate a hash of `to_hash` by the specified COSE algorithm ID. Defaults to hashing + with SHA256 + """ + # Default to SHA256 for hashing + hash = hashlib.sha256() + + if alg in SHA_384: + hash = hashlib.sha384() + elif alg in SHA_512: + hash = hashlib.sha512() + elif alg in SHA_1: + hash = hashlib.sha1() + + hash.update(to_hash) + return hash.digest() diff --git a/webauthn/helpers/json_loads_base64url_to_bytes.py b/webauthn/helpers/json_loads_base64url_to_bytes.py new file mode 100644 index 0000000..1a130f9 --- /dev/null +++ b/webauthn/helpers/json_loads_base64url_to_bytes.py @@ -0,0 +1,39 @@ +import json +from typing import Any, Union + +from .base64url_to_bytes import base64url_to_bytes + + +def _object_hook_base64url_to_bytes(orig_dict: dict) -> dict: + """ + A function for the `object_hook` argument in json.loads() that knows which fields in + an incoming JSON string need to be converted from Base64URL to bytes. + """ + # Registration and Authentication + if "rawId" in orig_dict: + orig_dict["rawId"] = base64url_to_bytes(orig_dict["rawId"]) + if "clientDataJSON" in orig_dict: + orig_dict["clientDataJSON"] = base64url_to_bytes(orig_dict["clientDataJSON"]) + # Registration + if "attestationObject" in orig_dict: + orig_dict["attestationObject"] = base64url_to_bytes( + orig_dict["attestationObject"] + ) + # Authentication + if "authenticatorData" in orig_dict: + orig_dict["authenticatorData"] = base64url_to_bytes( + orig_dict["authenticatorData"] + ) + if "signature" in orig_dict: + orig_dict["signature"] = base64url_to_bytes(orig_dict["signature"]) + if "userHandle" in orig_dict: + orig_dict["userHandle"] = base64url_to_bytes(orig_dict["userHandle"]) + return orig_dict + + +def json_loads_base64url_to_bytes(input: Union[str, bytes]) -> Any: + """ + Wrap `json.loads()` with a custom object_hook that knows which dict keys to convert + from Base64URL to bytes when converting from JSON to Pydantic model + """ + return json.loads(input, object_hook=_object_hook_base64url_to_bytes) diff --git a/webauthn/helpers/known_root_certs.py b/webauthn/helpers/known_root_certs.py new file mode 100644 index 0000000..6d93e43 --- /dev/null +++ b/webauthn/helpers/known_root_certs.py @@ -0,0 +1,199 @@ +####################################### +# +# Google Hardware Attestation Root 1 +# +# Downloaded from https://developer.android.com/training/articles/security-key-attestation#root_certificate +# (first entry) +# +# Valid until 2026-05-24 @ 09:28 PST +# +# SHA256 Fingerprint +# C1:98:4A:3E:F4:5C:1E:2A:91:85:51:DE:10:60:3C:86:F7:05:1B:22:49:C4:89:1C:AE:32:30:EA:BD:0C:97:D5 +# +####################################### +google_hardware_attestation_root_1 = """-----BEGIN CERTIFICATE----- +MIIFYDCCA0igAwIBAgIJAOj6GWMU0voYMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV +BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMTYwNTI2MTYyODUyWhcNMjYwNTI0MTYy +ODUyWjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B +AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS +Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7 +tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj +nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq +C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ +oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O +JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg +sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi +igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M +RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E +aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um +AGMCAwEAAaOBpjCBozAdBgNVHQ4EFgQUNmHhAHyIBQlRi0RsR/8aTMnqTxIwHwYD +VR0jBBgwFoAUNmHhAHyIBQlRi0RsR/8aTMnqTxIwDwYDVR0TAQH/BAUwAwEB/zAO +BgNVHQ8BAf8EBAMCAYYwQAYDVR0fBDkwNzA1oDOgMYYvaHR0cHM6Ly9hbmRyb2lk +Lmdvb2dsZWFwaXMuY29tL2F0dGVzdGF0aW9uL2NybC8wDQYJKoZIhvcNAQELBQAD +ggIBACDIw41L3KlXG0aMiS//cqrG+EShHUGo8HNsw30W1kJtjn6UBwRM6jnmiwfB +Pb8VA91chb2vssAtX2zbTvqBJ9+LBPGCdw/E53Rbf86qhxKaiAHOjpvAy5Y3m00m +qC0w/Zwvju1twb4vhLaJ5NkUJYsUS7rmJKHHBnETLi8GFqiEsqTWpG/6ibYCv7rY +DBJDcR9W62BW9jfIoBQcxUCUJouMPH25lLNcDc1ssqvC2v7iUgI9LeoM1sNovqPm +QUiG9rHli1vXxzCyaMTjwftkJLkf6724DFhuKug2jITV0QkXvaJWF4nUaHOTNA4u +JU9WDvZLI1j83A+/xnAJUucIv/zGJ1AMH2boHqF8CY16LpsYgBt6tKxxWH00XcyD +CdW2KlBCeqbQPcsFmWyWugxdcekhYsAWyoSf818NUsZdBWBaR/OukXrNLfkQ79Iy +ZohZbvabO/X+MVT3rriAoKc8oE2Uws6DF+60PV7/WIPjNvXySdqspImSN78mflxD +qwLqRBYkA3I75qppLGG9rp7UCdRjxMl8ZDBld+7yvHVgt1cVzJx9xnyGCC23Uaic +MDSXYrB4I4WHXPGjxhZuCuPBLTdOLU8YRvMYdEvYebWHMpvwGCF6bAx3JBpIeOQ1 +wDB5y0USicV3YgYGmi+NZfhA4URSh77Yd6uuJOJENRaNVTzk +-----END CERTIFICATE----- +""".encode( + "ascii" +) + +####################################### +# +# Google Hardware Attestation Root 2 +# +# Downloaded from https://developer.android.com/training/articles/security-key-attestation#root_certificate +# (second entry) +# +# Valid until 2034-11-18 @ 12:37 PST +# +# SHA256 Fingerprint +# 1E:F1:A0:4B:8B:A5:8A:B9:45:89:AC:49:8C:89:82:A7:83:F2:4E:A7:30:7E:01:59:A0:C3:A7:3B:37:7D:87:CC +# +####################################### +google_hardware_attestation_root_2 = """-----BEGIN CERTIFICATE----- +MIIFHDCCAwSgAwIBAgIJANUP8luj8tazMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV +BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMTkxMTIyMjAzNzU4WhcNMzQxMTE4MjAz +NzU4WjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B +AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS +Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7 +tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj +nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq +C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ +oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O +JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg +sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi +igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M +RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E +aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um +AGMCAwEAAaNjMGEwHQYDVR0OBBYEFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMB8GA1Ud +IwQYMBaAFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMA8GA1UdEwEB/wQFMAMBAf8wDgYD +VR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4ICAQBOMaBc8oumXb2voc7XCWnu +XKhBBK3e2KMGz39t7lA3XXRe2ZLLAkLM5y3J7tURkf5a1SutfdOyXAmeE6SRo83U +h6WszodmMkxK5GM4JGrnt4pBisu5igXEydaW7qq2CdC6DOGjG+mEkN8/TA6p3cno +L/sPyz6evdjLlSeJ8rFBH6xWyIZCbrcpYEJzXaUOEaxxXxgYz5/cTiVKN2M1G2ok +QBUIYSY6bjEL4aUN5cfo7ogP3UvliEo3Eo0YgwuzR2v0KR6C1cZqZJSTnghIC/vA +D32KdNQ+c3N+vl2OTsUVMC1GiWkngNx1OO1+kXW+YTnnTUOtOIswUP/Vqd5SYgAI +mMAfY8U9/iIgkQj6T2W6FsScy94IN9fFhE1UtzmLoBIuUFsVXJMTz+Jucth+IqoW +Fua9v1R93/k98p41pjtFX+H8DslVgfP097vju4KDlqN64xV1grw3ZLl4CiOe/A91 +oeLm2UHOq6wn3esB4r2EIQKb6jTVGu5sYCcdWpXr0AUVqcABPdgL+H7qJguBw09o +jm6xNIrw2OocrDKsudk/okr/AwqEyPKw9WnMlQgLIKw1rODG2NvU9oR3GVGdMkUB +ZutL8VuFkERQGt6vQ2OCw0sV47VMkuYbacK/xyZFiRcrPJPb41zgbQj9XAEyLKCH +ex0SdDrx+tWUDqG8At2JHA== +-----END CERTIFICATE----- +""".encode( + "ascii" +) + +####################################### +# +# GlobalSign Root CA +# +# Downloaded from https://pki.goog/roots.pem +# +# Valid until 2028-01-28 @ 04:00 PST +# +# SHA256 Fingerprint +# EB:D4:10:40:E4:BB:3E:C7:42:C9:E3:81:D3:1E:F2:A4:1A:48:B6:68:5C:96:E7:CE:F3:C1:DF:6C:D4:33:1C:99 +# +####################################### +globalsign_root_ca = """-----BEGIN CERTIFICATE----- +MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG +A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv +b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw +MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i +YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT +aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ +jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp +xy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp +1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG +snUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ +U26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8 +9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E +BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B +AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz +yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE +38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP +AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad +DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME +HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A== +-----END CERTIFICATE----- +""".encode( + "ascii" +) + +####################################### +# +# GlobalSign R2 +# +# Downloaded from https://pki.goog/repo/certs/gsr2.pem +# +# Valid until 2021-12-15 @ 00:00 PST +# +# SHA256 Fingerprint +# 69:E2:D0:6C:30:F3:66:16:61:65:E9:1D:68:D1:CE:E5:CC:47:58:4A:80:22:7E:76:66:60:86:C0:10:72:41:EB +# +####################################### +globalsign_r2 = """-----BEGIN CERTIFICATE----- +MIIDvDCCAqSgAwIBAgINAgPk9GHsmdnVeWbKejANBgkqhkiG9w0BAQUFADBMMSAw +HgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMjETMBEGA1UEChMKR2xvYmFs +U2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjAeFw0wNjEyMTUwODAwMDBaFw0yMTEy +MTUwODAwMDBaMEwxIDAeBgNVBAsTF0dsb2JhbFNpZ24gUm9vdCBDQSAtIFIyMRMw +EQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWduMIIBIjANBgkq +hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAps8kDr4ubyiZRULEqz4hVJsL03+EcPoS +s8u/h1/Gf4bTsjBc1v2t8Xvc5fhglgmSEPXQU977e35ziKxSiHtKpspJpl6op4xa +Ebx6guu+jOmzrJYlB5dKmSoHL7Qed7+KD7UCfBuWuMW5Oiy81hK561l94tAGhl9e +SWq1OV6INOy8eAwImIRsqM1LtKB9DHlN8LgtyyHK1WxbfeGgKYSh+dOUScskYpEg +vN0L1dnM+eonCitzkcadG6zIy+jgoPQvkItN+7A2G/YZeoXgbfJhE4hcn+CTClGX +ilrOr6vV96oJqmC93Nlf33KpYBNeAAHJSvo/pOoHAyECjoLKA8KbjwIDAQABo4Gc +MIGZMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSb +4gdXZxwewGoG3lm0mi3f3BmGLjAfBgNVHSMEGDAWgBSb4gdXZxwewGoG3lm0mi3f +3BmGLjA2BgNVHR8ELzAtMCugKaAnhiVodHRwOi8vY3JsLmdsb2JhbHNpZ24ubmV0 +L3Jvb3QtcjIuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQANeX81Z1YqDIs4EaLjG0qP +OxIzaJI/y4kiRj3a+y3KOx74clIkLuMgi/9/5iv/n+1LyhGU9g7174slbzJOPbSp +p1eT19ST2mYbdgTLx/hm3tTLoHIY/w4ZbnQYwfnPwAG4RefnEFYPQJmpD+Wh8BJw +Bgtm2drTale/T6NBwmwnEFunfaMfMX3g6IBrx7VKnxIkJh/3p190WveLKgl9n7i5 +SWce/4woPimEn9WfEQWRvp6wKhaCKFjuCMuulEZusoOUJ4LfJnXxcuQTgIrSnwI7 +KfSSjsd42w3lX1fbgJp7vPmLM6OBRvAXuYRKTFqMAWbb7OaGIEE+cbxY6PDepnva +-----END CERTIFICATE----- +""".encode( + "ascii" +) + +####################################### +# +# Apple WebAuthn Root CA +# +# Downloaded from https://www.apple.com/certificateauthority/Apple_WebAuthn_Root_CA.pem +# +# Valid until 2045-03-14 @ 17:00 PST +# +# SHA256 Fingerprint +# 09:15:DD:5C:07:A2:8D:B5:49:D1:F6:77:BB:5A:75:D4:BF:BE:95:61:A7:73:42:43:27:76:2E:9E:02:F9:BB:29 +# +####################################### +apple_webauthn_root_ca = """-----BEGIN CERTIFICATE----- +MIICEjCCAZmgAwIBAgIQaB0BbHo84wIlpQGUKEdXcTAKBggqhkjOPQQDAzBLMR8w +HQYDVQQDDBZBcHBsZSBXZWJBdXRobiBSb290IENBMRMwEQYDVQQKDApBcHBsZSBJ +bmMuMRMwEQYDVQQIDApDYWxpZm9ybmlhMB4XDTIwMDMxODE4MjEzMloXDTQ1MDMx +NTAwMDAwMFowSzEfMB0GA1UEAwwWQXBwbGUgV2ViQXV0aG4gUm9vdCBDQTETMBEG +A1UECgwKQXBwbGUgSW5jLjETMBEGA1UECAwKQ2FsaWZvcm5pYTB2MBAGByqGSM49 +AgEGBSuBBAAiA2IABCJCQ2pTVhzjl4Wo6IhHtMSAzO2cv+H9DQKev3//fG59G11k +xu9eI0/7o6V5uShBpe1u6l6mS19S1FEh6yGljnZAJ+2GNP1mi/YK2kSXIuTHjxA/ +pcoRf7XkOtO4o1qlcaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUJtdk +2cV4wlpn0afeaxLQG2PxxtcwDgYDVR0PAQH/BAQDAgEGMAoGCCqGSM49BAMDA2cA +MGQCMFrZ+9DsJ1PW9hfNdBywZDsWDbWFp28it1d/5w2RPkRX3Bbn/UbDTNLx7Jr3 +jAGGiQIwHFj+dJZYUJR786osByBelJYsVZd2GbHQu209b5RCmGQ21gpSAk9QZW4B +1bWeT0vT +-----END CERTIFICATE----- +""".encode( + "ascii" +) diff --git a/webauthn/helpers/options_to_json.py b/webauthn/helpers/options_to_json.py new file mode 100644 index 0000000..b915087 --- /dev/null +++ b/webauthn/helpers/options_to_json.py @@ -0,0 +1,22 @@ +from typing import Union + +from .structs import ( + PublicKeyCredentialCreationOptions, + PublicKeyCredentialRequestOptions, +) + + +def options_to_json( + options: Union[ + PublicKeyCredentialCreationOptions, + PublicKeyCredentialRequestOptions, + ] +) -> str: + """ + Prepare options for transmission to the front end as JSON + """ + return options.json( + by_alias=True, + skip_defaults=False, + exclude_none=True, + ) diff --git a/webauthn/helpers/parse_attestation_object.py b/webauthn/helpers/parse_attestation_object.py new file mode 100644 index 0000000..042899a --- /dev/null +++ b/webauthn/helpers/parse_attestation_object.py @@ -0,0 +1,25 @@ +import cbor2 + +from .parse_attestation_statement import parse_attestation_statement +from .parse_authenticator_data import parse_authenticator_data +from .structs import AttestationObject + + +def parse_attestation_object(val: bytes) -> AttestationObject: + """ + Decode and peel apart the CBOR-encoded blob `response.attestationObject` into + structured data. + """ + attestation_dict = cbor2.loads(val) + + decoded_attestation_object = AttestationObject( + fmt=attestation_dict["fmt"], + auth_data=parse_authenticator_data(attestation_dict["authData"]), + ) + + if "attStmt" in attestation_dict: + decoded_attestation_object.att_stmt = parse_attestation_statement( + attestation_dict["attStmt"] + ) + + return decoded_attestation_object diff --git a/webauthn/helpers/parse_attestation_statement.py b/webauthn/helpers/parse_attestation_statement.py new file mode 100644 index 0000000..6d53d26 --- /dev/null +++ b/webauthn/helpers/parse_attestation_statement.py @@ -0,0 +1,26 @@ +from .structs import AttestationStatement + + +def parse_attestation_statement(val: dict) -> AttestationStatement: + """ + Turn `response.attestationObject.attStmt` into structured data + """ + attestation_statement = AttestationStatement() + + # Populate optional fields that may exist in the attestation statement + if "sig" in val: + attestation_statement.sig = val["sig"] + if "x5c" in val: + attestation_statement.x5c = val["x5c"] + if "response" in val: + attestation_statement.response = val["response"] + if "alg" in val: + attestation_statement.alg = val["alg"] + if "ver" in val: + attestation_statement.ver = val["ver"] + if "certInfo" in val: + attestation_statement.cert_info = val["certInfo"] + if "pubArea" in val: + attestation_statement.pub_area = val["pubArea"] + + return attestation_statement diff --git a/webauthn/helpers/parse_authenticator_data.py b/webauthn/helpers/parse_authenticator_data.py new file mode 100644 index 0000000..47866a5 --- /dev/null +++ b/webauthn/helpers/parse_authenticator_data.py @@ -0,0 +1,66 @@ +from .exceptions import InvalidAuthenticatorDataStructure +from .structs import AttestedCredentialData, AuthenticatorData, AuthenticatorDataFlags + + +def parse_authenticator_data(val: bytes) -> AuthenticatorData: + """ + Turn `response.attestationObject.authData` into structured data + """ + # Don't bother parsing if there aren't enough bytes for at least: + # - rpIdHash (32 bytes) + # - flags (1 byte) + # - signCount (4 bytes) + if len(val) < 37: + raise InvalidAuthenticatorDataStructure( + f"Authenticator data was {len(val)} bytes, expected at least 37 bytes" + ) + + pointer = 0 + + rp_id_hash = val[pointer:32] + pointer += 32 + + # Cast byte to ordinal so we can use bitwise operators on it + flags_bytes = ord(val[pointer : pointer + 1]) + pointer += 1 + + sign_count = val[pointer : pointer + 4] + pointer += 4 + + # Parse flags + flags = AuthenticatorDataFlags( + up=flags_bytes & (1 << 0) != 0, + uv=flags_bytes & (1 << 2) != 0, + at=flags_bytes & (1 << 6) != 0, + ed=flags_bytes & (1 << 7) != 0, + ) + + # The value to return + authenticator_data = AuthenticatorData( + rp_id_hash=rp_id_hash, + flags=flags, + sign_count=int.from_bytes(sign_count, "big"), + ) + + # Parse AttestedCredentialData if present + if flags.at is True: + aaguid = val[pointer : pointer + 16] + pointer += 16 + + credential_id_len = int.from_bytes(val[pointer : pointer + 2], "big") + pointer += 2 + + credential_id = val[pointer : pointer + credential_id_len] + pointer += credential_id_len + + # The remainder of the bytes will be the credential public key + credential_public_key = val[pointer:] + + attested_cred_data = AttestedCredentialData( + aaguid=aaguid, + credential_id=credential_id, + credential_public_key=credential_public_key, + ) + authenticator_data.attested_credential_data = attested_cred_data + + return authenticator_data diff --git a/webauthn/helpers/parse_client_data_json.py b/webauthn/helpers/parse_client_data_json.py new file mode 100644 index 0000000..152b517 --- /dev/null +++ b/webauthn/helpers/parse_client_data_json.py @@ -0,0 +1,73 @@ +import json +from json.decoder import JSONDecodeError + +from pydantic import ValidationError + +from .base64url_to_bytes import base64url_to_bytes +from .exceptions import InvalidClientDataJSONStructure +from .structs import CollectedClientData, TokenBinding + + +def parse_client_data_json(val: bytes) -> CollectedClientData: + """ + Break apart `response.clientDataJSON` buffer into structured data + """ + try: + json_dict = json.loads(val) + except JSONDecodeError: + raise InvalidClientDataJSONStructure( + "Unable to decode client_data_json bytes as JSON" + ) + + # Ensure required values are present in client data + if "type" not in json_dict: + raise InvalidClientDataJSONStructure( + 'client_data_json missing required property "type"' + ) + if "challenge" not in json_dict: + raise InvalidClientDataJSONStructure( + 'client_data_json missing required property "challenge"' + ) + if "origin" not in json_dict: + raise InvalidClientDataJSONStructure( + 'client_data_json missing required property "origin"' + ) + + client_data = CollectedClientData( + type=json_dict["type"], + challenge=base64url_to_bytes(json_dict["challenge"]), + origin=json_dict["origin"], + ) + + # Populate optional values if set + if "crossOrigin" in json_dict: + cross_origin = bool(json_dict["crossOrigin"]) + client_data.cross_origin = cross_origin + + if "tokenBinding" in json_dict: + token_binding_dict = json_dict["tokenBinding"] + + # Some U2F devices set a string to `token_binding`, in which case ignore it + if type(token_binding_dict) is dict: + if "status" not in token_binding_dict: + raise InvalidClientDataJSONStructure( + 'token_binding missing required property "status"' + ) + + status = token_binding_dict["status"] + try: + # This will raise ValidationError on an unexpected status + token_binding = TokenBinding(status=status) + + # Handle optional values + if "id" in token_binding_dict: + id = token_binding_dict["id"] + token_binding.id = f"{id}" + + client_data.token_binding = token_binding + except ValidationError: + # If we encounter a status we don't expect then ignore token_binding + # completely + pass + + return client_data diff --git a/webauthn/helpers/pem_cert_bytes_to_open_ssl_x509.py b/webauthn/helpers/pem_cert_bytes_to_open_ssl_x509.py new file mode 100644 index 0000000..67b1d79 --- /dev/null +++ b/webauthn/helpers/pem_cert_bytes_to_open_ssl_x509.py @@ -0,0 +1,12 @@ +from cryptography.hazmat.backends import default_backend +from cryptography.x509 import load_pem_x509_certificate +from OpenSSL.crypto import X509 + + +def pem_cert_bytes_to_open_ssl_x509(cert: bytes) -> X509: + """Convert PEM-formatted certificate bytes into an X509 instance usable for cert + chain validation + """ + cert_crypto = load_pem_x509_certificate(cert, default_backend()) + cert_openssl = X509().from_cryptography(cert_crypto) + return cert_openssl diff --git a/webauthn/helpers/snake_case_to_camel_case.py b/webauthn/helpers/snake_case_to_camel_case.py new file mode 100644 index 0000000..3a76787 --- /dev/null +++ b/webauthn/helpers/snake_case_to_camel_case.py @@ -0,0 +1,14 @@ +def snake_case_to_camel_case(snake_case: str) -> str: + """ + Helper method for converting a snake_case'd value to camelCase + + input: pub_key_cred_params + output: pubKeyCredParams + """ + parts = snake_case.split("_") + converted = parts[0].lower() + "".join(part.title() for part in parts[1:]) + + # Massage "clientDataJson" to "clientDataJSON" + converted = converted.replace("Json", "JSON") + + return converted diff --git a/webauthn/helpers/structs.py b/webauthn/helpers/structs.py new file mode 100644 index 0000000..21c5641 --- /dev/null +++ b/webauthn/helpers/structs.py @@ -0,0 +1,514 @@ +from enum import Enum +from typing import List, Literal, Optional + +from pydantic import BaseModel + +from .bytes_to_base64url import bytes_to_base64url +from .cose import COSEAlgorithmIdentifier +from .json_loads_base64url_to_bytes import json_loads_base64url_to_bytes +from .snake_case_to_camel_case import snake_case_to_camel_case + + +class WebAuthnBaseModel(BaseModel): + """ + A subclass of Pydantic's BaseModel that includes convenient defaults + when working with WebAuthn data structures + + `modelInstance.json()` (to JSON): + - Encodes bytes to Base64URL + - Converts snake_case properties to camelCase + + `Model.parse_raw()` (from JSON): + - Decodes Base64URL to bytes + - Converts camelCase properties to snake_case + """ + + class Config: + json_encoders = {bytes: bytes_to_base64url} + json_loads = json_loads_base64url_to_bytes + alias_generator = snake_case_to_camel_case + allow_population_by_field_name = True + + +################ +# +# Fundamental data structures +# +################ + + +class AuthenticatorTransport(str, Enum): + """How an authenticator communicates to the client/browser. + + Members: + `USB`: USB wired connection + `NFC`: Near Field Communication + `BLE`: Bluetooth Low Energy + `INTERNAL`: Direct connection (read: a platform authenticator) + + https://www.w3.org/TR/webauthn-2/#enum-transport + """ + + USB = "usb" + NFC = "nfc" + BLE = "ble" + INTERNAL = "internal" + + +class AuthenticatorAttachment(str, Enum): + """How an authenticator is connected to the client/browser. + + Members: + `PLATFORM`: A non-removable authenticator, like TouchID or Windows Hello + `CROSS_PLATFORM`: A "roaming" authenticator, like a YubiKey + + https://www.w3.org/TR/webauthn-2/#enumdef-authenticatorattachment + """ + + PLATFORM = "platform" + CROSS_PLATFORM = "cross-platform" + + +class ResidentKeyRequirement(str, Enum): + """The Relying Party's preference for the authenticator to create a dedicated "client-side" credential for it. Requiring an authenticator to store a dedicated credential should not be done lightly due to the limited storage capacity of some types of authenticators. + + Members: + `DISCOURAGED`: The authenticator should not create a dedicated credential + `PREFERRED`: The authenticator can create and store a dedicated credential, but if it doesn't that's alright too + `REQUIRED`: The authenticator MUST create a dedicated credential. If it cannot, the RP is prepared for an error to occur. + + https://www.w3.org/TR/webauthn-2/#enum-residentKeyRequirement + """ + + DISCOURAGED = "discouraged" + PREFERRED = "preferred" + REQUIRED = "required" + + +class UserVerificationRequirement(str, Enum): + """The degree to which the Relying Party wishes to verify a user's identity. + + Members: + `REQUIRED`: User verification must occur + `PREFERRED`: User verification would be great, but if not that's okay too + `DISCOURAGED`: User verification should not occur, but it's okay if it does + + https://www.w3.org/TR/webauthn-2/#enumdef-userverificationrequirement + """ + + REQUIRED = "required" + PREFERRED = "preferred" + DISCOURAGED = "discouraged" + + +class AttestationConveyancePreference(str, Enum): + """The Relying Party's interest in receiving an attestation statement. + + Members: + `NONE`: The Relying Party isn't interested in receiving an attestation statement + `INDIRECT`: The Relying Party is interested in an attestation statement, but the client is free to generate it as it sees fit + `DIRECT`: The Relying Party is interested in an attestation statement generated directly by the authenticator + `ENTERPRISE`: The Relying Party is interested in a statement with identifying information. Typically used within organizations + + https://www.w3.org/TR/webauthn-2/#enum-attestation-convey + """ + + NONE = "none" + INDIRECT = "indirect" + DIRECT = "direct" + ENTERPRISE = "enterprise" + + +class PublicKeyCredentialType(str, Enum): + """The type of credential that should be returned by an authenticator. There's but a single member because this is a specific subclass of a higher-level `CredentialType` that can be of other types. + + Members: + `PUBLIC_KEY`: The literal string `"public-key"` + + https://www.w3.org/TR/webauthn-2/#enumdef-publickeycredentialtype + """ + + PUBLIC_KEY = "public-key" + + +class AttestationFormat(str, Enum): + """The "syntax" of an attestation statement. Formats should be registered with the IANA and include documented signature verification steps. + + Members: + `PACKED` + `TPM` + `ANDROID_KEY` + `ANDROID_SAFETYNET` + `FIDO_U2F` + `APPLE` + `NONE` + + https://www.iana.org/assignments/webauthn/webauthn.xhtml + """ + + PACKED = "packed" + TPM = "tpm" + ANDROID_KEY = "android-key" + ANDROID_SAFETYNET = "android-safetynet" + FIDO_U2F = "fido-u2f" + APPLE = "apple" + NONE = "none" + + +class ClientDataType(str, Enum): + """Specific values included in authenticator registration and authentication responses to help avoid certain types of "signature confusion attacks". + + Members: + `WEBAUTHN_CREATE`: The string "webauthn.create". Synonymous with `navigator.credentials.create()` in the browser + `WEBAUTHN_GET`: The string "webauthn.get". Synonymous with `navigator.credentials.get()` in the browser + + https://www.w3.org/TR/webauthn-2/#dom-collectedclientdata-type + """ + + WEBAUTHN_CREATE = "webauthn.create" + WEBAUTHN_GET = "webauthn.get" + + +class TokenBindingStatus(str, Enum): + """ + https://www.w3.org/TR/webauthn-2/#dom-tokenbinding-status + """ + + PRESENT = "present" + SUPPORTED = "supported" + + +class TokenBinding(BaseModel): + """ + https://www.w3.org/TR/webauthn-2/#dictdef-tokenbinding + """ + + status: TokenBindingStatus + id: Optional[str] + + +class PublicKeyCredentialRpEntity(WebAuthnBaseModel): + """Information about the Relying Party. + + Attributes: + `name`: A user-readable name for the Relying Party + `id`: A unique, constant value assigned to the Relying Party. Authenticators use this value to associate a credential with a particular Relying Party user + + https://www.w3.org/TR/webauthn-2/#dictdef-publickeycredentialrpentity + """ + + name: str + id: Optional[str] + + +class PublicKeyCredentialUserEntity(WebAuthnBaseModel): + """Information about a user of a Relying Party. + + Attributes: + `id`: An "opaque byte sequence" that uniquely identifies a user. Typically something like a UUID, but never user-identifying like an email address. Cannot exceed 64 bytes. + `name`: A value which a user can see to determine which account this credential is associated with. A username or email address is fine here. + `display_name`: A user-friendly representation of a user, like a full name. + + https://www.w3.org/TR/webauthn-2/#dictdef-publickeycredentialuserentity + """ + + id: bytes + name: str + display_name: str + + +class PublicKeyCredentialParameters(WebAuthnBaseModel): + """Information about a cryptographic algorithm that may be used when creating a credential. + + Attributes: + `type`: The literal string `"public-key"` + `alg`: A numeric indicator of a particular algorithm + + https://www.w3.org/TR/webauthn-2/#dictdef-publickeycredentialparameters + """ + + type: Literal["public-key"] + alg: COSEAlgorithmIdentifier + + +class PublicKeyCredentialDescriptor(WebAuthnBaseModel): + """Information about a generated credential. + + Attributes: + `type`: The literal string `"public-key"` + `id`: The sequence of bytes representing the credential's ID + (optional) `transports`: The types of connections to the client/browser the authenticator supports + + https://www.w3.org/TR/webauthn-2/#dictdef-publickeycredentialdescriptor + """ + + type: Literal[ + PublicKeyCredentialType.PUBLIC_KEY + ] = PublicKeyCredentialType.PUBLIC_KEY + id: bytes + transports: Optional[List[AuthenticatorTransport]] = None + + +class AuthenticatorSelectionCriteria(WebAuthnBaseModel): + """A Relying Party's requirements for the types of authenticators that may interact with the client/browser. + + Attributes: + (optional) `authenticator_attachment`: How the authenticator can be connected to the client/browser + (optional) `resident_key`: Whether the authenticator should be able to store a credential on itself + (optional) `require_resident_key`: DEPRECATED, set a value for `resident_key` instead + (optional) `user_verification`: How the authenticator should be capable of determining user identity + + https://www.w3.org/TR/webauthn-2/#dictdef-authenticatorselectioncriteria + """ + + authenticator_attachment: Optional[AuthenticatorAttachment] + resident_key: Optional[ResidentKeyRequirement] + require_resident_key: Optional[bool] = False + user_verification: Optional[ + UserVerificationRequirement + ] = UserVerificationRequirement.PREFERRED + + +class CollectedClientData(BaseModel): + """Decoded ClientDataJSON + + Attributes: + `type`: Either `"webauthn.create"` or `"webauthn.get"`, for registration and authentication ceremonies respectively + `challenge`: The challenge passed to the authenticator within the options + `origin`: The base domain with protocol on which the registration or authentication ceremony took place (e.g. "https://foo.bar") + (optional) `cross_origin`: Whether or not the the registration or authentication ceremony took place on a different origin (think within an