[WebAuthN] Support CTAP HID authenticators on macOS
[WebKit-https.git] / Source / WebKit / UIProcess / WebAuthentication / Mock / MockHidConnection.cpp
1 /*
2  * Copyright (C) 2018 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "MockHidConnection.h"
28
29 #if ENABLE(WEB_AUTHN) && PLATFORM(MAC)
30
31 #include <WebCore/AuthenticatorGetInfoResponse.h>
32 #include <WebCore/CBORReader.h>
33 #include <WebCore/FidoConstants.h>
34 #include <wtf/BlockPtr.h>
35 #include <wtf/CryptographicallyRandomNumber.h>
36 #include <wtf/RunLoop.h>
37 #include <wtf/text/Base64.h>
38
39 namespace WebKit {
40 using Mock = MockWebAuthenticationConfiguration::Hid;
41 using namespace WebCore;
42 using namespace cbor;
43 using namespace fido;
44
45 namespace MockHidConnectionInternal {
46 // https://fidoalliance.org/specs/fido-v2.0-ps-20170927/fido-client-to-authenticator-protocol-v2.0-ps-20170927.html#mandatory-commands
47 const size_t CtapChannelIdSize = 4;
48 const uint8_t CtapKeepAliveStatusProcessing = 1;
49 // https://fidoalliance.org/specs/fido-v2.0-ps-20170927/fido-client-to-authenticator-protocol-v2.0-ps-20170927.html#commands
50 const int64_t CtapMakeCredentialRequestOptionsKey = 7;
51 const int64_t CtapGetAssertionRequestOptionsKey = 5;
52 }
53
54 MockHidConnection::MockHidConnection(IOHIDDeviceRef device, const MockWebAuthenticationConfiguration& configuration)
55     : HidConnection(device)
56     , m_configuration(configuration)
57 {
58 }
59
60 void MockHidConnection::initialize()
61 {
62     m_initialized = true;
63 }
64
65 void MockHidConnection::terminate()
66 {
67     m_terminated = true;
68 }
69
70 void MockHidConnection::send(Vector<uint8_t>&& data, DataSentCallback&& callback)
71 {
72     ASSERT(m_initialized);
73     assembleRequest(WTFMove(data));
74
75     auto sent = DataSent::Yes;
76     if (stagesMatch() && m_configuration.hid->error == Mock::Error::DataNotSent)
77         sent = DataSent::No;
78
79     auto task = BlockPtr<void()>::fromCallable([callback = WTFMove(callback), sent]() mutable {
80         ASSERT(!RunLoop::isMain());
81         RunLoop::main().dispatch([callback = WTFMove(callback), sent]() mutable {
82             callback(sent);
83         });
84     });
85     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), task.get());
86 }
87
88 void MockHidConnection::registerDataReceivedCallbackInternal()
89 {
90     if (stagesMatch() && m_configuration.hid->error == Mock::Error::EmptyReport) {
91         receiveReport({ });
92         shouldContinueFeedReports();
93         return;
94     }
95     if (!m_configuration.hid->fastDataArrival)
96         feedReports();
97 }
98
99 void MockHidConnection::assembleRequest(Vector<uint8_t>&& data)
100 {
101     if (!m_requestMessage) {
102         m_requestMessage = FidoHidMessage::createFromSerializedData(data);
103         ASSERT(m_requestMessage);
104     } else {
105         auto status = m_requestMessage->addContinuationPacket(data);
106         ASSERT_UNUSED(status, status);
107     }
108
109     if (m_requestMessage->messageComplete())
110         parseRequest();
111 }
112
113 void MockHidConnection::parseRequest()
114 {
115     using namespace MockHidConnectionInternal;
116
117     ASSERT(m_requestMessage);
118     // Set stages.
119     if (m_requestMessage->cmd() == FidoHidDeviceCommand::kInit) {
120         auto previousSubStage = m_subStage;
121         m_subStage = Mock::SubStage::Init;
122         if (previousSubStage == Mock::SubStage::Msg)
123             m_stage = Mock::Stage::Request;
124     }
125     if (m_requestMessage->cmd() == FidoHidDeviceCommand::kCbor)
126         m_subStage = Mock::SubStage::Msg;
127
128     // Set options.
129     if (m_stage == Mock::Stage::Request && m_subStage == Mock::SubStage::Msg) {
130         m_requireResidentKey = false;
131         m_requireUserVerification = false;
132
133         auto payload = m_requestMessage->getMessagePayload();
134         ASSERT(payload.size());
135         auto cmd = static_cast<CtapRequestCommand>(payload[0]);
136         payload.remove(0);
137         auto requestMap = CBORReader::read(payload);
138         ASSERT(requestMap);
139
140         if (cmd == CtapRequestCommand::kAuthenticatorMakeCredential) {
141             auto it = requestMap->getMap().find(CBORValue(CtapMakeCredentialRequestOptionsKey)); // Find options.
142             if (it != requestMap->getMap().end()) {
143                 auto& optionMap = it->second.getMap();
144
145                 auto itr = optionMap.find(CBORValue(kResidentKeyMapKey));
146                 if (itr != optionMap.end())
147                     m_requireResidentKey = itr->second.getBool();
148
149                 itr = optionMap.find(CBORValue(kUserVerificationMapKey));
150                 if (itr != optionMap.end())
151                     m_requireUserVerification = itr->second.getBool();
152             }
153         }
154
155         if (cmd == CtapRequestCommand::kAuthenticatorGetAssertion) {
156             auto it = requestMap->getMap().find(CBORValue(CtapGetAssertionRequestOptionsKey)); // Find options.
157             if (it != requestMap->getMap().end()) {
158                 auto& optionMap = it->second.getMap();
159                 auto itr = optionMap.find(CBORValue(kUserVerificationMapKey));
160                 if (itr != optionMap.end())
161                     m_requireUserVerification = itr->second.getBool();
162             }
163         }
164     }
165
166     m_currentChannel = m_requestMessage->channelId();
167     m_requestMessage = std::nullopt;
168     if (m_configuration.hid->fastDataArrival)
169         feedReports();
170 }
171
172 void MockHidConnection::feedReports()
173 {
174     using namespace MockHidConnectionInternal;
175
176     if (m_subStage == Mock::SubStage::Init) {
177         Vector<uint8_t> payload;
178         payload.reserveInitialCapacity(kHidInitResponseSize);
179         // FIXME(191533): Use a real nonce.
180         payload.appendVector(Vector<uint8_t>({ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }));
181         payload.grow(kHidInitResponseSize);
182         cryptographicallyRandomValues(payload.data() + payload.size(), CtapChannelIdSize);
183         auto channel = kHidBroadcastChannel;
184         if (stagesMatch() && m_configuration.hid->error == Mock::Error::WrongChannelId)
185             channel--;
186         FidoHidInitPacket initPacket(channel, FidoHidDeviceCommand::kInit, WTFMove(payload), payload.size());
187         receiveReport(initPacket.getSerializedData());
188         shouldContinueFeedReports();
189         return;
190     }
191
192     std::optional<FidoHidMessage> message;
193     if (m_stage == Mock::Stage::Info && m_subStage == Mock::SubStage::Msg) {
194         auto infoData = encodeAsCBOR(AuthenticatorGetInfoResponse({ ProtocolVersion::kCtap }, Vector<uint8_t>(kAaguidLength)));
195         infoData.insert(0, static_cast<uint8_t>(CtapDeviceResponseCode::kSuccess)); // Prepend status code.
196         if (stagesMatch() && m_configuration.hid->error == Mock::Error::WrongChannelId)
197             message = FidoHidMessage::create(m_currentChannel - 1, FidoHidDeviceCommand::kCbor, infoData);
198         else
199             message = FidoHidMessage::create(m_currentChannel, FidoHidDeviceCommand::kCbor, infoData);
200     }
201
202     if (m_stage == Mock::Stage::Request && m_subStage == Mock::SubStage::Msg) {
203         if (m_configuration.hid->keepAlive) {
204             m_configuration.hid->keepAlive = false;
205             FidoHidInitPacket initPacket(m_currentChannel, FidoHidDeviceCommand::kKeepAlive, { CtapKeepAliveStatusProcessing }, 1);
206             receiveReport(initPacket.getSerializedData());
207             continueFeedReports();
208             return;
209         }
210         if (stagesMatch() && m_configuration.hid->error == Mock::Error::UnsupportedOptions && (m_requireResidentKey || m_requireUserVerification))
211             message = FidoHidMessage::create(m_currentChannel, FidoHidDeviceCommand::kCbor, { static_cast<uint8_t>(CtapDeviceResponseCode::kCtap2ErrUnsupportedOption) });
212         else {
213             Vector<uint8_t> payload;
214             auto status = base64Decode(m_configuration.hid->payloadBase64, payload);
215             ASSERT_UNUSED(status, status);
216             message = FidoHidMessage::create(m_currentChannel, FidoHidDeviceCommand::kCbor, payload);
217         }
218     }
219
220     ASSERT(message);
221     bool isFirst = true;
222     while (message->numPackets()) {
223         auto report = message->popNextPacket();
224         if (!isFirst && stagesMatch() && m_configuration.hid->error == Mock::Error::WrongChannelId)
225             report = FidoHidContinuationPacket(m_currentChannel - 1, 0, { }).getSerializedData();
226         // Packets are feed asynchronously to mimic actual data transmission.
227         RunLoop::main().dispatch([report = WTFMove(report), weakThis = makeWeakPtr(*this)]() mutable {
228             if (!weakThis)
229                 return;
230             weakThis->receiveReport(WTFMove(report));
231         });
232         isFirst = false;
233     }
234 }
235
236 bool MockHidConnection::stagesMatch() const
237 {
238     return m_configuration.hid->stage == m_stage && m_configuration.hid->subStage == m_subStage;
239 }
240
241 void MockHidConnection::shouldContinueFeedReports()
242 {
243     if (!m_configuration.hid->continueAfterErrorData)
244         return;
245     m_configuration.hid->continueAfterErrorData = false;
246     m_configuration.hid->error = Mock::Error::Success;
247     continueFeedReports();
248 }
249
250 void MockHidConnection::continueFeedReports()
251 {
252     // Send actual response for the next run.
253     RunLoop::main().dispatch([weakThis = makeWeakPtr(*this)]() mutable {
254         if (!weakThis)
255             return;
256         weakThis->feedReports();
257     });
258 }
259
260 } // namespace WebKit
261
262 #endif // ENABLE(WEB_AUTHN) && PLATFORM(MAC)