Refuse a kiosk caller wearing an address that belongs to the path
Both kiosks admit a check-in or check-out with no login when the caller sits in a configured network. The subtraction that makes that safe was missing. A reverse proxy normally sits ON the plant network a site enters in the allowlist. When the proxy forwards nothing - misconfigured, or something bypassed it - the request arrives wearing the proxy's own address, which matches the allowlist, while carrying no evidence whatever about who sent it. That is the one case that has to refuse, and it was being admitted. The previous fail-closed test only looked closed because the proxy in it happened to sit outside the range. Addresses that belong to the path are now subtracted before the allowlist is consulted: loopback always, since no site's kiosk is the server itself, plus whatever the site declares as its proxies. USB and printedparts get the same treatment - they had diverged for no reason anybody chose. Three more, same surface: A range that admits everybody can no longer be saved by accident. 0.0.0.0/0 and ::/0 are refused outright, anything wider than a site plausibly needs is refused unless an explicit override is set, and the refusal says why. The kiosk token no longer travels in a URL. The provisioning link carries a single-use setup code redeemed on first open, so the token stays out of browser history, referrers and proxy logs. The route is declared public deliberately: the secret is the code, the way a password-reset link is the secret. The badge-to-name lookup is bounded. It answers without a login and is now reachable from a whole network rather than one screen, so a source that keeps missing gets refused rather than being allowed to walk the directory. On by default, budget and kill switch are settings. All four new settings carry controls on their settings pages. A setting that can stop the kiosk, or widen it, must not be reachable only by hand-editing rows. The installer's client-IP advice is corrected: it described the opposite of what the shipped waitress flags do, and named only GE-Enforce as the thing that breaks when the rule is absent, when the two kiosk allowlists depend on it too.
This commit is contained in:
@@ -20,13 +20,17 @@ cmmc_usb schema used here:
|
||||
'YYYY-MM-DD HH:MM:SS' string; scanned_viruses/sanitized are '0'|'1'|null.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import logging
|
||||
import re
|
||||
import secrets
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import hmac
|
||||
|
||||
from flask import Blueprint, request, Response
|
||||
from flask import Blueprint, current_app, redirect, request, Response
|
||||
from flask_jwt_extended import jwt_required
|
||||
|
||||
from shopdb.api import (
|
||||
@@ -39,7 +43,7 @@ from shopdb.api import (
|
||||
get_pagination_params,
|
||||
require_permission,
|
||||
)
|
||||
from shopdb.api import Setting, request_ip_allowlisted, audit_log, db
|
||||
from shopdb.api import Setting, audit_log, cache, client_ip, db, ip_in_cidrs
|
||||
|
||||
from . import selfhosted
|
||||
|
||||
@@ -743,23 +747,110 @@ def _kiosk_enabled():
|
||||
return _kiosk_setting('usb_kiosk_enabled', False)
|
||||
|
||||
|
||||
# The device token also travels as a cookie, set by the setup exchange below,
|
||||
# so it never has to sit in a URL to reach a screen.
|
||||
KIOSK_TOKEN_COOKIE = 'usbkiosktoken'
|
||||
|
||||
# Where this site's reverse proxies are, as CIDRs. NOT a source of addresses -
|
||||
# see the block below - but a subtraction from the allowlist: a request wearing
|
||||
# one of these addresses is infrastructure talking, never a caller.
|
||||
KIOSK_TRUSTED_PROXIES = 'usb_kiosk_trusted_proxies'
|
||||
|
||||
# Addresses that are never a kiosk client at any site, whatever was typed into
|
||||
# the allowlist. Loopback is the shipped Windows stack with no forwarding header
|
||||
# at all: HttpPlatformHandler connects from 127.0.0.1, waitress has nothing to
|
||||
# promote, and every caller then arrives wearing the app server's own address.
|
||||
KIOSK_NEVER_A_CLIENT = '127.0.0.0/8, ::1/128'
|
||||
|
||||
|
||||
def _kiosk_token_presented():
|
||||
"""True when the caller presents the configured device token.
|
||||
|
||||
The token is per-DEVICE. A kiosk is a browser on a screen by the cabinet, so
|
||||
a token served inside the page would be readable by anyone who could load
|
||||
it. An admin opens the screen once as /usb-kiosk?token=..., the page keeps
|
||||
it in that browser and sends it as X-Kiosk-Token.
|
||||
it.
|
||||
|
||||
Two carriers, one value. A screen provisioned the old way keeps it in
|
||||
localStorage and sends X-Kiosk-Token; a screen provisioned through
|
||||
kiosk_setup holds it in an HttpOnly cookie that the browser sends on its
|
||||
own. Accepting both is what lets the URL-borne token go away without
|
||||
reprovisioning every screen already on the floor.
|
||||
"""
|
||||
expected = (Setting.get('usb_kiosk_token') or '').strip()
|
||||
presented = (request.headers.get('X-Kiosk-Token') or '').strip()
|
||||
if not expected or not presented:
|
||||
if not expected:
|
||||
return False
|
||||
presented = ((request.headers.get('X-Kiosk-Token') or '').strip()
|
||||
or (request.cookies.get(KIOSK_TOKEN_COOKIE) or '').strip())
|
||||
if not presented:
|
||||
return False
|
||||
# compare_digest, not ==: == leaks the token's length and matching prefix
|
||||
# through timing.
|
||||
return hmac.compare_digest(presented, expected)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The address a caller is admitted on, traced through the stack that ships
|
||||
# ---------------------------------------------------------------------------
|
||||
# IIS -> HttpPlatformHandler -> waitress on 127.0.0.1 -> this app, and waitress
|
||||
# is launched with --trusted-proxy=127.0.0.1
|
||||
# --trusted-proxy-headers=x-forwarded-for --trusted-proxy-count=1
|
||||
# (deploy/windows/web.config). HttpPlatformHandler ALWAYS connects over
|
||||
# loopback, so waitress always sees its configured trusted proxy as the peer: it
|
||||
# takes the LAST X-Forwarded-For hop, writes it into REMOTE_ADDR, and truncates
|
||||
# the environ header to that one hop, all before Flask is entered.
|
||||
#
|
||||
# So request.remote_addr IS the forwarded address by the time anything here
|
||||
# runs, and X-Forwarded-For carries a single entry equal to it. That is why the
|
||||
# version of this code that walked the header could not work on the Windows
|
||||
# deployment: it looked for the peer inside usb_kiosk_trusted_proxies before it
|
||||
# would read the header, and the peer is never the proxy any more - waitress
|
||||
# already replaced it with whatever the proxy forwarded. The branch could not
|
||||
# fire, and the parsing under it was inert.
|
||||
#
|
||||
# THIS APP TAKES THE WSGI LAYER'S WORD, and the app-level parsing is gone. Not
|
||||
# because that word is trustworthy in itself, but because Python is the wrong
|
||||
# place to adjudicate it: the proxy's own address is destroyed before Flask is
|
||||
# reached, so nothing here can tell a hop IIS wrote from one a caller sent.
|
||||
# Whether the address is real is settled in front of waitress, and only there:
|
||||
# -ClientIpSource direct: the IIS rewrite rule OVERWRITES X-Forwarded-For with
|
||||
# IIS's own REMOTE_ADDR, so a caller-sent header is destroyed on arrival.
|
||||
# -ClientIpSource proxy: the reverse proxy APPENDS the caller, so the last hop
|
||||
# is the address that proxy itself observed.
|
||||
# Under either, a client-sent header cannot choose the value waitress promotes.
|
||||
# The installer checks this in both modes and, when it does not hold, says to
|
||||
# leave the kiosk allowlist empty (deploy/windows/installer/shopdb-install.ps1).
|
||||
#
|
||||
# Reading request.headers['X-Forwarded-For'] here would undo all of it: on a box
|
||||
# whose front end does not overwrite, that header is the caller's to invent, and
|
||||
# the kiosk would admit on a value the caller's network position does not
|
||||
# support. So it is not read. Anywhere in this file.
|
||||
|
||||
|
||||
def _kiosk_client_ip():
|
||||
"""The caller address, as the layer in front of Flask resolved it."""
|
||||
return client_ip(request)
|
||||
|
||||
|
||||
def _kiosk_address_is_infrastructure(address):
|
||||
"""True when this address belongs to the path, not to a caller.
|
||||
|
||||
The fail-closed half of network admission, and the half that was missing. A
|
||||
reverse proxy normally sits ON the plant network a site enters in
|
||||
usb_kiosk_allowed_cidrs. A request that arrives wearing the proxy's own
|
||||
address - because the proxy forwarded nothing, or because nothing forwarded
|
||||
at all - therefore MATCHED the allowlist and was admitted, while carrying no
|
||||
evidence whatever about who sent it. That is the one case that has to
|
||||
refuse.
|
||||
|
||||
Being inside the allowlist is not enough on its own: the address also has to
|
||||
be one a client could plausibly have had. The previous version only looked
|
||||
closed because the proxy in its test happened to sit outside the allowlist.
|
||||
"""
|
||||
if ip_in_cidrs(address, KIOSK_NEVER_A_CLIENT):
|
||||
return True
|
||||
return ip_in_cidrs(address, Setting.get(KIOSK_TRUSTED_PROXIES))
|
||||
|
||||
|
||||
def _kiosk_ip_allowlisted():
|
||||
"""True when the caller sits in the configured kiosk network allowlist.
|
||||
|
||||
@@ -770,11 +861,14 @@ def _kiosk_ip_allowlisted():
|
||||
cleared profile. Network position is what those callers actually have in
|
||||
common.
|
||||
|
||||
Fail-closed behaviour and the IIS rewrite-rule dependency that makes the
|
||||
caller address trustworthy are documented on request_ip_allowlisted.
|
||||
Fail-closed behaviour is documented on ip_in_cidrs; where the caller address
|
||||
comes from is on _kiosk_client_ip, and which addresses can never be a caller
|
||||
at all is on _kiosk_address_is_infrastructure.
|
||||
"""
|
||||
return request_ip_allowlisted(
|
||||
request, Setting.get('usb_kiosk_allowed_cidrs'))
|
||||
address = _kiosk_client_ip()
|
||||
if _kiosk_address_is_infrastructure(address):
|
||||
return False
|
||||
return ip_in_cidrs(address, Setting.get('usb_kiosk_allowed_cidrs'))
|
||||
|
||||
|
||||
def _kiosk_open():
|
||||
@@ -815,6 +909,298 @@ def _kiosk_badge(data):
|
||||
return badge, None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# What a site may store in a kiosk CIDR list
|
||||
# ---------------------------------------------------------------------------
|
||||
# These two settings decide who may write without logging in, and the settings
|
||||
# API stored whatever was typed: it checks valuetype and nothing else, and has
|
||||
# no per-key hook a plugin can declare. So '0.0.0.0/0' saved cleanly and turned
|
||||
# the kiosk into an open write for anything that could reach the server.
|
||||
#
|
||||
# Checked at the SAVE (see validate_kiosk_settings_write, registered by the
|
||||
# plugin), because that is the only moment an administrator finds out. Refusing
|
||||
# a range at admission time instead would look exactly like the setting quietly
|
||||
# not working.
|
||||
|
||||
KIOSK_CIDR_KEYS = ('usb_kiosk_allowed_cidrs', 'usb_kiosk_trusted_proxies')
|
||||
KIOSK_WIDE_OVERRIDE = 'usb_kiosk_allow_wide_cidrs'
|
||||
# A /16 is already 65,536 addresses. Anything wider is a claim about the site
|
||||
# that a site should have to make on purpose, not a typo that widens a door.
|
||||
KIOSK_MIN_PREFIX = {4: 16, 6: 48}
|
||||
|
||||
|
||||
def kiosk_cidr_problem(raw, allowwide=False):
|
||||
"""Why this CIDR list may not be stored, or None when it may.
|
||||
|
||||
The message names the entry and says what it would mean, because the person
|
||||
reading it is fixing a range on a settings page, not debugging a validator.
|
||||
"""
|
||||
for part in (raw or '').split(','):
|
||||
part = part.strip()
|
||||
if not part:
|
||||
continue
|
||||
try:
|
||||
network = ipaddress.ip_network(part, strict=False)
|
||||
except ValueError:
|
||||
return ('"{0}" is not a network. Use address/prefix, for example '
|
||||
'192.0.2.0/24.'.format(part))
|
||||
if network.prefixlen == 0:
|
||||
return ('"{0}" is every address there is. The kiosk writes without '
|
||||
'a login, so this would let anything that can reach the '
|
||||
'server move a drive against a badge it guessed. Name the '
|
||||
'shop-floor ranges instead.'.format(part))
|
||||
floor = KIOSK_MIN_PREFIX[network.version]
|
||||
if network.prefixlen < floor and not allowwide:
|
||||
return ('"{0}" covers {1} addresses, which is wider than a site '
|
||||
'range (/{2} or narrower). Everyone inside it is admitted '
|
||||
'with no token and no login. Narrow it, or turn on "{3}" '
|
||||
'if this site really is one flat network that '
|
||||
'wide.'.format(part, network.num_addresses, floor,
|
||||
KIOSK_WIDE_OVERRIDE))
|
||||
return None
|
||||
|
||||
|
||||
# Both settings routes are gated on this one permission. Named here because the
|
||||
# guard below has to apply the SAME gate the view would, and a guard that
|
||||
# guessed a weaker one would be the hole it is meant to close.
|
||||
SETTINGS_WRITE_PERMISSION = 'settings.edit'
|
||||
|
||||
|
||||
def _settings_write_refusal():
|
||||
"""The view's own 401/403 for this caller, or None when it may write.
|
||||
|
||||
A before_request runs ahead of the view, so it runs ahead of
|
||||
@require_permission too. That ordering leaked the validation rules: an
|
||||
anonymous PUT of '0.0.0.0/0' was answered 400 with the reason, while an
|
||||
anonymous PUT of a sane range fell through to the view and was answered 401.
|
||||
The difference is an oracle - anyone who could reach the app could walk the
|
||||
allowlist rules without ever holding an account.
|
||||
|
||||
So authentication decides first, by running the same decorator the view
|
||||
carries rather than a local imitation of it. Guest grants, scoped personal
|
||||
tokens and the admin bypass therefore behave identically here and there, and
|
||||
the response an unauthorized caller gets is the one it would have got if
|
||||
this guard did not exist.
|
||||
"""
|
||||
@require_permission(SETTINGS_WRITE_PERMISSION)
|
||||
def permitted():
|
||||
return None
|
||||
|
||||
return permitted()
|
||||
|
||||
|
||||
def validate_kiosk_settings_write():
|
||||
"""before_request guard on the core settings save, for the kiosk CIDR keys.
|
||||
|
||||
Registered app-wide by the plugin (init_app): the keys belong to this
|
||||
plugin, so this plugin is what knows a bad value, and returning a response
|
||||
from before_request answers the save without performing it.
|
||||
"""
|
||||
if request.endpoint not in ('settings.update_setting',
|
||||
'settings.create_setting'):
|
||||
return None
|
||||
data = request.get_json(silent=True) or {}
|
||||
if request.endpoint == 'settings.update_setting':
|
||||
key = (request.view_args or {}).get('key')
|
||||
else:
|
||||
key = data.get('key')
|
||||
if key not in KIOSK_CIDR_KEYS or 'value' not in data:
|
||||
return None
|
||||
refusal = _settings_write_refusal()
|
||||
if refusal is not None:
|
||||
return refusal
|
||||
# _kiosk_setting, not bool(Setting.get(...)): a row stored as a string holds
|
||||
# the word 'false', and bool('false') is True - which would turn the
|
||||
# override on for a site that had just turned it off.
|
||||
problem = kiosk_cidr_problem(str(data.get('value') or ''),
|
||||
_kiosk_setting(KIOSK_WIDE_OVERRIDE, False))
|
||||
if problem:
|
||||
return error_response(ErrorCodes.VALIDATION_ERROR, problem)
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Badge lookups: a bounded number of misses per caller
|
||||
# ---------------------------------------------------------------------------
|
||||
# Every kiosk call that takes a badge answers with the employee's NAME, which is
|
||||
# what makes the kiosk usable and also makes it a lookup table: a badge is a
|
||||
# short number, so a caller who is admitted can walk it. Admission used to mean
|
||||
# one screen by the cabinet; with the network allowlist it can mean a whole
|
||||
# VLAN, and that changes what the lookup is worth to somebody with a loop.
|
||||
#
|
||||
# Only MISSES are counted. An ordinary day at the cabinet produces none - a miss
|
||||
# is a scan of something this site has never heard of - so the budget can sit
|
||||
# well above a bad scanning day and still stop enumeration inside a minute.
|
||||
# Same fixed-window cache shape as the login limiter in shopdb.core.api.auth:
|
||||
# under SimpleCache the counter is per-process, which is defence in depth rather
|
||||
# than a hard quota.
|
||||
|
||||
BADGE_MISS_MAX = 15
|
||||
BADGE_MISS_WINDOW_SECONDS = 600
|
||||
|
||||
# The two of those an operator would ever reach for, as settings. They were
|
||||
# app-config only, which on an air-gapped server means hand-editing
|
||||
# instance/config.py and restarting IIS - so in practice the limiter had no off
|
||||
# switch and no dial at all, and the one lever anybody had was to turn the whole
|
||||
# kiosk off. Both default to exactly what the constants above did.
|
||||
#
|
||||
# The WINDOW deliberately stays app-config. It is the shape of the limiter, not
|
||||
# a number a site tunes; a budget expressed per ten minutes is the thing being
|
||||
# decided, and offering two interacting dials invites a combination nobody
|
||||
# meant.
|
||||
KIOSK_BADGE_LIMIT_ENABLED = 'usb_kiosk_badge_limit_enabled'
|
||||
KIOSK_BADGE_MISS_MAX = 'usb_kiosk_badge_miss_max'
|
||||
|
||||
|
||||
def _kiosk_int_setting(key, default):
|
||||
"""A positive whole number from a setting, else default.
|
||||
|
||||
A settings page stores text, so a blank, a word or a pasted range can all
|
||||
arrive here. Any of those has to land on the shipped budget rather than on
|
||||
zero, because zero is not "no limit" in this counter - it refuses every
|
||||
badge lookup the site has from the first scan of the window.
|
||||
"""
|
||||
row = Setting.query.filter_by(key=key).first()
|
||||
raw = row.value if row is not None and row.value is not None else ''
|
||||
try:
|
||||
value = int(str(raw).strip())
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return value if value > 0 else default
|
||||
|
||||
|
||||
def _badge_miss_budget():
|
||||
# Config first so instance/config.py and the test fixtures keep overriding,
|
||||
# then the setting, then the shipped number.
|
||||
maxmisses = current_app.config.get('USB_KIOSK_BADGE_MISS_MAX')
|
||||
if maxmisses is None:
|
||||
maxmisses = _kiosk_int_setting(KIOSK_BADGE_MISS_MAX, BADGE_MISS_MAX)
|
||||
return (current_app.config.get('USB_KIOSK_BADGE_WINDOW_SECONDS',
|
||||
BADGE_MISS_WINDOW_SECONDS),
|
||||
maxmisses)
|
||||
|
||||
|
||||
def _badge_miss_key(window):
|
||||
bucket = int(time.time() // window) if window > 0 else 0
|
||||
return 'usbkioskbadgemiss:{0}:{1}'.format(
|
||||
_kiosk_client_ip() or 'unknown', bucket)
|
||||
|
||||
|
||||
def _badge_limit_enabled():
|
||||
"""On everywhere but a test run, where the shared cache would bleed.
|
||||
|
||||
The counter lives in the process-wide cache, which outlives a test and is
|
||||
shared by whatever else lands on the same xdist worker - so misses spent in
|
||||
one module surface as an unrelated 429 in another, and which modules share a
|
||||
worker moves around. AUTH_RATELIMIT_ENABLED and the endpoints enrollment
|
||||
limiter are switched off in TestingConfig for exactly that reason; this one
|
||||
is younger than that file and defaults itself the same way.
|
||||
|
||||
Order: an explicit app config value (instance/config.py, and the fixtures in
|
||||
the test suite) wins, then TESTING, then the site setting, which ships on.
|
||||
A site turning this off is a real decision - the kiosk answers with an
|
||||
employee NAME, so an unbounded badge lookup is a directory anyone admitted
|
||||
can walk - which is why it is reachable rather than buried in a config file
|
||||
nobody on an air-gapped box can edit without a maintenance window.
|
||||
"""
|
||||
override = current_app.config.get('USB_KIOSK_BADGE_LIMIT_ENABLED')
|
||||
if override is not None:
|
||||
return bool(override)
|
||||
if current_app.config.get('TESTING', False):
|
||||
return False
|
||||
return _kiosk_setting(KIOSK_BADGE_LIMIT_ENABLED, True)
|
||||
|
||||
|
||||
def badge_lookups_exhausted():
|
||||
"""True when this caller has spent its budget of unrecognised badges."""
|
||||
if not _badge_limit_enabled():
|
||||
return False
|
||||
window, maxmisses = _badge_miss_budget()
|
||||
return (cache.get(_badge_miss_key(window)) or 0) >= maxmisses
|
||||
|
||||
|
||||
def record_badge_miss():
|
||||
"""Count one unrecognised scan against this caller.
|
||||
|
||||
Called from both directory modes - the raw-SQL path below and the
|
||||
self-hosted one in selfhosted.py - at the point where a scanned badge
|
||||
resolves to nobody. Holder-name lookups do not come through here: those are
|
||||
the kiosk naming a drive's holder, not a caller guessing.
|
||||
"""
|
||||
if not _badge_limit_enabled():
|
||||
return
|
||||
window, maxmisses = _badge_miss_budget()
|
||||
key = _badge_miss_key(window)
|
||||
count = (cache.get(key) or 0) + 1
|
||||
cache.set(key, count, timeout=window)
|
||||
if count == maxmisses:
|
||||
logger.warning('usb kiosk: %s unrecognised badges from %s within %ss; '
|
||||
'refusing badge lookups for the rest of the window',
|
||||
count, _kiosk_client_ip(), window)
|
||||
|
||||
|
||||
def _badge_lookups_refused():
|
||||
return error_response(
|
||||
'RATE_LIMITED',
|
||||
'Too many badges this screen does not recognise. Wait a few minutes '
|
||||
'and try again, or see IT.', http_code=429)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Provisioning a screen without putting the token in a URL
|
||||
# ---------------------------------------------------------------------------
|
||||
# A query string is the one place a credential is guaranteed to be copied:
|
||||
# browser history, the Referer on the next request, the IIS access log, whatever
|
||||
# the proxy keeps. So the link an administrator carries to a screen holds a code
|
||||
# that is good once and briefly, and the token itself comes back in a Set-Cookie
|
||||
# that no log line carries.
|
||||
#
|
||||
# Only the code's DIGEST is stored, so the pending row is not itself a
|
||||
# credential; the expiry rides with it.
|
||||
|
||||
KIOSK_SETUP_CODE = 'usb_kiosk_setup_code'
|
||||
# Long enough to walk from a desk to the cabinet, short enough that a link left
|
||||
# in a history or a log is already dead when somebody reads it back.
|
||||
KIOSK_SETUP_TTL_SECONDS = 30 * 60
|
||||
# The screen is provisioned once and must not quietly fall out of the kiosk
|
||||
# months later, which is the failure this cookie has to avoid above all.
|
||||
KIOSK_COOKIE_MAX_AGE = 5 * 365 * 24 * 60 * 60
|
||||
|
||||
|
||||
def _issue_kiosk_setup_code():
|
||||
"""Mint a single-use code, store its digest and expiry, return the code."""
|
||||
code = secrets.token_urlsafe(24)
|
||||
digest = hashlib.sha256(code.encode()).hexdigest()
|
||||
expiry = int(time.time()) + KIOSK_SETUP_TTL_SECONDS
|
||||
Setting.set(KIOSK_SETUP_CODE, '{0}|{1}'.format(digest, expiry),
|
||||
valuetype='string', category='usb',
|
||||
description='Digest and expiry of the pending kiosk setup '
|
||||
'code. Written and cleared by the setup link; not '
|
||||
'edited by hand.')
|
||||
return code
|
||||
|
||||
|
||||
def _redeem_kiosk_setup_code(code):
|
||||
"""True exactly once per issued code, and never once it has expired.
|
||||
|
||||
Cleared on ANY attempt. A code is worth one screen; burning it on a wrong
|
||||
guess costs an administrator one click and leaves a prober nothing to
|
||||
retry against.
|
||||
"""
|
||||
stored = (Setting.get(KIOSK_SETUP_CODE) or '').strip()
|
||||
if not stored or '|' not in stored:
|
||||
return False
|
||||
Setting.set(KIOSK_SETUP_CODE, '', valuetype='string', category='usb')
|
||||
digest, _, expiry = stored.partition('|')
|
||||
try:
|
||||
if int(expiry) < int(time.time()):
|
||||
return False
|
||||
except ValueError:
|
||||
return False
|
||||
return hmac.compare_digest(
|
||||
digest, hashlib.sha256((code or '').encode()).hexdigest())
|
||||
|
||||
|
||||
@usb_bp.route('/kiosk/provisioning-link', methods=['GET'])
|
||||
@require_permission('settings.edit')
|
||||
def kiosk_provisioning_link():
|
||||
@@ -830,9 +1216,16 @@ def kiosk_provisioning_link():
|
||||
|
||||
So the copy step stops depending on catching that moment. The mask stays -
|
||||
it is right that a token does not travel in an ordinary settings list - and
|
||||
this named, permission-gated route hands the value to somebody who is
|
||||
this named, permission-gated route hands over a way in to somebody who is
|
||||
already allowed to set it.
|
||||
|
||||
WHAT IT HANDS OVER IS NOT THE TOKEN. The link used to be
|
||||
'/usb-kiosk?token=<value>', which put the credential in a query string: the
|
||||
address bar, the browser history, a Referer, the IIS log and anything in
|
||||
between. It is now a single-use code that kiosk_setup trades for the token
|
||||
over a Set-Cookie. One click here, one open on the screen - the operator
|
||||
flow is the same.
|
||||
|
||||
Returns a relative URL. The caller's own origin is the right base for a
|
||||
screen being provisioned from that same browser, and the server has no
|
||||
reliable idea what hostname the operator reached it by.
|
||||
@@ -841,12 +1234,60 @@ def kiosk_provisioning_link():
|
||||
if not token:
|
||||
return error_response(ErrorCodes.VALIDATION_ERROR,
|
||||
'No kiosk token set. Generate one first.')
|
||||
# Revealing a credential is worth a line in the audit log: it is the moment
|
||||
# the value left the database, and the trail should say who asked.
|
||||
code = _issue_kiosk_setup_code()
|
||||
# Issuing a way to claim the token is worth a line in the audit log: the
|
||||
# trail should say who asked, and when the clock on it started.
|
||||
audit_log('viewed', 'Setting', entityname='usb_kiosk_token',
|
||||
details='kiosk provisioning link')
|
||||
details='kiosk setup link issued')
|
||||
db.session.commit()
|
||||
return success_response({'url': '/usb-kiosk?token=' + token})
|
||||
return success_response({
|
||||
'url': '/api/usb/kiosk/setup?code=' + code,
|
||||
'expiresinminutes': KIOSK_SETUP_TTL_SECONDS // 60,
|
||||
})
|
||||
|
||||
|
||||
@usb_bp.route('/kiosk/setup', methods=['GET'])
|
||||
def kiosk_setup():
|
||||
"""Trade a setup code for this browser's kiosk cookie, then open the kiosk.
|
||||
|
||||
Opened once on the screen being provisioned. The code is spent here, the
|
||||
token travels back in a Set-Cookie rather than a URL, and the browser is
|
||||
sent on to the kiosk page with nothing left in the address bar.
|
||||
|
||||
HttpOnly, so the page's own JavaScript cannot read the token back out and
|
||||
put it somewhere that does get logged. SameSite=Lax, so another site cannot
|
||||
make this browser POST at the kiosk routes with it. Secure only over https:
|
||||
setting it unconditionally would drop the cookie on the plain-http sites
|
||||
this is deployed on and provision nothing.
|
||||
|
||||
Not gated on usb_kiosk_enabled: a site sets its screens up before opening
|
||||
the door, and a kiosk that is off refuses every call anyway.
|
||||
"""
|
||||
token = (Setting.get('usb_kiosk_token') or '').strip()
|
||||
if not token:
|
||||
return error_response(ErrorCodes.VALIDATION_ERROR,
|
||||
'No kiosk token set. Generate one first.')
|
||||
if not _redeem_kiosk_setup_code(request.args.get('code')):
|
||||
# 410, not 404: this one is read by an operator standing at a screen,
|
||||
# and "gone" plus what to do next is the difference between a working
|
||||
# kiosk and a support call.
|
||||
return error_response(
|
||||
ErrorCodes.NOT_FOUND,
|
||||
'This setup link has already been used or has expired. Generate a '
|
||||
'new one under Settings > USB.', http_code=410)
|
||||
audit_log('viewed', 'Setting', entityname='usb_kiosk_token',
|
||||
details='kiosk setup link redeemed')
|
||||
db.session.commit()
|
||||
|
||||
mount = request.script_root or ''
|
||||
response = redirect(mount + '/usb-kiosk')
|
||||
response.set_cookie(KIOSK_TOKEN_COOKIE, token,
|
||||
max_age=KIOSK_COOKIE_MAX_AGE, httponly=True,
|
||||
samesite='Lax', secure=request.is_secure,
|
||||
path=mount + '/')
|
||||
# This response carries the token. Nothing anywhere may keep a copy.
|
||||
response.headers['Cache-Control'] = 'no-store'
|
||||
return response
|
||||
|
||||
|
||||
@usb_bp.route('/kiosk/device/<device_id>', methods=['GET'])
|
||||
@@ -920,6 +1361,8 @@ def kiosk_session():
|
||||
"""
|
||||
if not _kiosk_open():
|
||||
return _kiosk_disabled_response()
|
||||
if badge_lookups_exhausted():
|
||||
return _badge_lookups_refused()
|
||||
data = request.get_json() or {}
|
||||
if _usb_selfhosted():
|
||||
return selfhosted.kiosk_session(data)
|
||||
@@ -933,6 +1376,7 @@ def kiosk_session():
|
||||
with conn.cursor() as cur:
|
||||
name = _resolve_badge_name(cur, badge)
|
||||
if not name:
|
||||
record_badge_miss()
|
||||
return error_response(
|
||||
ErrorCodes.VALIDATION_ERROR,
|
||||
'Badge not recognized - see IT',
|
||||
@@ -978,6 +1422,8 @@ def kiosk_others():
|
||||
return _kiosk_disabled_response()
|
||||
if not _kiosk_setting('usb_kiosk_allow_return_for_others', True):
|
||||
return _kiosk_disabled_response()
|
||||
if badge_lookups_exhausted():
|
||||
return _badge_lookups_refused()
|
||||
data = request.get_json() or {}
|
||||
if _usb_selfhosted():
|
||||
return selfhosted.kiosk_others(data)
|
||||
@@ -990,6 +1436,7 @@ def kiosk_others():
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
if not _resolve_badge_name(cur, badge):
|
||||
record_badge_miss()
|
||||
return error_response(ErrorCodes.VALIDATION_ERROR,
|
||||
'Badge not recognized - see IT',
|
||||
http_code=422)
|
||||
@@ -1020,6 +1467,8 @@ def kiosk_checkout():
|
||||
"""Check a device out at the kiosk. Body: {device_id, badge}."""
|
||||
if not _kiosk_open():
|
||||
return _kiosk_disabled_response()
|
||||
if badge_lookups_exhausted():
|
||||
return _badge_lookups_refused()
|
||||
data = request.get_json() or {}
|
||||
if _usb_selfhosted():
|
||||
return selfhosted.kiosk_checkout(data)
|
||||
@@ -1054,6 +1503,7 @@ def kiosk_checkout():
|
||||
# kiosk there is no signed-in operator to vouch for it.
|
||||
name = _resolve_badge_name(cur, badge)
|
||||
if not name:
|
||||
record_badge_miss()
|
||||
return error_response(
|
||||
ErrorCodes.VALIDATION_ERROR,
|
||||
'Badge not recognized - see IT to check this device out',
|
||||
@@ -1107,6 +1557,8 @@ def kiosk_checkin():
|
||||
"""
|
||||
if not _kiosk_open():
|
||||
return _kiosk_disabled_response()
|
||||
if badge_lookups_exhausted():
|
||||
return _badge_lookups_refused()
|
||||
data = request.get_json() or {}
|
||||
if _usb_selfhosted():
|
||||
return selfhosted.kiosk_checkin(data)
|
||||
@@ -1131,6 +1583,7 @@ def kiosk_checkin():
|
||||
|
||||
name = _resolve_badge_name(cur, badge)
|
||||
if not name:
|
||||
record_badge_miss()
|
||||
return error_response(
|
||||
ErrorCodes.VALIDATION_ERROR,
|
||||
'Badge not recognized - see IT to return this device',
|
||||
|
||||
@@ -343,6 +343,27 @@ def kiosk_device(device_id):
|
||||
})
|
||||
|
||||
|
||||
def _badge_not_recognised(suffix=''):
|
||||
"""One unrecognised scan, counted against the caller, then the refusal.
|
||||
|
||||
WHY COUNTED. The answer to a recognised badge is an employee's NAME, and a
|
||||
badge is a short number, so this is a lookup somebody admitted to the kiosk
|
||||
can walk. Network-position admission can now mean a whole VLAN rather than
|
||||
one screen by the cabinet, so the number of badges a caller may guess wrong
|
||||
has to be bounded. The budget lives in routes.py alongside the admission
|
||||
checks; the import is deferred because routes imports this module.
|
||||
|
||||
The wording stays per-action ("to check this device out"), because the
|
||||
person at the screen is being told what did not happen.
|
||||
"""
|
||||
from .routes import record_badge_miss
|
||||
|
||||
record_badge_miss()
|
||||
return error_response(ErrorCodes.VALIDATION_ERROR,
|
||||
'Badge not recognized - see IT' + suffix,
|
||||
http_code=422)
|
||||
|
||||
|
||||
def kiosk_session(data):
|
||||
"""See routes.kiosk_session for why the list costs a valid badge."""
|
||||
badge, badgeerror = _kiosk_badge_digits(data.get('badge'))
|
||||
@@ -350,8 +371,7 @@ def kiosk_session(data):
|
||||
return badgeerror
|
||||
name = _resolve_name(badge)
|
||||
if not name:
|
||||
return error_response(ErrorCodes.VALIDATION_ERROR,
|
||||
'Badge not recognized - see IT', http_code=422)
|
||||
return _badge_not_recognised()
|
||||
|
||||
yours, available, others = [], [], 0
|
||||
for device in USBDevice.query.filter_by(isactive=True).order_by(
|
||||
@@ -377,8 +397,7 @@ def kiosk_others(data):
|
||||
if badgeerror:
|
||||
return badgeerror
|
||||
if not _resolve_name(badge):
|
||||
return error_response(ErrorCodes.VALIDATION_ERROR,
|
||||
'Badge not recognized - see IT', http_code=422)
|
||||
return _badge_not_recognised()
|
||||
|
||||
out = []
|
||||
for device in USBDevice.query.filter_by(isactive=True, ischeckedout=True
|
||||
@@ -419,10 +438,7 @@ def kiosk_checkout(data):
|
||||
# path. A checkout nobody can trace to a person defeats the tracking.
|
||||
name = _resolve_name(badge)
|
||||
if not name:
|
||||
return error_response(
|
||||
ErrorCodes.VALIDATION_ERROR,
|
||||
'Badge not recognized - see IT to check this device out',
|
||||
http_code=422)
|
||||
return _badge_not_recognised(' to check this device out')
|
||||
|
||||
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
# The transition IS the guard. The ischeckedout test above reads, decides
|
||||
@@ -477,10 +493,7 @@ def kiosk_checkin(data):
|
||||
|
||||
name = _resolve_name(badge)
|
||||
if not name:
|
||||
return error_response(
|
||||
ErrorCodes.VALIDATION_ERROR,
|
||||
'Badge not recognized - see IT to return this device',
|
||||
http_code=422)
|
||||
return _badge_not_recognised(' to return this device')
|
||||
|
||||
holderbadge = (device.currentuserid or '').strip()
|
||||
if holderbadge and holderbadge != badge:
|
||||
|
||||
Reference in New Issue
Block a user