<!-- PDF-show
\newpage
-->

Note: this flow is currently not being actively maintained.

# PID Option B: Authenticated Channel with eID Card (B) with mDoc, ISO REST API

## Basic Idea

Presentation of PID and QEAAs (EAAs) reusing the entire System for German eID or Smart-eID for PID. The protocol is based on ISO standards ISO 18013-5/-7 and ISO 23220 and has two options for QEAA handling:

1. get PID and QEAA in one shot (request/response)
2. get PID and QEAA independent of each other (multiple requests/responses)

## Cryptographic Formats

Long-Term keys:

* PID Provider has long-term key pair $(pp\_pub, pp\_priv)$ that can be verified using $x5chain$
* RP has long-term key pair $(rp\_pub, rp\_priv)$

Transaction-specific keys:

* **RP contribution to HMAC key:** RP generates ephemeral key pair $(rp\_eph\_pub, rp\_eph\_priv)$
* **PID Provider contribution to HMAC key:** PID provider generates ephemeral device key pair $(dev\_eph\_pub, dev\_eph\_priv)$ for each request

Artifacts:

* $issuerAuth := \text{sign}(dev\_eph\_pub, x5chain)_{pp\_priv}$
* $hmac\_key := \text{ecdh}(rp\_eph\_pub, dev\_eph\_priv)$
* $deviceAuth := \text{hmac}(\mathit{eID\_data}, \mathit{SessionTranscript})_{hmac\_key}$

<!-- PDF-show
\newpage
\blandscape
-->

## Sequence Diagram

[User Journey: PID Presentation - Authenticated Channel - eID Card](../user_journeys/PID-AuthenticatedChannel-eIDcard-presentation.png)

```plantuml
@startuml

'Ensure messages are not too wide
skinparam maxMessageSize 200
skinparam wrapWidth 300

'Macro for colored [TLS] block
!function tls()
!return "<color #118888>[TLS]</color>"
!endfunction

'Align text on arrows to center
skinparam sequenceMessageAlign center

'padding between boxes
skinparam BoxPadding 100

actor User
participant "Browser App\n(same device)" as IB
participant WS [
                Relying Party
                ----
                ""Long-term Key: (//rp_pub//, //rp_priv//)""
                ""for Reader Authentication:""
]
participant MDOC as "User's EUDI Wallet Instance\n(eID-Client)"
participant IS  [
                PID Provider
                (eService+eID Server)
                ----
                ""Long-term Key: (//pp_pub//, //pp_priv//)""
                ""for mDoc Authentication (ECDH for HMAC):""
            ]

autonumber "<b>(000)"
User --> IB: browse \nto application
hnote over IB #dfd: Screen: same_device_relying_party_start

group start session acc. to ISO/IEC 23220-4 and ISO/IEC 18013-7
  IB -> WS: tls() HTTP **GET** <rp-website>

  WS -> WS: create ISO-RestAPI-sessionID\nand ReaderEngagement
note right
ReaderEngagement contains:
- ephemeral session keys for
session encryption Reader.EDeviceKey.pub
- referrer url incl. sessionID, e.g., https://relying-party-service.de/{uuid}/
- OriginInfo

end note

WS --> IB: tls() HTTP 200 \nparams("HTML with link to mdoc://base64(ReaderEngagement)")

IB -> MDOC: mdoc:// \nparams("/base64(ReaderEngagement)")
hnote over MDOC #dfd: Screen: launch_wallet
activate MDOC
User --> MDOC: user consent (unlock wallet)
hnote over MDOC #dfd: Screen: unlock_wallet

MDOC -> MDOC: generate ephemeral Session Keys\ncreate Device Engagement

MDOC -> WS: tls() HTTP **POST** params("MessageData")
note right
MessageData contains
- deviceEngagementBytes with
- RetrievalMethod == RestAPI
- ephemeral session key Wallet.EDeviceKey.pub
- MacKeySupport := TRUE
- MacKeyCurves := []
- OriginInfo.ReferrerURL := https://relying-party-service.de/{uuid}/
- OriginInfo.BaseURL := https://relying-party-service.de
end note

'newpage

WS -> WS: validate OriginInfo.ReferrerURL and OriginInfo.BaseURL with OriginIfo from ReaderEngagement
note left
  recognize MiTM attack
end note

WS -> WS: calculate mdoc_request for PID and mDL
note left
  mdoc_request contains
  * ephemeral MacKeys Reader.MacKey.pub if DeviceEngagement requests Mac support
  * ReaderAuthentication  :_= COSE_Sign1 with detached  ReaderAuthenticationBytes (incl. SessionTranscript)
end note
WS -> WS:  perform key agreement (Wallet.EDeviceKey.pub * EReaderKey.priv) and HKDF for S.key
WS -> WS : SessionData := enc(S.key, mdoc_request)
WS --> MDOC: tls() HTTP **200** params("SesssionData")

MDOC -> MDOC: perform key agreement (EDeviceKey.priv * Reader.EReaderKey.pub) S.key
MDOC -> MDOC: mdoc_request := dec(S.key, SesssionData)
MDOC -> MDOC: calculate SessionTranscript

MDOC -> MDOC: validate ReaderAuthentication
note right
Signature over detached  ReaderAuthenticationBytes (incl. SessionTranscript)
ReaderAuthenticationBytes needs to be rebuilt for validation on Device side
end note
hnote over MDOC #dfd: Screen: consent_present_credential

MDOC -> IS: tls() HTTP GET /tcToken params("Reader.MacKey.pub, SessionTranscript")
note right #fc7: Security risk: No PoP for MacKey used here; can an attacker forward a MacKey from a different session to the PID Provider?

activate IS

hnote over MDOC #dfd: Screen: eid_start

'newpage

group Read eID or Smart eID acc. to BSI TR-03130
    MDOC <-> IS : tlspsk() eID Process
    note left : only the required PID attributes are requested
    hnote over MDOC #dfd: Screen: eid_pin
    hnote over MDOC #dfd: Screen: eid_nfc_data
IS -> IS: store eID data
end

end

group Prepare response for PID acc. ISO 18013-7 and ISO 23220-4 in mdoc format (REST-API)

IS -> IS: generate MDoc-Device Key-Pair and create MSO with MDoc.EDeviceKey.pub but w/o data items
note left
the Device Key pair shall be generated within an HSM and will be referenced by the SessionID
end note

IS -> IS:  perform key agreement (Reader.MacKey.pub * MDoc.EDeviceKey.priv) and HKDF for HMAC
IS --> IS: calculate HMAC for DeviceAuth
IS -> IS : create mDoc-Response from PID incl. DeviceAuth
note over IS #AAFFAA: user data is not signed, but HMACd
MDOC -> IS: tls() HTTP **GET** /pid
note left #AAFFAA
  trust relation between wallet and PID-Provider needs to be defined,
  options are reuse existing TLS-PSK channel for mutual authentication
  or  mTLS
end note

IS --> MDOC: tls() HTTP **200** params("mdoc-response")

note over MDOC : optional: get QEAA

MDOC -> MDOC: SessionData := enc(S.key, mdoc-response)
MDOC -> WS: tls() HTTP **POST** params("SessionData")

'newpage

WS -> WS:  perform key agreement (Reader.MacKey.pub * MDoc.EDeviceKey.priv) and HKDF for HMAC
WS -> WS:  mdoc _response := dec(S.key, SessionData)
WS -> WS:  verify HMAC for DeviveAuth in mdoc _response
end

group request addtional mDoc from wallet

WS -> WS: SessionData := enc(S.key, mdoc-request)
note left
  reuse S.key from step 011
end note
WS --> MDOC : tls() HTTP 200 params("SessionData")

WS -> WS: SessionData := enc(S.key, mdoc-request)
note right: Question: This step should probably be something else?
note left
  reuse S.key from step 011
end note
MDOC -> WS: tls()  HTTP **POST** params("SessionData")
MDOC -> MDOC: SessionData := enc(S.key, mdoc-response)
note left
  reuse S.key from step 014
end note
WS --> MDOC: tls()  HTTP **200**

end
deactivate MDOC

note over WS
 TLS session from step 002 needs to be matched with ISO REST session (long polling, web sockets or similar).
end note
note over WS #FAA: Security risk: No protection against relaying requests yet (binding to browser session).

hnote over MDOC #dfd: Screen: success_redirect
hnote over IB #dfd: Screen: same_device_relying_party_identified

@enduml
```

<!-- PDF-show
\elandscape
-->

## Step-by-Step Description

User browses to Relying Party (RP) website

1. open the Browser app
2. request RP website within the Browser app
3. RP generates an ephemeral session key pair and a ReaderEngagement structure according to ISO 18013-7 annex A.1
4. ReaderEngagement contains:
   - the public ephemeral session key
   - an OriginInfo structure with a referrer-url incl. a REST-API sessionID, e.g., `https://rp.example.com/mdoc-reader/1234`
5. RP returns a HTML page to the browser containing a link to the wallet app (e.g., `mdoc://enc(base64,ReaderEngagement)`)
   - The user clicks on the link and the wallet will be launched
   - The wallet app retrieves the Authorization Request from the RP website (e.g., `https://rp.example.com/mdoc-reader/1234`) and the public ephemeral session key
6. The user might be asked for consent to unlock the wallet (needs to be discussed!)
7. RP generates an ephemeral session key pair and a DeviceEngagement structure according to ISO 18013-7 annex A.2
   - DeviceEngagement indicates support of Mac keys for mDoc authentication
   - DeviceEngagement contains an OriginIfo structure. This value shall not be determined using data from the ReaderEngagement structure.
8. Wallet sends a CBOR encoded message data structure via HTTPS **POST** to the RP containing the DeviceEngagement structure
9. RP validates OriginInfo from DeviceEngagement with provided ReaderEngagement from step 2
10. RP calculates mDoc-request
    - just for PID or PID and QEAA (e.g., mDL)
    - mDoc-request contains items to request, public Reader Mac-key and ReaderAuthentication
11. RP performs ECDH key agreement and calculates the symmetric session key S.key
12. RP encrypts the mDoc-request with S.key
13. RP returns the mDoc-request to the wallet
14. wallet performs ECDH key agreement and calculates the symmetric session key S.key
15. wallet decrypts mDoc-request with S.key
16. wallet calculates SessionTranscript acc ISO 18013-7 A.8
17. wallet performs Reader Authentication
18. wallet starts eID-process if mdoc-request contains PID request
19. wallet performs eID process acc. TR 03124
20. PID-Provider stores eID data temporarily
21. PID-Provider generates mDoc authentication key pair and creates an MSO structure, this might also be done for one time, e.g., during service startup
22. optional: perform reading of additional QEAA's or EAA's by ruse of existing TLS-PSK channel
23. PID-Provider performs ECDH and HKDF for HMAC key
24. PID-Provider calculates HMAC for Device Authentication using the SessionTranscript
25. PID-Provider calculates mDoc-response
    - for PID and QEAA, if optional step 22. has been performed
    - just for PID, if optional step 22. has been omitted
26. wallet encrypts mDoc-response using session key S.key
27. wallet posts the mDoc-response to the RP
28. RP decrypts mDoc-response using S.key
29. RP performs ECDH and HKDF for HMAC key
30. RP verifies mDoc authentication
31. optional: RP calculates an additional mDoc-request
32. optional: RP returns additional mDoc-request to the wallet
33. optional: Wallet encrypts mdoc-response
34. wallet posts mdoc-response to RP
35. RP ends the session

## Implementation Considerations

*TBD*

## Usability Considerations

The user expects a simple and intuitive user interface with the same or similar user experience as for other security-critical applications such as banking apps.
That means, that the entire session will be performed within the same instance of a browser window or tab. This applies in particular for the same-device flow as well as for the cross-device flow. For both flows, the user starts the session by requesting the website in step 002 and expects to get the result in the same browser window or tab.
Step 005 might be a deep link within a website behind a button for the same device flow or a qr-code with identical information `mdoc://enc(base64,ReaderEngagement)` for the cross-device flow.
At the end of the session the content of the browser window or tab from step 004 needs to be updated. To achieve this, at least 2 options are available:

1. using long polling
2. using websockets with notifications


The cross-device flow is mandatory for EUID wallet according to document "EUDIW Design Guide_Data Sharing Scenarios-v1.00_clean.doc".

- Unlock wallet (Step 006) should probably be moved to a later point in the flow, ideally just before using the credential.

## Security Considerations

**SessionTranscript:** "Device Retrieval" with remote CA keys is defined
by the ISO standards 18013-7 and 23220-4. The SessionTranscript is used within
the authentication structure for the reader mDoc-request (ReaderAuthentication)
and the authentication structure for the mDoc-response structure (DeviceAuthentication). The aim is the cryptographical binding of the data
exchange protocol (request/response) with the underlying transport protocol
REST-API. The
SessionTranscript shall be created independently on each site of the
communication channel.

<!-- Note: "SHA256(ReaderEngagementBytes)" breaks word-wrapping in PDF output, adding some spaces to it, fixes it. -->

- The SessionTranscript structure contains a ReaderEngagementHashBytes structure calculated using SHA256( ReaderEngagementBytes ) where ReaderEngagement contains the ephemeral RP public key (EReaderKeyBytes) and the URI of the RP website(TestApiOptions).
- The hashing of ReaderEngagementBytes prevents the leakage of session information from the Relying Party to the PID-Provider, for privacy reasons.

**Cross-device Flow** is mandatory for the EUID wallet. The proposed user flow as discussed in Usability Considerations (above) does not solve the problem of session hijacking by an attacker.
Compared to the user experience to banking apps in combination with banking services, the RP does not know the wallet.

**Proof of Possession (PoP)** requires a kind of key attestation, which is not yet defined.

## Privacy Considerations

- Selective Disclosure is achieved by ensuring that the credential contains only those data items (claims) that are requested by the RP. The list of requested claims is part of the request to the PID Provider.