[WebAuthN] Import U2F command/response converters from Chromium
[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 <WebCore/WebAuthenticationConstants.h>
35 #include <wtf/BlockPtr.h>
36 #include <wtf/CryptographicallyRandomNumber.h>
37 #include <wtf/RunLoop.h>
38 #include <wtf/text/Base64.h>
39
40 namespace WebKit {
41 using Mock = MockWebAuthenticationConfiguration::Hid;
42 using namespace WebCore;
43 using namespace cbor;
44 using namespace fido;
45
46 namespace MockHidConnectionInternal {
47 // https://fidoalliance.org/specs/fido-v2.0-ps-20170927/fido-client-to-authenticator-protocol-v2.0-ps-20170927.html#mandatory-commands
48 const size_t CtapChannelIdSize = 4;
49 const uint8_t CtapKeepAliveStatusProcessing = 1;
50 // https://fidoalliance.org/specs/fido-v2.0-ps-20170927/fido-client-to-authenticator-protocol-v2.0-ps-20170927.html#commands
51 const int64_t CtapMakeCredentialRequestOptionsKey = 7;
52 const int64_t CtapGetAssertionRequestOptionsKey = 5;
53 }
54
55 MockHidConnection::MockHidConnection(IOHIDDeviceRef device, const MockWebAuthenticationConfiguration& configuration)
56     : HidConnection(device)
57     , m_configuration(configuration)
58 {
59 }
60
61 void MockHidConnection::initialize()
62 {
63     m_initialized = true;
64 }
65
66 void MockHidConnection::terminate()
67 {
68     m_terminated = true;
69 }
70
71 void MockHidConnection::send(Vector<uint8_t>&& data, DataSentCallback&& callback)
72 {
73     ASSERT(m_initialized);
74     auto task = makeBlockPtr([weakThis = makeWeakPtr(*this), data = WTFMove(data), callback = WTFMove(callback)]() mutable {
75         ASSERT(!RunLoop::isMain());
76         RunLoop::main().dispatch([weakThis, data = WTFMove(data), callback = WTFMove(callback)]() mutable {
77             if (!weakThis) {
78                 callback(DataSent::No);
79                 return;
80             }
81
82             weakThis->assembleRequest(WTFMove(data));
83
84             auto sent = DataSent::Yes;
85             if (weakThis->stagesMatch() && weakThis->m_configuration.hid->error == Mock::Error::DataNotSent)
86                 sent = DataSent::No;
87             callback(sent);
88         });
89     });
90     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), task.get());
91 }
92
93 void MockHidConnection::registerDataReceivedCallbackInternal()
94 {
95     if (stagesMatch() && m_configuration.hid->error == Mock::Error::EmptyReport) {
96         receiveReport({ });
97         shouldContinueFeedReports();
98         return;
99     }
100     if (!m_configuration.hid->fastDataArrival)
101         feedReports();
102 }
103
104 void MockHidConnection::assembleRequest(Vector<uint8_t>&& data)
105 {
106     if (!m_requestMessage) {
107         m_requestMessage = FidoHidMessage::createFromSerializedData(data);
108         ASSERT(m_requestMessage);
109     } else {
110         auto status = m_requestMessage->addContinuationPacket(data);
111         ASSERT_UNUSED(status, status);
112     }
113
114     if (m_requestMessage->messageComplete())
115         parseRequest();
116 }
117
118 void MockHidConnection::parseRequest()
119 {
120     using namespace MockHidConnectionInternal;
121
122     ASSERT(m_requestMessage);
123     // Set stages.
124     if (m_requestMessage->cmd() == FidoHidDeviceCommand::kInit) {
125         auto previousSubStage = m_subStage;
126         m_subStage = Mock::SubStage::Init;
127         if (previousSubStage == Mock::SubStage::Msg)
128             m_stage = Mock::Stage::Request;
129     }
130     if (m_requestMessage->cmd() == FidoHidDeviceCommand::kCbor)
131         m_subStage = Mock::SubStage::Msg;
132
133     // Set options.
134     if (m_stage == Mock::Stage::Request && m_subStage == Mock::SubStage::Msg) {
135         m_requireResidentKey = false;
136         m_requireUserVerification = false;
137
138         auto payload = m_requestMessage->getMessagePayload();
139         ASSERT(payload.size());
140         auto cmd = static_cast<CtapRequestCommand>(payload[0]);
141         payload.remove(0);
142         auto requestMap = CBORReader::read(payload);
143         ASSERT(requestMap);
144
145         if (cmd == CtapRequestCommand::kAuthenticatorMakeCredential) {
146             auto it = requestMap->getMap().find(CBORValue(CtapMakeCredentialRequestOptionsKey)); // Find options.
147             if (it != requestMap->getMap().end()) {
148                 auto& optionMap = it->second.getMap();
149
150                 auto itr = optionMap.find(CBORValue(kResidentKeyMapKey));
151                 if (itr != optionMap.end())
152                     m_requireResidentKey = itr->second.getBool();
153
154                 itr = optionMap.find(CBORValue(kUserVerificationMapKey));
155                 if (itr != optionMap.end())
156                     m_requireUserVerification = itr->second.getBool();
157             }
158         }
159
160         if (cmd == CtapRequestCommand::kAuthenticatorGetAssertion) {
161             auto it = requestMap->getMap().find(CBORValue(CtapGetAssertionRequestOptionsKey)); // Find options.
162             if (it != requestMap->getMap().end()) {
163                 auto& optionMap = it->second.getMap();
164                 auto itr = optionMap.find(CBORValue(kUserVerificationMapKey));
165                 if (itr != optionMap.end())
166                     m_requireUserVerification = itr->second.getBool();
167             }
168         }
169     }
170
171     // Store nonce.
172     if (m_subStage == Mock::SubStage::Init) {
173         m_nonce = m_requestMessage->getMessagePayload();
174         ASSERT(m_nonce.size() == kHidInitNonceLength);
175     }
176
177     m_currentChannel = m_requestMessage->channelId();
178     m_requestMessage = WTF::nullopt;
179     if (m_configuration.hid->fastDataArrival)
180         feedReports();
181 }
182
183 void MockHidConnection::feedReports()
184 {
185     using namespace MockHidConnectionInternal;
186
187     if (m_subStage == Mock::SubStage::Init) {
188         Vector<uint8_t> payload;
189         payload.reserveInitialCapacity(kHidInitResponseSize);
190         payload.appendVector(m_nonce);
191         if (stagesMatch() && m_configuration.hid->error == Mock::Error::WrongNonce)
192             payload[0]--;
193         payload.grow(kHidInitResponseSize);
194         cryptographicallyRandomValues(payload.data() + payload.size(), CtapChannelIdSize);
195         auto channel = kHidBroadcastChannel;
196         if (stagesMatch() && m_configuration.hid->error == Mock::Error::WrongChannelId)
197             channel--;
198         FidoHidInitPacket initPacket(channel, FidoHidDeviceCommand::kInit, WTFMove(payload), payload.size());
199         receiveReport(initPacket.getSerializedData());
200         shouldContinueFeedReports();
201         return;
202     }
203
204     Optional<FidoHidMessage> message;
205     if (m_stage == Mock::Stage::Info && m_subStage == Mock::SubStage::Msg) {
206         auto infoData = encodeAsCBOR(AuthenticatorGetInfoResponse({ ProtocolVersion::kCtap }, Vector<uint8_t>(aaguidLength, 0u)));
207         infoData.insert(0, static_cast<uint8_t>(CtapDeviceResponseCode::kSuccess)); // Prepend status code.
208         if (stagesMatch() && m_configuration.hid->error == Mock::Error::WrongChannelId)
209             message = FidoHidMessage::create(m_currentChannel - 1, FidoHidDeviceCommand::kCbor, infoData);
210         else
211             message = FidoHidMessage::create(m_currentChannel, FidoHidDeviceCommand::kCbor, infoData);
212     }
213
214     if (m_stage == Mock::Stage::Request && m_subStage == Mock::SubStage::Msg) {
215         if (m_configuration.hid->keepAlive) {
216             m_configuration.hid->keepAlive = false;
217             FidoHidInitPacket initPacket(m_currentChannel, FidoHidDeviceCommand::kKeepAlive, { CtapKeepAliveStatusProcessing }, 1);
218             receiveReport(initPacket.getSerializedData());
219             continueFeedReports();
220             return;
221         }
222         if (stagesMatch() && m_configuration.hid->error == Mock::Error::UnsupportedOptions && (m_requireResidentKey || m_requireUserVerification))
223             message = FidoHidMessage::create(m_currentChannel, FidoHidDeviceCommand::kCbor, { static_cast<uint8_t>(CtapDeviceResponseCode::kCtap2ErrUnsupportedOption) });
224         else {
225             Vector<uint8_t> payload;
226             auto status = base64Decode(m_configuration.hid->payloadBase64, payload);
227             ASSERT_UNUSED(status, status);
228             message = FidoHidMessage::create(m_currentChannel, FidoHidDeviceCommand::kCbor, payload);
229         }
230     }
231
232     ASSERT(message);
233     bool isFirst = true;
234     while (message->numPackets()) {
235         auto report = message->popNextPacket();
236         if (!isFirst && stagesMatch() && m_configuration.hid->error == Mock::Error::WrongChannelId)
237             report = FidoHidContinuationPacket(m_currentChannel - 1, 0, { }).getSerializedData();
238         // Packets are feed asynchronously to mimic actual data transmission.
239         RunLoop::main().dispatch([report = WTFMove(report), weakThis = makeWeakPtr(*this)]() mutable {
240             if (!weakThis)
241                 return;
242             weakThis->receiveReport(WTFMove(report));
243         });
244         isFirst = false;
245     }
246 }
247
248 bool MockHidConnection::stagesMatch() const
249 {
250     return m_configuration.hid->stage == m_stage && m_configuration.hid->subStage == m_subStage;
251 }
252
253 void MockHidConnection::shouldContinueFeedReports()
254 {
255     if (!m_configuration.hid->continueAfterErrorData)
256         return;
257     m_configuration.hid->continueAfterErrorData = false;
258     m_configuration.hid->error = Mock::Error::Success;
259     continueFeedReports();
260 }
261
262 void MockHidConnection::continueFeedReports()
263 {
264     // Send actual response for the next run.
265     RunLoop::main().dispatch([weakThis = makeWeakPtr(*this)]() mutable {
266         if (!weakThis)
267             return;
268         weakThis->feedReports();
269     });
270 }
271
272 } // namespace WebKit
273
274 #endif // ENABLE(WEB_AUTHN) && PLATFORM(MAC)