1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <aidl/android/hardware/secure_element/BnSecureElement.h>
18 #include <android-base/hex.h>
19 #include <android-base/logging.h>
20 #include <android/binder_manager.h>
21 #include <android/binder_process.h>
22 
23 #include <algorithm>
24 
25 using aidl::android::hardware::secure_element::BnSecureElement;
26 using aidl::android::hardware::secure_element::ISecureElementCallback;
27 using aidl::android::hardware::secure_element::LogicalChannelResponse;
28 using android::base::HexString;
29 using ndk::ScopedAStatus;
30 
31 static const std::vector<uint8_t> kIssuerSecurityDomainSelectResponse = {0x00, 0x00, 0x90, 0x00};
32 
33 namespace se {
34 // Application identifier.
35 using Aid = std::vector<uint8_t>;
36 
37 // ISO7816 APDU status codes.
38 enum Status : uint16_t {
39     SW_WRONG_DATA = 0x6A80,
40     SW_LOGICAL_CHANNEL_NOT_SUPPORTED = 0x6881,
41     SW_CONDITIONS_NOT_SATISFIED = 0x6985,
42     SW_INCORRECT_P1P2 = 0x6A86,
43     SW_BYTES_REMAINING_00 = 0x6100,
44     SW_WRONG_LENGTH = 0x6700,
45     SW_CORRECT_LENGTH_00 = 0x6C00,
46     SW_INS_NOT_SUPPORTED = 0x6D00,
47     SW_NO_ERROR = 0x9000,
48 };
49 
50 // Type for raw APDUs.
51 using RawApdu = std::vector<uint8_t>;
52 
53 // Wrap a command APDU (Application Processing Data Unit) to provide
54 // accessors for header fields.
55 struct Apdu {
56   public:
57     // Construct a command Apdu.
Apduse::Apdu58     Apdu(std::vector<uint8_t> packet) : bytes_(std::move(packet)) {
59         CHECK(bytes_.size() >= kHeaderSize) << "command APDU created with invalid length";
60         size_t payload_len = bytes_.size() - kHeaderSize;
61 
62         // TODO(b/123254068) - add support for extended command APDUs.
63         // Pre compute Lc and Le.
64 
65         // Case 1: CLA | INS | P1 | P2
66         if (payload_len == 0) {
67             lc_ = 0;
68             le_ = 0;
69             return;
70         }
71 
72         // Case 2: CLA | INS | P1 | P2 | Le
73         // Le has a value of 1 to 255.
74         if (payload_len == 1) {
75             le_ = bytes_[kHeaderSize];
76             le_ = le_ == 0 ? 256 : le_;
77             lc_ = 0;
78             return;
79         }
80 
81         // Case 3: CLA | INS | P1 | P2 | Lc | Data
82         // Lc is less than 256 bytes
83         // of data, and Le is zero.
84         lc_ = bytes_[kHeaderSize];
85         if (payload_len <= (1 + lc_)) {
86             le_ = 0;
87         }
88 
89         // Case 4: CLA | INS | P1 | P2 | Lc | Data | Le
90         // The legacy Case 4. Lc and Le
91         // are less than 256 bytes of data.
92         else {
93             le_ = bytes_[bytes_.size() - 1];
94             le_ = le_ == 0 ? 256 : le_;
95         }
96     }
97 
98     // Construct a response Apdu with data.
CreateResponsese::Apdu99     static RawApdu CreateResponse(std::vector<uint8_t> data, Status status) {
100         // Append status word.
101         data.push_back(status >> 8);
102         data.push_back(status);
103         return data;
104     }
105 
106     // Construct a response Apdu with no data.
CreateResponsese::Apdu107     static RawApdu CreateResponse(Status status) {
108         // Append status word.
109         return std::vector<uint8_t>{static_cast<uint8_t>(status >> 8),
110                                     static_cast<uint8_t>(status)};
111     }
112 
113     // Return if command APDU is extended.
114     // The ISO/IEC 7816-4:2013 specification defines an extended APDU as any APDU
115     // whose payload data, response data or expected data length exceeds the 256
116     // byte limit.
IsExtendedse::Apdu117     bool IsExtended() const { return (bytes_.size() - kHeaderSize) > 256; }
118 
119     // Return if command APDU has payload bytes.
HasPayloadse::Apdu120     bool HasPayload() const { return bytes_.size() > kHeaderSize; }
121 
get_clase::Apdu122     uint8_t get_cla() const { return bytes_[0]; }
get_insse::Apdu123     uint8_t get_ins() const { return bytes_[1]; }
get_p1se::Apdu124     uint8_t get_p1() const { return bytes_[2]; }
get_p2se::Apdu125     uint8_t get_p2() const { return bytes_[3]; }
126 
127     // Return the channel number encoded in the CLA field.
get_channel_numberse::Apdu128     uint8_t get_channel_number() const {
129         // Type 4 commands — Encode legacy ISO/IEC 7816-4 logical channel
130         // information. Type 16 commands — Defined by the ISO/IEC 7816-4:2013
131         // specification to
132         //   encode information for additional 16 logical channels in the card.
133         uint8_t cla = get_cla();
134         return (cla & 0x40) == 0 ? cla & 0x3 : 4 + (cla & 0xf);
135     }
136 
137     // Return the length of the command data field.
get_lcse::Apdu138     uint16_t get_lc() const { return lc_; }
139 
140     // Return the expected length of the response data field.
141     // Le should be have the same format as Lc.
get_lese::Apdu142     uint16_t get_le() const { return le_; }
143 
144     // Get the pointer to the APDU raw data.
get_datase::Apdu145     std::vector<uint8_t> const& get_data() const { return bytes_; }
146 
147   private:
148     // Size of command header, including CLA, INS, P1, P2 fields.
149     const size_t kHeaderSize = 4;
150 
151     // Command or response buffer.
152     std::vector<uint8_t> bytes_{};
153 
154     // Lengths of command data field and expected response data field.
155     uint16_t lc_{0};
156     uint16_t le_{0};
157 };
158 
159 // Type of SE applets.
160 class Applet {
161   public:
~Applet()162     virtual ~Applet() {}
163 
164     // Called to inform this applet that it has been selected.
165     virtual RawApdu Select(Aid const& aid, uint8_t p2) = 0;
166 
167     // Called by the Java Card runtime environment to process an
168     // incoming APDU command. SELECT commands are processed by \ref select
169     // instead.
170     virtual RawApdu Process(Apdu const& apdu) = 0;
171 };
172 };  // namespace se
173 
174 // Implement the Google-eSE-test.cap test applet for passing OMAPI CTS tests
175 // on Cuttlefish. The reference can be found here:
176 // cts/tests/tests/secure_element/sample_applet/src/com/android/cts/omapi/test/CtsAndroidOmapiTestApplet.java
177 class CtsAndroidOmapiTestApplet : public se::Applet {
178   public:
CtsAndroidOmapiTestApplet()179     CtsAndroidOmapiTestApplet() {}
~CtsAndroidOmapiTestApplet()180     virtual ~CtsAndroidOmapiTestApplet() {}
181 
Select(se::Aid const & aid,uint8_t)182     se::RawApdu Select(se::Aid const& aid, uint8_t /*p2*/) override {
183         if (aid[aid.size() - 1] == 0x31) {
184             // AID: A000000476416E64726F696443545331
185             return se::Apdu::CreateResponse(se::Status::SW_NO_ERROR);
186         } else {
187             // AID: A000000476416E64726F696443545332
188             return se::Apdu::CreateResponse(GenerateBerTLVBytes(SELECT_RESPONSE_DATA_LENGTH),
189                                             se::Status::SW_NO_ERROR);
190         }
191     }
192 
ReadNextResponseChunk(uint16_t max_output_len)193     se::RawApdu ReadNextResponseChunk(uint16_t max_output_len) {
194         uint16_t output_len = static_cast<uint16_t>(response_.size() - response_offset_);
195         output_len = std::min<uint16_t>(max_output_len, output_len);
196         std::vector<uint8_t> output{
197                 &response_[response_offset_],
198                 &response_[response_offset_ + output_len],
199         };
200         response_offset_ += output_len;
201         uint16_t remaining_len = response_.size() - response_offset_;
202         se::Status status = se::Status::SW_NO_ERROR;
203         if (remaining_len > 0) {
204             if (remaining_len > 256) {
205                 remaining_len = 0x00;
206             }
207             status = se::Status(se::Status::SW_BYTES_REMAINING_00 | remaining_len);
208         } else {
209             response_.clear();
210             response_offset_ = 0;
211         }
212         return se::Apdu::CreateResponse(output, status);
213     }
214 
Process(se::Apdu const & apdu)215     se::RawApdu Process(se::Apdu const& apdu) override {
216         uint16_t lc;
217         uint16_t le = apdu.get_le();
218         uint8_t p1 = apdu.get_p1();
219         uint8_t p2 = apdu.get_p2();
220 
221         switch (apdu.get_ins()) {
222             case NO_DATA_INS_1:
223             case NO_DATA_INS_2:
224                 LOG(INFO) << __func__ << ": NO_DATA_INS_1|2";
225                 return se::Apdu::CreateResponse(se::Status::SW_NO_ERROR);
226 
227             case DATA_INS_1:
228             case DATA_INS_2:
229                 // Return 256 bytes of data.
230                 LOG(INFO) << __func__ << ": DATA_INS_1|2";
231                 return se::Apdu::CreateResponse(GeneratesBytes(256), se::Status::SW_NO_ERROR);
232 
233             case GET_RESPONSE_INS:
234                 // ISO GET_RESPONSE command.
235                 LOG(INFO) << __func__ << ": GET_RESPONSE_INS";
236                 if (response_.empty()) {
237                     return se::Apdu::CreateResponse(se::Status::SW_CONDITIONS_NOT_SATISFIED);
238                 }
239                 return ReadNextResponseChunk(apdu.get_le());
240 
241             case SW_62xx_APDU_INS:
242                 LOG(INFO) << __func__ << ": SW_62xx_APDU_INS";
243                 if (p1 < 1 || p1 > 16) {
244                     return se::Apdu::CreateResponse(se::Status::SW_INCORRECT_P1P2);
245                 }
246                 if (p2 == SW_62xx_DATA_APDU_P2) {
247                     return se::Apdu::CreateResponse(GeneratesBytes(3),
248                                                     se::Status(SW_62xx_resp[p1 - 1]));
249                 }
250                 if (p2 == SW_62xx_VALIDATE_DATA_P2) {
251                     std::vector<uint8_t> output{SW_62xx_VALIDATE_DATA_RESP.begin(),
252                                                 SW_62xx_VALIDATE_DATA_RESP.end()};
253                     output[2] = p1;
254                     return se::Apdu::CreateResponse(std::move(output),
255                                                     se::Status(SW_62xx_resp[p1 - 1]));
256                 }
257                 return se::Apdu::CreateResponse(se::Status(SW_62xx_resp[p1 - 1]));
258 
259             case SEGMENTED_RESP_INS_1:
260             case SEGMENTED_RESP_INS_2:
261                 LOG(INFO) << __func__ << ": SEGMENTED_RESP_INS_1|2";
262                 response_ = GeneratesBytes((static_cast<uint16_t>(p1) << 8) | p2);
263                 response_offset_ = 0;
264                 return ReadNextResponseChunk(std::min<uint16_t>(apdu.get_le(), 256));
265 
266             case SEGMENTED_RESP_INS_3:
267             case SEGMENTED_RESP_INS_4:
268                 LOG(INFO) << __func__ << ": SEGMENTED_RESP_INS_3|4";
269                 response_ = GeneratesBytes((static_cast<uint16_t>(p1) << 8) | p2);
270                 response_offset_ = 0;
271                 return ReadNextResponseChunk(apdu.get_le());
272 
273             case SEGMENTED_RESP_INS_5:
274                 LOG(INFO) << __func__ << ": SEGMENTED_RESP_INS_5";
275                 if (le == 0xff) {
276                     return se::Apdu::CreateResponse(
277                             se::Status(se::Status::SW_CORRECT_LENGTH_00 | 0xff));
278                 }
279                 response_ = GeneratesBytes((static_cast<uint16_t>(p1) << 8) | p2);
280                 response_offset_ = 0;
281                 return ReadNextResponseChunk(apdu.get_le());
282 
283             case CHECK_SELECT_P2_APDU:
284                 LOG(INFO) << __func__ << ": CHECK_SELECT_P2_APDU";
285                 return se::Apdu::CreateResponse(std::vector<uint8_t>{apdu.get_p2()},
286                                                 se::Status::SW_NO_ERROR);
287 
288             default:
289                 // Case is not known.
290                 LOG(INFO) << __func__ << ": UNKNOWN_INS";
291                 return se::Apdu::CreateResponse(se::Status::SW_INS_NOT_SUPPORTED);
292         }
293     }
294 
295   private:
296     std::vector<uint8_t> response_{};
297     uint16_t response_offset_{0};
298 
299     static const uint8_t NO_DATA_INS_1 = 0x06;
300     static const uint8_t NO_DATA_INS_2 = 0x0A;
301     static const uint8_t DATA_INS_1 = 0x08;
302     static const uint8_t DATA_INS_2 = 0x0C;
303     static const uint8_t SW_62xx_APDU_INS = 0xF3;
304     static const uint8_t SW_62xx_DATA_APDU_P2 = 0x08;
305     static const uint8_t SW_62xx_VALIDATE_DATA_P2 = 0x0C;
306 
307     static constexpr std::array<uint8_t, 7> SW_62xx_VALIDATE_DATA_RESP = {0x01, 0xF3, 0x00, 0x0C,
308                                                                           0x01, 0xAA, 0x00};
309     static constexpr uint16_t SW_62xx_resp[] = {
310             0x6200, 0x6281, 0x6282, 0x6283, 0x6285, 0x62F1, 0x62F2, 0x63F1,
311             0x63F2, 0x63C2, 0x6202, 0x6280, 0x6284, 0x6286, 0x6300, 0x6381,
312     };
313 
314     static const uint8_t SEGMENTED_RESP_INS_1 = 0xC2;
315     static const uint8_t SEGMENTED_RESP_INS_2 = 0xC4;
316     static const uint8_t SEGMENTED_RESP_INS_3 = 0xC6;
317     static const uint8_t SEGMENTED_RESP_INS_4 = 0xC8;
318     static const uint8_t SEGMENTED_RESP_INS_5 = 0xCF;
319     static const uint8_t CHECK_SELECT_P2_APDU = 0xF4;
320     static const uint8_t GET_RESPONSE_INS = 0xC0;
321     static const uint8_t BER_TLV_TYPE = 0x1F;
322     static const uint16_t SELECT_RESPONSE_DATA_LENGTH = 252;
323 
324     static const uint16_t LENGTH_256 = 0x0100;
325     static constexpr std::array<uint8_t, 256> resp_bytes256{
326             0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D,
327             0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B,
328             0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29,
329             0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
330             0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45,
331             0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53,
332             0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61,
333             0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
334             0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D,
335             0x7E, 0x7F, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B,
336             0x8C, 0x8D, 0x8E, 0x8F, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99,
337             0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,
338             0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5,
339             0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF, 0xC0, 0xC1, 0xC2, 0xC3,
340             0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1,
341             0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF,
342             0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED,
343             0xEE, 0xEF, 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB,
344             0xFC, 0xFD, 0xFE, 0xFF};
345 
346     // Generate a response buffer of the selected length containing valid
347     // BER TLV bytes.
GenerateBerTLVBytes(uint16_t le)348     static std::vector<uint8_t> GenerateBerTLVBytes(uint16_t le) {
349         // Support length from 0x00 - 0x7FFF.
350         uint16_t le_len = 1;
351         if (le < (uint16_t)0x80) {
352             le_len = 1;
353         } else if (le < (uint16_t)0x100) {
354             le_len = 2;
355         } else {
356             le_len = 3;
357         }
358 
359         uint16_t total_len = (uint16_t)(le + 2 + le_len);
360         std::vector<uint8_t> output(total_len);
361         uint16_t i = 0;
362 
363         output[i++] = BER_TLV_TYPE;
364         output[i++] = 0x00;  // second byte of Type
365         if (le < 0x80) {
366             output[i++] = le;
367         } else if (le < 0x100) {
368             output[i++] = 0x81;
369             output[i++] = le;
370         } else {
371             output[i++] = 0x82;
372             output[i++] = (le >> 8);
373             output[i++] = (le & 0xFF);
374         }
375         while (i < total_len) {
376             output[i++] = ((i - 2 - le_len) & 0xFF);
377         }
378 
379         // Set the last byte to 0xFF for CTS validation.
380         output[total_len - 1] = 0xFF;
381         return output;
382     }
383 
384     // Generate a response buffer of the selected length using the
385     // array resp_bytes256 as input.
GeneratesBytes(uint16_t total_len)386     static std::vector<uint8_t> GeneratesBytes(uint16_t total_len) {
387         std::vector<uint8_t> output(total_len);
388         uint16_t i = 0;
389 
390         while (i < total_len) {
391             if ((total_len - i) >= resp_bytes256.size()) {
392                 std::memcpy(&output[i], resp_bytes256.data(), resp_bytes256.size());
393                 i += resp_bytes256.size();
394             } else {
395                 output[i] = i & 0xFF;
396                 i += 1;
397             }
398         }
399 
400         // Set the last byte to 0xFF for CTS validation.
401         output[total_len - 1] = 0xFF;
402         return output;
403     }
404 };
405 
406 class EmulatedSecureElement : public BnSecureElement {
407   public:
EmulatedSecureElement()408     EmulatedSecureElement() {
409         std::shared_ptr<CtsAndroidOmapiTestApplet> test_applet =
410                 std::make_shared<CtsAndroidOmapiTestApplet>();
411 
412         applets_.push_back(std::pair{se::Aid{0xA0, 0x00, 0x00, 0x04, 0x76, 0x41, 0x6E, 0x64, 0x72,
413                                              0x6F, 0x69, 0x64, 0x43, 0x54, 0x53, 0x31},
414                                      test_applet});
415 
416         applets_.push_back(std::pair{se::Aid{0xA0, 0x00, 0x00, 0x04, 0x76, 0x41, 0x6E, 0x64, 0x72,
417                                              0x6F, 0x69, 0x64, 0x43, 0x54, 0x53, 0x32},
418                                      test_applet});
419     }
420 
init(const std::shared_ptr<ISecureElementCallback> & client_callback)421     ScopedAStatus init(const std::shared_ptr<ISecureElementCallback>& client_callback) override {
422         LOG(INFO) << __func__ << " callback: " << client_callback.get();
423         if (client_callback == nullptr) {
424             return ScopedAStatus::fromExceptionCode(EX_NULL_POINTER);
425         }
426         for (auto& channel : channels_) {
427             channel = Channel();
428         }
429         client_callback_ = client_callback;
430         client_callback_->onStateChange(true, "init");
431         return ScopedAStatus::ok();
432     }
433 
getAtr(std::vector<uint8_t> * aidl_return)434     ScopedAStatus getAtr(std::vector<uint8_t>* aidl_return) override {
435         LOG(INFO) << __func__;
436         if (client_callback_ == nullptr) {
437             return ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
438         }
439         *aidl_return = atr_;
440         return ScopedAStatus::ok();
441     }
442 
reset()443     ScopedAStatus reset() override {
444         LOG(INFO) << __func__;
445         if (client_callback_ == nullptr) {
446             return ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
447         }
448         client_callback_->onStateChange(false, "reset");
449         client_callback_->onStateChange(true, "reset");
450         // All channels are closed after reset.
451         for (auto& channel : channels_) {
452             channel = Channel();
453         }
454         return ScopedAStatus::ok();
455     }
456 
isCardPresent(bool * aidl_return)457     ScopedAStatus isCardPresent(bool* aidl_return) override {
458         LOG(INFO) << __func__;
459         if (client_callback_ == nullptr) {
460             return ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
461         }
462         *aidl_return = true;
463         return ScopedAStatus::ok();
464     }
465 
openBasicChannel(const std::vector<uint8_t> & aid,int8_t p2,std::vector<uint8_t> * aidl_return)466     ScopedAStatus openBasicChannel(const std::vector<uint8_t>& aid, int8_t p2,
467                                    std::vector<uint8_t>* aidl_return) override {
468         LOG(INFO) << __func__ << " aid: " << HexString(aid.data(), aid.size()) << " (" << aid.size()
469                   << ") p2 " << p2;
470         if (client_callback_ == nullptr) {
471             return ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
472         }
473 
474         std::vector<uint8_t> select_response;
475         std::shared_ptr<se::Applet> applet = nullptr;
476 
477         // The basic channel can only be opened once, and stays opened
478         // and locked until the channel is closed.
479         if (channels_[0].opened) {
480             LOG(INFO) << __func__ << " basic channel already opened";
481             return ScopedAStatus::fromServiceSpecificError(CHANNEL_NOT_AVAILABLE);
482         }
483 
484         // If the AID is defined (the AID is not Null and the length of the
485         // AID is not 0) and the channel is not locked then the corresponding
486         // applet shall be selected.
487         if (aid.size() > 0) {
488             applet = SelectApplet(aid);
489             if (applet == nullptr) {
490                 // No applet registered with matching AID.
491                 LOG(INFO) << __func__ << " basic channel AID not found";
492                 return ScopedAStatus::fromServiceSpecificError(NO_SUCH_ELEMENT_ERROR);
493             }
494             select_response = applet->Select(aid, p2);
495         }
496 
497         // If the AID is a 0 length AID and the channel is not locked, the
498         // method will select the Issuer Security Domain of the SE by sending a
499         // SELECT command with a 0 length AID as defined in
500         // [GP Card specification].
501         if (aid.size() == 0) {
502             select_response = kIssuerSecurityDomainSelectResponse;
503         }
504 
505         LOG(INFO) << __func__ << " sending response: "
506                   << HexString(select_response.data(), select_response.size());
507 
508         // TODO(b/123254068) - this is not an implementation of the OMAPI protocol
509         // or APDU. The functionality here is enough to exercise the framework,
510         // but actual calls to the secure element will fail. This implementation
511         // does not model channel isolation or any other aspects important to
512         // implementing secure element.
513         channels_[0] = Channel(aid, p2, applet);
514         *aidl_return = select_response;
515         return ScopedAStatus::ok();
516     }
517 
openLogicalChannel(const std::vector<uint8_t> & aid,int8_t p2,::aidl::android::hardware::secure_element::LogicalChannelResponse * aidl_return)518     ScopedAStatus openLogicalChannel(
519             const std::vector<uint8_t>& aid, int8_t p2,
520             ::aidl::android::hardware::secure_element::LogicalChannelResponse* aidl_return)
521             override {
522         LOG(INFO) << __func__ << " aid: " << HexString(aid.data(), aid.size()) << " (" << aid.size()
523                   << ") p2 " << p2;
524 
525         if (client_callback_ == nullptr) {
526             return ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
527         }
528 
529         size_t channel_number = 1;
530         std::vector<uint8_t> select_response;
531         std::shared_ptr<se::Applet> applet = nullptr;
532 
533         // Look for an available channel number.
534         for (; channel_number < channels_.size(); channel_number++) {
535             if (channels_[channel_number].opened == false) {
536                 break;
537             }
538         }
539 
540         // All channels are currently allocated.
541         if (channel_number >= channels_.size()) {
542             LOG(INFO) << __func__ << " all logical channels already opened";
543             return ScopedAStatus::fromServiceSpecificError(CHANNEL_NOT_AVAILABLE);
544         }
545 
546         // If the AID is defined (the AID is not Null and the length of the
547         // AID is not 0) then the corresponding applet shall be selected.
548         if (aid.size() > 0) {
549             applet = SelectApplet(aid);
550             if (applet == nullptr) {
551                 // No applet registered with matching AID.
552                 LOG(INFO) << __func__ << " logical channel AID not found";
553                 return ScopedAStatus::fromServiceSpecificError(NO_SUCH_ELEMENT_ERROR);
554             }
555             select_response = applet->Select(aid, p2);
556         }
557 
558         // If the length of the AID is 0, the method will select the
559         // Issuer Security Domain of the SE by sending a SELECT command
560         // with 0 length AID as defined in [GPCS].
561         if (aid.size() == 0) {
562             select_response = kIssuerSecurityDomainSelectResponse;
563         }
564 
565         LOG(INFO) << __func__ << " sending response: "
566                   << HexString(select_response.data(), select_response.size());
567 
568         // TODO(b/123254068) - this is not an implementation of the OMAPI protocol
569         // or APDU. The functionality here is enough to exercise the framework,
570         // but actual calls to the secure element will fail. This implementation
571         // does not model channel isolation or any other aspects important to
572         // implementing secure element.
573         channels_[channel_number] = Channel(aid, p2, applet);
574         *aidl_return = LogicalChannelResponse{
575                 .channelNumber = static_cast<int8_t>(channel_number),
576                 .selectResponse = select_response,
577         };
578         return ScopedAStatus::ok();
579     }
580 
closeChannel(int8_t channel_number)581     ScopedAStatus closeChannel(int8_t channel_number) override {
582         LOG(INFO) << __func__ << " channel number: " << static_cast<int>(channel_number);
583         if (client_callback_ == nullptr) {
584             return ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
585         }
586 
587         // The selected basic or logical channel is not opened.
588         if (channel_number >= channels_.size() || !channels_[channel_number].opened) {
589             return ScopedAStatus::fromServiceSpecificError(FAILED);
590         }
591 
592         // TODO(b/123254068) - this is not an implementation of the OMAPI protocol
593         // or APDU. The functionality here is enough to exercise the framework,
594         // but actual calls to the secure element will fail. This implementation
595         // does not model channel isolation or any other aspects important to
596         // implementing secure element.
597         channels_[channel_number].opened = false;
598         return ScopedAStatus::ok();
599     }
600 
transmit(const std::vector<uint8_t> & data,std::vector<uint8_t> * aidl_return)601     ScopedAStatus transmit(const std::vector<uint8_t>& data,
602                            std::vector<uint8_t>* aidl_return) override {
603         LOG(INFO) << __func__ << " data: " << HexString(data.data(), data.size()) << " ("
604                   << data.size() << ")";
605         if (client_callback_ == nullptr) {
606             return ScopedAStatus::fromExceptionCode(EX_ILLEGAL_STATE);
607         }
608 
609         se::Apdu apdu(data);
610         uint8_t channel_number = apdu.get_channel_number();
611         std::vector<uint8_t> response_apdu;
612 
613         switch (apdu.get_ins()) {
614             // TODO(b/123254068) - Implement support channel management APDUs.
615             case MANAGE_CHANNEL_INS:
616                 // P1 = '00' to open
617                 // P1 = '80' to close
618                 LOG(INFO) << __func__ << " MANAGE_CHANNEL apdu";
619                 response_apdu =
620                         se::Apdu::CreateResponse(se::Status::SW_LOGICAL_CHANNEL_NOT_SUPPORTED);
621                 break;
622 
623             // TODO(b/123254068) - Implement support channel management APDUs.
624             case SELECT_INS:
625                 LOG(INFO) << __func__ << " SELECT apdu";
626                 response_apdu =
627                         se::Apdu::CreateResponse(se::Status::SW_LOGICAL_CHANNEL_NOT_SUPPORTED);
628                 break;
629 
630             default:
631                 CHECK(channel_number < channels_.size()) << " invalid channel number";
632                 if (!channels_[channel_number].opened) {
633                     LOG(INFO) << __func__ << " the channel " << static_cast<int>(channel_number)
634                               << " is not opened";
635                     response_apdu =
636                             se::Apdu::CreateResponse(se::Status::SW_LOGICAL_CHANNEL_NOT_SUPPORTED);
637                     break;
638                 }
639                 // Send the APDU to the applet for processing.
640                 // Applet implementation is optional, default to sending
641                 // SW_INS_NOT_SUPPORTED.
642                 if (channels_[channel_number].applet == nullptr) {
643                     response_apdu = se::Apdu::CreateResponse(se::Status::SW_INS_NOT_SUPPORTED);
644                 } else {
645                     response_apdu = channels_[channel_number].applet->Process(apdu);
646                 }
647                 break;
648         }
649 
650         aidl_return->assign(response_apdu.begin(), response_apdu.end());
651         LOG(INFO) << __func__
652                   << " response: " << HexString(aidl_return->data(), aidl_return->size()) << " ("
653                   << aidl_return->size() << ")";
654         return ScopedAStatus::ok();
655     }
656 
657   private:
658     struct Channel {
659       public:
660         Channel() = default;
661         Channel(Channel const&) = default;
ChannelEmulatedSecureElement::Channel662         Channel(se::Aid const& aid, uint8_t p2, std::shared_ptr<se::Applet> applet)
663             : opened(true), aid(aid), p2(p2), applet(std::move(applet)) {}
664         Channel& operator=(Channel const&) = default;
665 
666         bool opened{false};
667         se::Aid aid{};
668         uint8_t p2{0};
669         std::shared_ptr<se::Applet> applet{nullptr};
670     };
671 
672     // OMAPI abstraction.
673 
674     // Channel 0 is the basic channel, channels 1-19 are the logical channels.
675     std::array<Channel, 20> channels_{};
676     std::shared_ptr<ISecureElementCallback> client_callback_{nullptr};
677 
678     // Secure element abstraction.
679 
680     static const uint8_t MANAGE_CHANNEL_INS = 0x70;
681     static const uint8_t SELECT_INS = 0xa4;
682 
683     // Secure element ATR (Answer-To-Reset).
684     // The format is specified by ISO/IEC 1816-4 2020 and lists
685     // the capabilities of the card.
686     //
687     // TODO(b/123254068): encode the default SE properties in the ATR:
688     // support for extended Lc / Le fields, maximum number of logical channels.
689     // The CTS tests are *not* checking this value.
690     std::vector<uint8_t> const atr_{};
691 
692     // Applet registration.
693     std::vector<std::pair<se::Aid, std::shared_ptr<se::Applet>>> applets_{};
694 
695     // Return the first applet that matches the selected aid.
SelectApplet(se::Aid const & aid)696     std::shared_ptr<se::Applet> SelectApplet(se::Aid const& aid) {
697         for (auto& [applet_aid, applet] : applets_) {
698             if (applet_aid == aid) {
699                 return applet;
700             }
701         }
702         return nullptr;
703     }
704 };
705 
main()706 int main() {
707     ABinderProcess_setThreadPoolMaxThreadCount(0);
708 
709     auto se = ndk::SharedRefBase::make<EmulatedSecureElement>();
710     const std::string name = std::string() + BnSecureElement::descriptor + "/eSE1";
711     binder_status_t status = AServiceManager_addService(se->asBinder().get(), name.c_str());
712     CHECK_EQ(status, STATUS_OK);
713 
714     ABinderProcess_joinThreadPool();
715     return EXIT_FAILURE;  // should not reach
716 }
717