The `on_device` field is being moved to PassphraseAck, State messages are removed. Features newly contain `session_id`.pull/803/head
parent
7eb6b14997
commit
90d5cdfd5b
@ -0,0 +1,55 @@
|
||||
from micropython import const
|
||||
|
||||
import storage.device
|
||||
from trezor import wire
|
||||
from trezor.messages.PassphraseAck import PassphraseAck
|
||||
from trezor.messages.PassphraseRequest import PassphraseRequest
|
||||
from trezor.ui.passphrase import CANCELLED, PassphraseKeyboard
|
||||
|
||||
if __debug__:
|
||||
from apps.debug import input_signal
|
||||
|
||||
_MAX_PASSPHRASE_LEN = const(50)
|
||||
|
||||
|
||||
def is_enabled() -> bool:
|
||||
return storage.device.is_passphrase_enabled()
|
||||
|
||||
|
||||
async def get(ctx: wire.Context) -> str:
|
||||
if is_enabled():
|
||||
return await request_from_user(ctx)
|
||||
else:
|
||||
return ""
|
||||
|
||||
|
||||
async def request_from_user(ctx: wire.Context) -> str:
|
||||
request = PassphraseRequest()
|
||||
ack = await ctx.call(request, PassphraseAck)
|
||||
if ack.on_device:
|
||||
if ack.passphrase is not None:
|
||||
raise wire.ProcessError("Passphrase provided when it should not be")
|
||||
passphrase = await request_from_user_on_device(ctx)
|
||||
else:
|
||||
if ack.passphrase is None:
|
||||
raise wire.ProcessError("Passphrase not provided")
|
||||
passphrase = ack.passphrase
|
||||
|
||||
if len(passphrase) > _MAX_PASSPHRASE_LEN:
|
||||
raise wire.DataError("Maximum passphrase length is %d" % _MAX_PASSPHRASE_LEN)
|
||||
|
||||
return passphrase
|
||||
|
||||
|
||||
async def request_from_user_on_device(ctx: wire.Context) -> str:
|
||||
keyboard = PassphraseKeyboard("Enter passphrase", _MAX_PASSPHRASE_LEN)
|
||||
if __debug__:
|
||||
passphrase = await ctx.wait(keyboard, input_signal())
|
||||
else:
|
||||
passphrase = await ctx.wait(keyboard)
|
||||
if passphrase is CANCELLED:
|
||||
raise wire.ActionCancelled("Passphrase entry cancelled")
|
||||
|
||||
assert isinstance(passphrase, str)
|
||||
|
||||
return passphrase
|
@ -1,86 +0,0 @@
|
||||
from micropython import const
|
||||
|
||||
import storage.device
|
||||
from storage import cache
|
||||
from trezor import ui, wire
|
||||
from trezor.messages import ButtonRequestType, PassphraseSourceType
|
||||
from trezor.messages.ButtonAck import ButtonAck
|
||||
from trezor.messages.ButtonRequest import ButtonRequest
|
||||
from trezor.messages.PassphraseAck import PassphraseAck
|
||||
from trezor.messages.PassphraseRequest import PassphraseRequest
|
||||
from trezor.messages.PassphraseStateAck import PassphraseStateAck
|
||||
from trezor.messages.PassphraseStateRequest import PassphraseStateRequest
|
||||
from trezor.ui.passphrase import CANCELLED, PassphraseKeyboard, PassphraseSource
|
||||
from trezor.ui.popup import Popup
|
||||
from trezor.ui.text import Text
|
||||
|
||||
if __debug__:
|
||||
from apps.debug import input_signal
|
||||
|
||||
_MAX_PASSPHRASE_LEN = const(50)
|
||||
|
||||
|
||||
async def protect_by_passphrase(ctx: wire.Context) -> str:
|
||||
if storage.device.has_passphrase():
|
||||
return await request_passphrase(ctx)
|
||||
else:
|
||||
return ""
|
||||
|
||||
|
||||
async def request_passphrase(ctx: wire.Context) -> str:
|
||||
source = storage.device.get_passphrase_source()
|
||||
if source == PassphraseSourceType.ASK:
|
||||
source = await request_passphrase_source(ctx)
|
||||
passphrase = await request_passphrase_ack(
|
||||
ctx, source == PassphraseSourceType.DEVICE
|
||||
)
|
||||
if len(passphrase) > _MAX_PASSPHRASE_LEN:
|
||||
raise wire.DataError("Maximum passphrase length is %d" % _MAX_PASSPHRASE_LEN)
|
||||
return passphrase
|
||||
|
||||
|
||||
async def request_passphrase_source(ctx: wire.Context) -> int:
|
||||
req = ButtonRequest(code=ButtonRequestType.PassphraseType)
|
||||
await ctx.call(req, ButtonAck)
|
||||
|
||||
text = Text("Enter passphrase", ui.ICON_CONFIG)
|
||||
text.normal("Where do you want to", "enter your passphrase?")
|
||||
source = PassphraseSource(text)
|
||||
|
||||
response = await ctx.wait(source)
|
||||
assert isinstance(response, int)
|
||||
return response
|
||||
|
||||
|
||||
async def request_passphrase_ack(ctx: wire.Context, on_device: bool) -> str:
|
||||
if not on_device:
|
||||
text = Text("Passphrase entry", ui.ICON_CONFIG)
|
||||
text.normal("Please type your", "passphrase on the", "connected host.")
|
||||
await Popup(text)
|
||||
|
||||
passphrase_request = PassphraseRequest(on_device=on_device)
|
||||
ack = await ctx.call(passphrase_request, PassphraseAck)
|
||||
|
||||
if on_device:
|
||||
if ack.passphrase is not None:
|
||||
raise wire.ProcessError("Passphrase provided when it should not be")
|
||||
|
||||
keyboard = PassphraseKeyboard("Enter passphrase", _MAX_PASSPHRASE_LEN)
|
||||
if __debug__:
|
||||
passphrase = await ctx.wait(keyboard, input_signal())
|
||||
else:
|
||||
passphrase = await ctx.wait(keyboard)
|
||||
if passphrase is CANCELLED:
|
||||
raise wire.ActionCancelled("Passphrase cancelled")
|
||||
else:
|
||||
if ack.passphrase is None:
|
||||
raise wire.ProcessError("Passphrase not provided")
|
||||
passphrase = ack.passphrase
|
||||
|
||||
assert isinstance(passphrase, str)
|
||||
|
||||
state = cache.get_state(prev_state=ack.state, passphrase=passphrase)
|
||||
state_request = PassphraseStateRequest(state=state)
|
||||
await ctx.call(state_request, PassphraseStateAck)
|
||||
|
||||
return passphrase
|
@ -1,14 +0,0 @@
|
||||
# Automatically generated by pb2py
|
||||
# fmt: off
|
||||
import protobuf as p
|
||||
|
||||
if __debug__:
|
||||
try:
|
||||
from typing import Dict, List # noqa: F401
|
||||
from typing_extensions import Literal # noqa: F401
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
||||
class PassphraseStateAck(p.MessageType):
|
||||
MESSAGE_WIRE_TYPE = 78
|
@ -1,26 +0,0 @@
|
||||
# Automatically generated by pb2py
|
||||
# fmt: off
|
||||
import protobuf as p
|
||||
|
||||
if __debug__:
|
||||
try:
|
||||
from typing import Dict, List # noqa: F401
|
||||
from typing_extensions import Literal # noqa: F401
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
||||
class PassphraseStateRequest(p.MessageType):
|
||||
MESSAGE_WIRE_TYPE = 77
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
state: bytes = None,
|
||||
) -> None:
|
||||
self.state = state
|
||||
|
||||
@classmethod
|
||||
def get_fields(cls) -> Dict:
|
||||
return {
|
||||
1: ('state', p.BytesType, 0),
|
||||
}
|
@ -0,0 +1,9 @@
|
||||
# Communication
|
||||
|
||||
_Note: In this section we describe the internal functioning of the communication protocol. If you wish to implement Trezor support you should use [Connect](https://github.com/trezor/connect/) or [python-trezor](https://pypi.org/project/trezor/), which will do all this hard work for you._
|
||||
|
||||
We use [Protobuf v2](https://developers.google.com/protocol-buffers/) for host-device communication. The communication cycle is very simple, Trezor receives a message (request), acts on it and responds with another one (response). Trezor on its own is incapable of initiating the communication.
|
||||
|
||||
## Definitions
|
||||
|
||||
Protobuf messages are defined in the [Common](https://github.com/trezor/trezor-firmware/tree/master/common) project, which is part of this monorepo. This repository is also exported to [trezor/trezor-common](https://github.com/trezor/trezor-common) to be used by third parties, which prefer not to include the whole monorepo. That copy is read-only mirror and all changes are happening in this monorepo.
|
@ -0,0 +1,64 @@
|
||||
# Passphrase
|
||||
|
||||
As of \[versions TBD\] we have changed how [passphrase](https://wiki.trezor.io/Passphrase) is communicated between the Host and the Device.
|
||||
|
||||
Passphrase is very tightly coupled with _sessions_. The reader is encouraged to read on that topic first in the [sessions.md](sessions.md) section.
|
||||
|
||||
## Scheme
|
||||
|
||||
As soon as Trezor needs the passphrase to do BIP-39/SLIP-39 derivations it prompts the user for passphrase.
|
||||
|
||||
```
|
||||
GetAddress(...)
|
||||
---------> PassphraseRequest()
|
||||
<---------
|
||||
PassphraseAck
|
||||
(str passphrase, bool on_device)
|
||||
---------> Address(...)
|
||||
<---------
|
||||
```
|
||||
|
||||
In the default Trezor setting, the passphrase is obtained from the Host. Trezor sends a PassphraseRequest message and awaits PassphraseAck as a response. This message contains field `passphrase` to transmit it or it has `on_device` boolean flag to indicate that the user wishes to enter the passphrase on Trezor instead. Setting both `passphrase` and `on_device` to true is forbidden.
|
||||
|
||||
Note that this has changed as of TBD. In previous firmware versions the `on_device` flag was in the PassphraseRequest message, since this decision has been made on Trezor. We also had two additional messages PassphraseStateRequest and PassphraseStateAck which were removed.
|
||||
|
||||
## Example
|
||||
|
||||
On an initialized device with passphrase enabled a common communication starts like this:
|
||||
|
||||
```
|
||||
Initialize()
|
||||
---------> Features(..., session_id)
|
||||
<---------
|
||||
GetAddress(...)
|
||||
---------> PassphraseRequest()
|
||||
<---------
|
||||
PassphraseAck(...)
|
||||
---------> Address(...)
|
||||
<---------
|
||||
```
|
||||
|
||||
The device requested the passphrase since the BIP-39/SLIP-39 seed is not yet cached. After this workflow the seed is cached and the passphrase will therefore never be requested again unless the session is cleared*.
|
||||
|
||||
Since we do not have sessions, the Host can not be sure that someone else has not used the device and applied another session id (e.g. changed the Passphrase). To work around this we send the session id again on every subsequent message. See more on that in [session.md]().
|
||||
|
||||
```
|
||||
Initialize(session_id)
|
||||
---------> Features(..., session_id)
|
||||
<---------
|
||||
GetPublicKey(...)
|
||||
---------> PublicKey(...)
|
||||
<---------
|
||||
```
|
||||
|
||||
As long as the session_id in `Initialize` is the same as the one Trezor stores internally, Trezor guarantees the same passphrase is being used.
|
||||
|
||||
----
|
||||
|
||||
\* There is one exception and that is Cardano. Because Cardano has a different BIP-39/SLIP-39 derivation scheme for passphrase we can not use the cached seed. As a workaround we prompt for the passphrase again in such case and cache the cardano seed in the cardano app directly.
|
||||
|
||||
## Passphrase always on device
|
||||
|
||||
User might want to enforce the passphrase entry on the device every time without the hassle of instructing the Host to do so.
|
||||
|
||||
For such cases the user may apply the *Passphrase always on device* setting TODO: Name. As the name suggests, with this setting the passphrase is prompted on the device right away and no PassphraseRequest/PassphraseAck messages are exchanged.
|
@ -0,0 +1,36 @@
|
||||
# Sessions (the lack of them)
|
||||
|
||||
Currently the communication protocol lacks sessions, which are planned to be introduced in the near future (see [#79](https://github.com/trezor/trezor-firmware/issues/79)).
|
||||
|
||||
To ensure the device is in the expected state we use something called _session_id_. Session id is a 32 bytes long random blob which identifies the internal device state (mainly its caches). This is primarily useful for passphrase to make sure the same passphrase is cached in the device as the one the user entered a few minutes ago. See [passphrase.md](passphrase.md) for more on that.
|
||||
|
||||
On first initialization the Host does not have a session id and starts the communication with an empty Initialize:
|
||||
|
||||
```
|
||||
Initialize()
|
||||
---------> Features(..., session_id)
|
||||
<---------
|
||||
```
|
||||
|
||||
After the first Features message is received the Host might store the session_id. To ensure the device state Host must send the Initialize message again including that particular session_id:
|
||||
|
||||
```
|
||||
Initialize(session_id)
|
||||
---------> Features(..., session_id)
|
||||
<---------
|
||||
Request
|
||||
---------> Response
|
||||
<---------
|
||||
```
|
||||
|
||||
So to make sure the device state has not changed, the Host must send the Initialize message with the correctly stored session_id before each request. Yes, this is stupid.
|
||||
|
||||
As mentioned, sessions will be introduced soon™ and fix that. We will probably take the first few bytes of the session_id, declare it a session id, and the rest will remain, without the annoying requirement of sending Initialize before every message.
|
||||
|
||||
----
|
||||
|
||||
The session is terminated and therefore the caches are cleared if:
|
||||
- Initialize.session_id is empty.
|
||||
- Initialize.session_id is different then the one cached in Trezor.
|
||||
- Trezor is replugged (session is not persistent).
|
||||
- ClearSession is received.
|
@ -1,14 +0,0 @@
|
||||
# Automatically generated by pb2py
|
||||
# fmt: off
|
||||
from .. import protobuf as p
|
||||
|
||||
if __debug__:
|
||||
try:
|
||||
from typing import Dict, List # noqa: F401
|
||||
from typing_extensions import Literal # noqa: F401
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
||||
class PassphraseStateAck(p.MessageType):
|
||||
MESSAGE_WIRE_TYPE = 78
|
@ -1,26 +0,0 @@
|
||||
# Automatically generated by pb2py
|
||||
# fmt: off
|
||||
from .. import protobuf as p
|
||||
|
||||
if __debug__:
|
||||
try:
|
||||
from typing import Dict, List # noqa: F401
|
||||
from typing_extensions import Literal # noqa: F401
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
|
||||
class PassphraseStateRequest(p.MessageType):
|
||||
MESSAGE_WIRE_TYPE = 77
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
state: bytes = None,
|
||||
) -> None:
|
||||
self.state = state
|
||||
|
||||
@classmethod
|
||||
def get_fields(cls) -> Dict:
|
||||
return {
|
||||
1: ('state', p.BytesType, 0),
|
||||
}
|
@ -0,0 +1,123 @@
|
||||
# This file is part of the Trezor project.
|
||||
#
|
||||
# Copyright (C) 2012-2019 SatoshiLabs and contributors
|
||||
#
|
||||
# This library is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser General Public License version 3
|
||||
# as published by the Free Software Foundation.
|
||||
#
|
||||
# This library is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the License along with this library.
|
||||
# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
|
||||
|
||||
import pytest
|
||||
|
||||
from trezorlib import messages
|
||||
from trezorlib.tools import parse_path
|
||||
|
||||
|
||||
def _get_xpub(client, passphrase):
|
||||
response = client.call_raw(
|
||||
messages.GetPublicKey(address_n=parse_path("44'/0'/0'"), coin_name="Bitcoin")
|
||||
)
|
||||
if passphrase is not None:
|
||||
assert isinstance(response, messages.PassphraseRequest)
|
||||
response = client.call_raw(messages.PassphraseAck(passphrase=passphrase))
|
||||
assert isinstance(response, messages.PublicKey)
|
||||
return response.xpub
|
||||
|
||||
|
||||
@pytest.mark.skip_t1 # TODO
|
||||
@pytest.mark.setup_client(passphrase=True)
|
||||
def test_session_with_passphrase(client):
|
||||
# Let's start the communication by calling Initialize.
|
||||
response = client.call_raw(messages.Initialize())
|
||||
assert isinstance(response, messages.Features)
|
||||
session_id = response.session_id
|
||||
assert len(session_id) == 32
|
||||
|
||||
# GetPublicKey requires passphrase and since it is not cached,
|
||||
# Trezor will prompt for it.
|
||||
xpub = _get_xpub(client, passphrase="A")
|
||||
assert (
|
||||
xpub
|
||||
== "xpub6CekxGcnqnJ6osfY4Rrq7W5ogFtR54KUvz4H16XzaQuukMFZCGebEpVznfq4yFcKEmYyShwj2UKjL7CazuNSuhdkofF4mHabHkLxCMVvsqG"
|
||||
)
|
||||
|
||||
# Call Initialize again, this time with the received session id and then call
|
||||
# GetPublicKey. The passphrase should be cached now so Trezor must
|
||||
# not ask for it again, whilst returning the same xpub.
|
||||
response = client.call_raw(messages.Initialize(session_id=session_id))
|
||||
assert isinstance(response, messages.Features)
|
||||
xpub = _get_xpub(client, passphrase=None)
|
||||
assert (
|
||||
xpub
|
||||
== "xpub6CekxGcnqnJ6osfY4Rrq7W5ogFtR54KUvz4H16XzaQuukMFZCGebEpVznfq4yFcKEmYyShwj2UKjL7CazuNSuhdkofF4mHabHkLxCMVvsqG"
|
||||
)
|
||||
|
||||
# If we set session id in Initialize to None, the cache will be cleared
|
||||
# and Trezor will ask for the passphrase again.
|
||||
response = client.call_raw(messages.Initialize(session_id=None))
|
||||
assert isinstance(response, messages.Features)
|
||||
xpub = _get_xpub(client, passphrase="A")
|
||||
assert (
|
||||
xpub
|
||||
== "xpub6CekxGcnqnJ6osfY4Rrq7W5ogFtR54KUvz4H16XzaQuukMFZCGebEpVznfq4yFcKEmYyShwj2UKjL7CazuNSuhdkofF4mHabHkLxCMVvsqG"
|
||||
)
|
||||
|
||||
# Unknown session id is the same as setting it to None.
|
||||
response = client.call_raw(messages.Initialize(session_id=b"X" * 32))
|
||||
assert isinstance(response, messages.Features)
|
||||
xpub = _get_xpub(client, passphrase="A")
|
||||
assert (
|
||||
xpub
|
||||
== "xpub6CekxGcnqnJ6osfY4Rrq7W5ogFtR54KUvz4H16XzaQuukMFZCGebEpVznfq4yFcKEmYyShwj2UKjL7CazuNSuhdkofF4mHabHkLxCMVvsqG"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skip_t1 # TODO
|
||||
@pytest.mark.setup_client()
|
||||
def test_session_enable_passphrase(client):
|
||||
# Let's start the communication by calling Initialize.
|
||||
response = client.call_raw(messages.Initialize())
|
||||
assert isinstance(response, messages.Features)
|
||||
session_id = response.session_id
|
||||
assert len(session_id) == 32
|
||||
|
||||
# Trezor will not prompt for passphrase because it is turned off.
|
||||
xpub = _get_xpub(client, passphrase=None)
|
||||
assert (
|
||||
xpub
|
||||
== "xpub6BiVtCpG9fQPxnPmHXG8PhtzQdWC2Su4qWu6XW9tpWFYhxydCLJGrWBJZ5H6qTAHdPQ7pQhtpjiYZVZARo14qHiay2fvrX996oEP42u8wZy"
|
||||
)
|
||||
|
||||
# Turn on passphrase.
|
||||
response = client.call_raw(messages.ApplySettings(use_passphrase=True))
|
||||
assert isinstance(response, messages.ButtonRequest) # confirm dialog
|
||||
client.debug.press_yes()
|
||||
response = client.call_raw(messages.ButtonAck())
|
||||
assert isinstance(response, messages.Success)
|
||||
|
||||
# The session id is unchanged, therefore we do not prompt for the passphrase.
|
||||
response = client.call_raw(messages.Initialize(session_id=session_id))
|
||||
xpub = _get_xpub(client, passphrase=None)
|
||||
assert isinstance(response, messages.Features)
|
||||
assert session_id == response.session_id
|
||||
assert (
|
||||
xpub
|
||||
== "xpub6BiVtCpG9fQPxnPmHXG8PhtzQdWC2Su4qWu6XW9tpWFYhxydCLJGrWBJZ5H6qTAHdPQ7pQhtpjiYZVZARo14qHiay2fvrX996oEP42u8wZy"
|
||||
)
|
||||
|
||||
# We clear the session id now, so the passphrase should be asked.
|
||||
response = client.call_raw(messages.Initialize())
|
||||
xpub = _get_xpub(client, passphrase="A")
|
||||
assert isinstance(response, messages.Features)
|
||||
assert session_id != response.session_id
|
||||
assert (
|
||||
xpub
|
||||
== "xpub6CekxGcnqnJ6osfY4Rrq7W5ogFtR54KUvz4H16XzaQuukMFZCGebEpVznfq4yFcKEmYyShwj2UKjL7CazuNSuhdkofF4mHabHkLxCMVvsqG"
|
||||
)
|
Loading…
Reference in new issue