[WebAuthN] Change the nonce in the CTAP kInit command to weak random values
[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 || m_requestMessage->cmd() == FidoHidDeviceCommand::kMsg)
131         m_subStage = Mock::SubStage::Msg;
132
133     if (m_stage == Mock::Stage::Request && m_subStage == Mock::SubStage::Msg) {
134         // Make sure we issue different msg cmd for CTAP and U2F.
135         ASSERT(m_configuration.hid->isU2f ^ (m_requestMessage->cmd() != FidoHidDeviceCommand::kMsg));
136
137         // Set options.
138         if (m_requestMessage->cmd() == FidoHidDeviceCommand::kCbor) {
139             m_requireResidentKey = false;
140             m_requireUserVerification = false;
141
142             auto payload = m_requestMessage->getMessagePayload();
143             ASSERT(payload.size());
144             auto cmd = static_cast<CtapRequestCommand>(payload[0]);
145             payload.remove(0);
146             auto requestMap = CBORReader::read(payload);
147             ASSERT(requestMap);
148
149             if (cmd == CtapRequestCommand::kAuthenticatorMakeCredential) {
150                 auto it = requestMap->getMap().find(CBORValue(CtapMakeCredentialRequestOptionsKey)); // Find options.
151                 if (it != requestMap->getMap().end()) {
152                     auto& optionMap = it->second.getMap();
153
154                     auto itr = optionMap.find(CBORValue(kResidentKeyMapKey));
155                     if (itr != optionMap.end())
156                         m_requireResidentKey = itr->second.getBool();
157
158                     itr = optionMap.find(CBORValue(kUserVerificationMapKey));
159                     if (itr != optionMap.end())
160                         m_requireUserVerification = itr->second.getBool();
161                 }
162             }
163
164             if (cmd == CtapRequestCommand::kAuthenticatorGetAssertion) {
165                 auto it = requestMap->getMap().find(CBORValue(CtapGetAssertionRequestOptionsKey)); // Find options.
166                 if (it != requestMap->getMap().end()) {
167                     auto& optionMap = it->second.getMap();
168                     auto itr = optionMap.find(CBORValue(kUserVerificationMapKey));
169                     if (itr != optionMap.end())
170                         m_requireUserVerification = itr->second.getBool();
171                 }
172             }
173         }
174     }
175
176     // Store nonce.
177     if (m_subStage == Mock::SubStage::Init) {
178         m_nonce = m_requestMessage->getMessagePayload();
179         ASSERT(m_nonce.size() == kHidInitNonceLength);
180     }
181
182     m_currentChannel = m_requestMessage->channelId();
183     m_requestMessage = WTF::nullopt;
184     if (m_configuration.hid->fastDataArrival)
185         feedReports();
186 }
187
188 void MockHidConnection::feedReports()
189 {
190     using namespace MockHidConnectionInternal;
191
192     if (m_subStage == Mock::SubStage::Init) {
193         Vector<uint8_t> payload;
194         payload.reserveInitialCapacity(kHidInitResponseSize);
195         payload.appendVector(m_nonce);
196         if (stagesMatch() && m_configuration.hid->error == Mock::Error::WrongNonce)
197             payload[0]--;
198         payload.grow(kHidInitResponseSize);
199         cryptographicallyRandomValues(payload.data() + payload.size(), CtapChannelIdSize);
200         auto channel = kHidBroadcastChannel;
201         if (stagesMatch() && m_configuration.hid->error == Mock::Error::WrongChannelId)
202             channel--;
203         FidoHidInitPacket initPacket(channel, FidoHidDeviceCommand::kInit, WTFMove(payload), payload.size());
204         receiveReport(initPacket.getSerializedData());
205         shouldContinueFeedReports();
206         return;
207     }
208
209     Optional<FidoHidMessage> message;
210     if (m_stage == Mock::Stage::Info && m_subStage == Mock::SubStage::Msg) {
211         auto infoData = encodeAsCBOR(AuthenticatorGetInfoResponse({ ProtocolVersion::kCtap }, Vector<uint8_t>(aaguidLength, 0u)));
212         infoData.insert(0, static_cast<uint8_t>(CtapDeviceResponseCode::kSuccess)); // Prepend status code.
213         if (stagesMatch() && m_configuration.hid->error == Mock::Error::WrongChannelId)
214             message = FidoHidMessage::create(m_currentChannel - 1, FidoHidDeviceCommand::kCbor, infoData);
215         else {
216             if (!m_configuration.hid->isU2f)
217                 message = FidoHidMessage::create(m_currentChannel, FidoHidDeviceCommand::kCbor, infoData);
218             else
219                 message = FidoHidMessage::create(m_currentChannel, FidoHidDeviceCommand::kError, { static_cast<uint8_t>(CtapDeviceResponseCode::kCtap1ErrInvalidCommand) });
220         }
221     }
222
223     if (m_stage == Mock::Stage::Request && m_subStage == Mock::SubStage::Msg) {
224         if (m_configuration.hid->keepAlive) {
225             m_configuration.hid->keepAlive = false;
226             FidoHidInitPacket initPacket(m_currentChannel, FidoHidDeviceCommand::kKeepAlive, { CtapKeepAliveStatusProcessing }, 1);
227             receiveReport(initPacket.getSerializedData());
228             continueFeedReports();
229             return;
230         }
231         if (stagesMatch() && m_configuration.hid->error == Mock::Error::UnsupportedOptions && (m_requireResidentKey || m_requireUserVerification))
232             message = FidoHidMessage::create(m_currentChannel, FidoHidDeviceCommand::kCbor, { static_cast<uint8_t>(CtapDeviceResponseCode::kCtap2ErrUnsupportedOption) });
233         else {
234             Vector<uint8_t> payload;
235             ASSERT(!m_configuration.hid->payloadBase64.isEmpty());
236             auto status = base64Decode(m_configuration.hid->payloadBase64[0], payload);
237             m_configuration.hid->payloadBase64.remove(0);
238             ASSERT_UNUSED(status, status);
239             if (!m_configuration.hid->isU2f)
240                 message = FidoHidMessage::create(m_currentChannel, FidoHidDeviceCommand::kCbor, payload);
241             else
242                 message = FidoHidMessage::create(m_currentChannel, FidoHidDeviceCommand::kMsg, payload);
243         }
244     }
245
246     ASSERT(message);
247     bool isFirst = true;
248     while (message->numPackets()) {
249         auto report = message->popNextPacket();
250         if (!isFirst && stagesMatch() && m_configuration.hid->error == Mock::Error::WrongChannelId)
251             report = FidoHidContinuationPacket(m_currentChannel - 1, 0, { }).getSerializedData();
252         // Packets are feed asynchronously to mimic actual data transmission.
253         RunLoop::main().dispatch([report = WTFMove(report), weakThis = makeWeakPtr(*this)]() mutable {
254             if (!weakThis)
255                 return;
256             weakThis->receiveReport(WTFMove(report));
257         });
258         isFirst = false;
259     }
260 }
261
262 bool MockHidConnection::stagesMatch() const
263 {
264     return m_configuration.hid->stage == m_stage && m_configuration.hid->subStage == m_subStage;
265 }
266
267 void MockHidConnection::shouldContinueFeedReports()
268 {
269     if (!m_configuration.hid->continueAfterErrorData)
270         return;
271     m_configuration.hid->continueAfterErrorData = false;
272     m_configuration.hid->error = Mock::Error::Success;
273     continueFeedReports();
274 }
275
276 void MockHidConnection::continueFeedReports()
277 {
278     // Send actual response for the next run.
279     RunLoop::main().dispatch([weakThis = makeWeakPtr(*this)]() mutable {
280         if (!weakThis)
281             return;
282         weakThis->feedReports();
283     });
284 }
285
286 } // namespace WebKit
287
288 #endif // ENABLE(WEB_AUTHN) && PLATFORM(MAC)