Merge pull request #728 from Foundation-Devices/SFT-3834-message-signing-microsd-length
What changed, and why it matters
This firmware update changes how the Passport hardware wallet handles message signing. It restores the ability to sign messages containing newlines (which had been blocked), increases the maximum microSD message file size from 240 to 4096 bytes, and adds a warning when a message ends in invisible whitespace. The core risk is that invisible characters at the end of a message, or a very long message that the user cannot fully review, could lead someone to sign something different from what they think they saw. The patch adds safeguards (footer warning, forced scrolling to the end) rather than removing all restrictions.
Treat this as a security-hardening feature change rather than a vulnerability fix. Review whether 4096 bytes is still short enough for users to reliably inspect the entire message, and verify that require_scroll_to_end cannot be bypassed. Consider localizing the new footer warning text before release.
Security signals we found
Restored newline support in signed messages after previous restriction
Increased microSD message signing length limit from 240 to 4096 bytes
Added footer warning for messages ending in invisible whitespace
Added require_scroll_to_end on message review pages
Continues to reject control characters, NUL, DEL, non-ASCII, and RTL override characters
Electrum-format messages parsed by splitting on spaces, not lines, to preserve signed bytes
Evidence from the diff
The commit refactors health-check and message-signing flows to pass raw message data instead of pre-split lines, allowing Electrum-style single-line ‘signmessage
Changed components
HealthCheckCommonFlowHealthCheckMicrosdFlowHealthCheckQRFlowSignElectrumMessageFlowLongTextPagevalidate_sign_text utilityvalidate_electrum_message_taskMSG_SIGNING_MAX_LENGTH constantInspect captured patch +230 / −48
### ports/stm32/boards/Passport/modules/flows/health_check_common_flow.py
@@ -9,9 +9,9 @@
class HealthCheckCommonFlow(Flow):
- def __init__(self, lines, normal_signing=False):
+ def __init__(self, data, normal_signing=False):
super().__init__(initial_state=self.validate_lines, name='HealthCheckCommonFlow')
- self.lines = lines
+ self.data = data
self.text = None
self.subpath = None
self.addr_type = AF_CLASSIC
@@ -23,9 +23,13 @@ async def validate_lines(self):
err_label = 'Message' if self.normal_signing else 'Health check'
- single_line = len(self.lines) == 1 and self.lines[0].startswith('signmessage ')
- if single_line:
- parts = self.lines[0].split(' ', 2)
+ lines = self.data.splitlines()
+ header = lines[0].split(' ', 2) if lines else []
+ electrum_format = self.data.startswith('signmessage ') and (
+ len(lines) == 1 or (len(header) == 3 and header[2].startswith('ascii:')))
+ if electrum_format:
+ # Splitting the payload into lines would change the signed bytes.
+ parts = self.data.split(' ', 2)
if len(parts) != 3 or not parts[2].startswith('ascii:'):
await ErrorPage('{} format is invalid.'.format(err_label)).show()
@@ -36,23 +40,23 @@ async def validate_lines(self):
self.text = parts[2][len('ascii:'):]
else:
- if len(self.lines) not in [2, 3]:
+ if len(lines) not in [2, 3]:
await ErrorPage('{} format is invalid.'.format(err_label)).show()
self.set_result(None)
return
- self.text = self.lines[0]
- self.subpath = self.lines[1]
+ self.text = lines[0]
+ self.subpath = lines[1]
- if len(self.lines) == 3:
- self.addr_type = get_addr_type_from_string(self.lines[2])
+ if len(lines) == 3:
+ self.addr_type = get_addr_type_from_string(lines[2])
if not self.text:
await ErrorPage(text='Message is empty.').show()
self.set_result(None)
return
- (subpath, error) = validate_sign_text(self.text, self.subpath)
+ (subpath, error) = validate_sign_text(self.text, self.subpath, allow_newlines=electrum_format)
if error is not None:
await ErrorPage(text=error).show()
@@ -61,7 +65,7 @@ async def validate_lines(self):
self.subpath = subpath
- if single_line:
+ if electrum_format:
# A root or missing path has no purpose component for address-type
# detection, even though the general path validator accepts it.
if not self.subpath or self.subpath == 'm':
@@ -83,7 +87,7 @@ async def validate_lines(self):
async def show_message(self):
import stash
- from utils import escape_text, stylize_address
+ from utils import escape_text, message_review_warning, stylize_address
from pages import LongTextPage, LongQuestionPage
import microns
from public_constants import MARGIN_FOR_ADDRESSES
@@ -95,7 +99,9 @@ async def show_message(self):
display_address = stylize_address(self.address)
result = await LongTextPage(centered=True,
- text=('\n' + escape_text(self.text)),
+ text='\n' + escape_text(self.text),
+ footer=message_review_warning(self.text),
+ require_scroll_to_end=True,
card_header={'title': 'Message'}).show()
if not result:
### ports/stm32/boards/Passport/modules/flows/health_check_microsd_flow.py
@@ -37,7 +37,7 @@ class HealthCheckMicrosdFlow(Flow):
def __init__(self, context=None, normal_signing=False):
super().__init__(initial_state=self.choose_file, name='HealthCheckMicrosdFlow')
self.file_path = None
- self.lines = None
+ self.data = None
self.signed_message = None
self.service_name = context
self.normal_signing = normal_signing
@@ -91,13 +91,13 @@ async def parse_message(self):
self.set_result(False)
return
- self.lines = data.splitlines()
+ self.data = data
self.goto(self.common_flow)
async def common_flow(self):
from flows import HealthCheckCommonFlow
- self.signed_message = await HealthCheckCommonFlow(self.lines, normal_signing=self.normal_signing).run()
+ self.signed_message = await HealthCheckCommonFlow(self.data, normal_signing=self.normal_signing).run()
if self.signed_message is None:
self.set_result(False)
return
### ports/stm32/boards/Passport/modules/flows/health_check_qr_flow.py
@@ -13,7 +13,7 @@ def __init__(self, context=None):
super().__init__(initial_state=self.scan_qr, name='HealthCheckQRFlow')
self.service_name = context
- self.lines = None
+ self.data = None
self.signed_message = None
async def scan_qr(self):
@@ -30,7 +30,7 @@ async def scan_qr(self):
try:
data = result.unwrap_bytes().decode('utf-8')
- self.lines = data.split('\n')
+ self.data = data
except Exception as e:
await ErrorPage('Health check format is invalid.').show()
self.set_result(False)
@@ -41,7 +41,7 @@ async def scan_qr(self):
async def common_flow(self):
from flows import HealthCheckCommonFlow
- self.signed_message = await HealthCheckCommonFlow(self.lines).run()
+ self.signed_message = await HealthCheckCommonFlow(self.data).run()
if self.signed_message is None:
self.set_result(False)
return
### ports/stm32/boards/Passport/modules/flows/sign_electrum_message_flow.py
@@ -6,7 +6,7 @@
from flows import Flow, ScanQRFlow
from pages import ErrorPage, LongTextPage, LongQuestionPage, ShowQRPage
from tasks import sign_text_file_task, validate_electrum_message_task
-from utils import escape_text, spinner_task, stylize_address
+from utils import escape_text, message_review_warning, spinner_task, stylize_address
from data_codecs.qr_type import QRType
import microns
from wallets.utils import get_addr_type_from_deriv
@@ -61,7 +61,9 @@ async def show_message(self):
display_address = stylize_address(self.address)
result = await LongTextPage(centered=True,
- text=('\n' + escape_text(self.message)),
+ text='\n' + escape_text(self.message),
+ footer=message_review_warning(self.message),
+ require_scroll_to_end=True,
card_header={'title': 'Message'}).show()
if not result:
### ports/stm32/boards/Passport/modules/pages/long_text_page.py
@@ -7,7 +7,7 @@
from styles.style import Stylize
from views import Label, View, Icon
from pages import Page
-from styles.colors import TEXT_GREY, SCROLLBAR_BG_COLOR
+from styles.colors import TEXT_GREY, SCROLLBAR_BG_COLOR, HIGHLIGHT_TEXT
import microns
import passport
@@ -24,7 +24,8 @@ def __init__(self,
right_micron=microns.Forward,
margins=None,
top_margin=None,
- require_scroll_to_end=False):
+ require_scroll_to_end=False,
+ footer=None):
super().__init__(
card_header=card_header,
statusbar=statusbar,
@@ -82,7 +83,19 @@ def __init__(self,
default.text_align(lv.TEXT_ALIGN.CENTER)
self.container.set_children([self.text])
- self.add_child(self.container)
+
+ if footer is not None:
+ title, body = footer
+ self.footer = Label(text=title, color=HIGHLIGHT_TEXT, center=centered, recolor=False)
+ self.footer.set_width(lv.pct(100))
+ with Stylize(self.footer) as default:
+ default.pad(top=16)
+ self.container.add_child(self.footer)
+ self.footer_body = Label(text=body, color=TEXT_GREY, center=centered, recolor=False)
+ self.footer_body.set_width(lv.pct(100))
+ self.container.add_child(self.footer_body)
+
+ self.add_child(self.container)
def attach(self, group):
super().attach(group)
### ports/stm32/boards/Passport/modules/public_constants.py
@@ -27,8 +27,8 @@
TXN_INPUT_OFFSET = 0
TXN_OUTPUT_OFFSET = MAX_TXN_LEN
-# Max length of text messages for signing
-MSG_SIGNING_MAX_LENGTH = const(240)
+# Bound microSD message files to keep parsing and review within memory limits.
+MSG_SIGNING_MAX_LENGTH = const(4096)
# Types of user auth we support
USER_AUTH_TOTP = const(1) # RFC6238
### ports/stm32/boards/Passport/modules/tasks/validate_electrum_message_task.py
@@ -24,10 +24,9 @@ async def validate_electrum_message_task(on_done, message):
await on_done(None, 'Unsupported message type')
return
- # Keep the printable-ASCII check: controls can truncate or obscure the
- # preview even though the original message bytes would still be signed.
+ # Reject controls that can hide signed bytes in the preview.
(subpath, error) = validate_sign_text(
- message, header_elements[1], space_limit=False, check_whitespace=False)
+ message, header_elements[1], space_limit=False, check_whitespace=False, allow_newlines=True)
if error:
await on_done(None, error)
### ports/stm32/boards/Passport/modules/tests/test_unit.py
@@ -164,5 +164,9 @@ def test_single_line_message(test):
assert test('single_line_message.py') == b'OK'
+def test_microsd_message_length(test):
+ assert test('microsd_message_length.py') == b'OK'
+
+
def test_scv_challenge(test):
assert test('scv_challenge.py') == b'OK'
### ports/stm32/boards/Passport/modules/tests/unit/electrum_message_validation.py
@@ -28,14 +28,15 @@ async def run_tests():
'Visible #ffffff hidden text#',
' leading spaces and trailing ',
'message:with:colons',
+ '\nfirst\n\nsecond\n',
+ '\r\nfirst\r\n\r\nsecond\r\n',
):
value, error = await validate(message)
assert error is None
assert value == (message, PATH)
- # NUL must not hide a signed suffix. Other controls (including LF and TAB),
- # DEL, and non-ASCII text are also outside the supported display charset.
- for character in tuple(chr(code) for code in range(32)) + ('\x7f', '\u00e9', '\u202e'):
+ # NUL and other unsupported controls must not hide signed text.
+ for character in tuple(chr(code) for code in range(32) if code != 10) + ('\x7f', '\u00e9', '\u202e'):
value, error = await validate('visible' + character + 'hidden')
assert value is None
assert error is not None
### ports/stm32/boards/Passport/modules/tests/unit/message_display.py
@@ -14,6 +14,17 @@
class MockReviewPage:
texts = []
+ def __init__(self, text, **kwargs):
+ assert kwargs['require_scroll_to_end']
+ self.texts.append((text, kwargs['footer']))
+
+ async def show(self):
+ return True
+
+
+class MockQuestionPage:
+ texts = []
+
def __init__(self, text, **kwargs):
self.texts.append(text)
@@ -71,11 +82,16 @@ async def run_tests():
original_electrum_spinner = electrum.spinner_task
try:
pages.LongTextPage = electrum.LongTextPage = MockReviewPage
- pages.LongQuestionPage = electrum.LongQuestionPage = MockReviewPage
+ pages.LongQuestionPage = electrum.LongQuestionPage = MockQuestionPage
stash.SensitiveValues = MockSensitiveValues
utils.spinner_task = electrum.spinner_task = mock_sign_spinner
cases = (
+ ('trailing space ', 'trailing space '),
+ ('leading and interior\nwhitespace', 'leading and interior\nwhitespace'),
+ ('I approve A' + '\n' * 40 + 'and B', 'I approve A' + '\n' * 40 + 'and B'),
+ ('\nfirst\n\nsecond\n', '\nfirst\n\nsecond\n'),
+ ('first\r\n#ff0000 second#\r\n', 'first\r\n##ff0000 second##\r\n'),
('literal # and ## hashes', 'literal ## and #### hashes'),
('#ff0000 red#', '##ff0000 red##'),
('before #00ff00 green# after #', 'before ##00ff00 green## after ##'),
@@ -85,15 +101,19 @@ async def run_tests():
flow = MockFlow()
flow.message = flow.text = message
MockReviewPage.texts = []
+ MockQuestionPage.texts = []
before = len(signed_messages)
if is_electrum:
await electrum.SignElectrumMessageFlow.show_message(flow)
assert flow.next_state == flow.do_sign
else:
await HealthCheckCommonFlow.show_message(flow)
assert flow.next_state == flow.sign_health_check
- assert MockReviewPage.texts[0] == '\n' + displayed
- assert len(MockReviewPage.texts) == 2
+ warning = None
+ if message.endswith(' ') or message.endswith('\n'):
+ warning = ('This message ends with whitespace.', 'It will be included in the signature.')
+ assert MockReviewPage.texts == [('\n' + displayed, warning)]
+ assert len(MockQuestionPage.texts) == 1
assert len(signed_messages) == before
assert flow.message == flow.text == message
if is_electrum:
### ports/stm32/boards/Passport/modules/tests/unit/microsd_message_length.py
@@ -0,0 +1,121 @@
+# SPDX-FileCopyrightText: © 2026 Foundation Devices, Inc. <hello@foundation.xyz>
+# SPDX-License-Identifier: GPL-3.0-or-later
+
+import flows
+import pages
+import uio
+import uasyncio as asyncio
+from flows.health_check_microsd_flow import HealthCheckMicrosdFlow
+from flows.health_check_common_flow import HealthCheckCommonFlow
+from public_constants import AF_CLASSIC
+
+
+class MockReadFileFlow:
+ data = b''
+
+ def __init__(self, path, binary, read_fn):
+ assert binary
+ self.read_fn = read_fn
+
+ async def run(self):
+ stream = uio.BytesIO(self.data)
+ result = self.read_fn(stream)
+ assert stream.tell() <= 4097
+ return result
+
+
+class MockErrorPage:
+ errors = []
+
+ def __init__(self, text):
+ self.errors.append(text)
+
+ async def show(self):
+ return True
+
+
+class MockFlow:
+ normal_signing = True
+ file_path = 'message.txt'
+ common_flow = 'validate'
+ show_message = 'review'
+ addr_type = AF_CLASSIC
+
+ def __init__(self):
+ self.next_state = None
+ self.result = 'unset'
+
+ def goto(self, state):
+ self.next_state = state
+
+ def set_result(self, result):
+ self.result = result
+
+
+async def run_tests():
+ original_reader = flows.ReadFileFlow
+ original_error_page = pages.ErrorPage
+ try:
+ flows.ReadFileFlow = MockReadFileFlow
+ pages.ErrorPage = MockErrorPage
+ path = "m/84'/0'/0'/0/0"
+ for prefix, suffix in (('signmessage ' + path + ' ascii:', ''), ('', '\n' + path + '\np2wpkh')):
+ for length in (241, 1024, 4096, 4097, 16384):
+ message = 'x' * (length - len(prefix) - len(suffix))
+ MockReadFileFlow.data = (prefix + message + suffix).encode()
+ MockErrorPage.errors = []
+ flow = MockFlow()
+ await HealthCheckMicrosdFlow.parse_message(flow)
+ if length > 4096:
+ assert MockErrorPage.errors == ['Message file is too long. Max length is 4096 bytes.']
+ assert flow.result is False
+ assert flow.next_state is None
+ else:
+ assert flow.next_state == flow.common_flow
+ await HealthCheckCommonFlow.validate_lines(flow)
+ assert not MockErrorPage.errors
+ assert flow.text == message
+ assert flow.next_state == flow.show_message
+ assert flow.result == 'unset'
+
+ for message in ('first\nsecond', '\nfirst\n\nsecond\n', 'first\r\n\r\nsecond\r\n',
+ 'first\nsecond\r\nthird\n', 'x' * 1000 + '\nlast\n'):
+ MockReadFileFlow.data = ('signmessage ' + path + ' ascii:' + message).encode()
+ MockErrorPage.errors = []
+ flow = MockFlow()
+ await HealthCheckMicrosdFlow.parse_message(flow)
+ await HealthCheckCommonFlow.validate_lines(flow)
+ assert not MockErrorPage.errors
+ assert flow.text.encode() == message.encode()
+ assert flow.next_state == flow.show_message
+ flow.address = '1BoatSLRHtKNngkdXEeobR76b53LETtpyT'
+ flow.signature = 'signature'
+ await HealthCheckCommonFlow.format_signature(flow)
+ assert flow.result.startswith('-----BEGIN BITCOIN SIGNED MESSAGE-----\n' + message + '\n')
+ assert '\n-----BEGIN BITCOIN SIGNATURE-----\n' in flow.result
+ assert flow.result.endswith('-----END BITCOIN SIGNATURE-----\n')
+
+ for character in tuple(chr(code) for code in range(32) if code != 10) + ('\x7f',):
+ MockReadFileFlow.data = ('signmessage ' + path + ' ascii:visible' + character + 'hidden').encode()
+ MockErrorPage.errors = []
+ flow = MockFlow()
+ await HealthCheckMicrosdFlow.parse_message(flow)
+ await HealthCheckCommonFlow.validate_lines(flow)
+ assert MockErrorPage.errors
+ assert flow.result is None
+ assert flow.next_state != flow.show_message
+
+ MockReadFileFlow.data = b'\xff'
+ MockErrorPage.errors = []
+ flow = MockFlow()
+ await HealthCheckMicrosdFlow.parse_message(flow)
+ assert MockErrorPage.errors == ['Message file contains invalid text.']
+ assert flow.result is False
+ assert flow.next_state is None
+ return_value.write(b'OK')
+ finally:
+ flows.ReadFileFlow = original_reader
+ pages.ErrorPage = original_error_page
+
+
+asyncio.run(run_tests())
### ports/stm32/boards/Passport/modules/tests/unit/single_line_message.py
@@ -24,7 +24,7 @@ class MockFlow:
sign_health_check = 'sign'
def __init__(self, lines, normal_signing):
- self.lines = lines
+ self.data = '\n'.join(lines)
self.normal_signing = normal_signing
self.addr_type = AF_CLASSIC
self.next_state = None
@@ -60,7 +60,7 @@ async def run_tests():
assert flow.next_state is None
# Strict text checks also apply to health checks, deliberately.
- for message in (' leading', 'trailing ', 'four spaces', 'line\nbreak', 'a\x00b', '\u00e9'):
+ for message in (' leading', 'trailing ', 'four spaces', 'line\rbreak', 'a\x00b', '\u00e9'):
MockErrorPage.errors = []
flow = MockFlow(['signmessage ' + path + ' ascii:' + message], normal_signing)
await HealthCheckCommonFlow.validate_lines(flow)
@@ -142,9 +142,9 @@ async def run_tests():
MockErrorPage.errors = []
flow = MockFlow(('signmessage ' + path + ' ascii:line\nbreak').splitlines(), normal_signing)
await HealthCheckCommonFlow.validate_lines(flow)
- assert MockErrorPage.errors
- assert flow.result is None
- assert flow.next_state is None
+ assert not MockErrorPage.errors
+ assert flow.text == 'line\nbreak'
+ assert flow.next_state == (flow.show_message if normal_signing else flow.sign_health_check)
return_value.write(b'OK')
finally:
### ports/stm32/boards/Passport/modules/tests/unit/transaction_review.py
@@ -11,7 +11,7 @@
from pages.long_text_page import LongTextPage
from psbt import psbtOutputProxy
from serializations import CTxOut
-from styles.colors import HIGHLIGHT_TEXT_HEX
+from styles.colors import HIGHLIGHT_TEXT, HIGHLIGHT_TEXT_HEX, TEXT_GREY
from uio import BytesIO
from utils import escape_text, recolor, stylize_address
@@ -217,11 +217,20 @@ def test_scroll_gate():
parent.set_flex_flow(lv.FLEX_FLOW.COLUMN)
group = lv.group_create()
try:
- for text, overflow in (('Short text', False), ('Long warning\n' * 50, True)):
- page = LongTextPage(text=text, require_scroll_to_end=True)
+ for text, footer, overflow in (
+ ('Short text', None, False),
+ ('Long warning\n' * 50, None, True),
+ ('Short text', ('Trailing whitespace notice ' * 30, 'Signature explanation'), True)):
+ page = LongTextPage(text=text, footer=footer, require_scroll_to_end=True)
page.mount(parent)
page.attach(group)
container = page.container.lvgl_root
+ if footer is not None:
+ assert page.footer.lvgl_root.get_style_text_color(0).full == HIGHLIGHT_TEXT.full
+ assert not page.footer.lvgl_root.get_recolor()
+ assert page.footer.lvgl_root.get_height() > 30
+ assert page.footer_body.lvgl_root.get_style_text_color(0).full == TEXT_GREY.full
+ assert not page.footer_body.lvgl_root.get_recolor()
assert (container.get_scroll_bottom() > 0) == overflow
assert (common.ui.right_micron is None) == overflow
page.right_action(True)
### ports/stm32/boards/Passport/modules/utils.py
@@ -1303,7 +1303,7 @@ def is_passphrase_active():
MSG_MAX_SPACES = 4
-def validate_sign_text(text, subpath, space_limit=True, check_whitespace=True, check_ascii=True):
+def validate_sign_text(text, subpath, space_limit=True, check_whitespace=True, check_ascii=True, allow_newlines=False):
# Check for leading or trailing whitespace
if check_whitespace:
if text[0] == ' ':
@@ -1315,9 +1315,9 @@ def validate_sign_text(text, subpath, space_limit=True, check_whitespace=True, c
# Ensure characters are in range and not too many spaces
run = 0
# print('text="{}"'.format(text))
- for ch in text:
- # print('ch="{}"'.format(ch))
- if check_ascii and ord(ch) not in MSG_CHARSET:
+ for index, ch in enumerate(text):
+ newline = allow_newlines and (ch == '\n' or (ch == '\r' and text[index + 1:index + 2] == '\n'))
+ if check_ascii and ord(ch) not in MSG_CHARSET and not newline:
return (subpath, 'File contains non-ASCII character: 0x%02x' % ord(ch))
if space_limit:
@@ -1487,6 +1487,13 @@ def escape_text(text):
return text.replace("#", "##")
+def message_review_warning(message):
+ if message and message[-1] in ' \r\n\t':
+ # TODO: localize
+ return ('This message ends with whitespace.', 'It will be included in the signature.')
+ return None
+
+
def stylize_address(address):
from styles.colors import TEXT_GREY_HEX, BLACK_HEX
Why this scored 44/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.