1 /*
2  * Copyright (C) 2016 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 <arpa/inet.h>
18 #include <sys/socket.h>
19 #include <sys/types.h>
20 #include <sys/un.h>
21 #include <unistd.h>
22 
23 #include <algorithm>
24 #include <string>
25 
26 #include <android-base/file.h>
27 #include <android-base/logging.h>
28 #include <android-base/properties.h>
29 #include <android-base/unique_fd.h>
30 #include <bootloader_message/bootloader_message.h>
31 #include <gtest/gtest.h>
32 
33 using namespace std::string_literals;
34 
35 static const std::string UNCRYPT_SOCKET = "/dev/socket/uncrypt";
36 static const std::string INIT_SVC_SETUP_BCB = "init.svc.setup-bcb";
37 static const std::string INIT_SVC_CLEAR_BCB = "init.svc.clear-bcb";
38 static const std::string INIT_SVC_UNCRYPT = "init.svc.uncrypt";
39 static constexpr int SOCKET_CONNECTION_MAX_RETRY = 30;
40 
StopService()41 static void StopService() {
42   ASSERT_TRUE(android::base::SetProperty("ctl.stop", "setup-bcb"));
43   ASSERT_TRUE(android::base::SetProperty("ctl.stop", "clear-bcb"));
44   ASSERT_TRUE(android::base::SetProperty("ctl.stop", "uncrypt"));
45 
46   bool success = false;
47   for (int retry = 0; retry < SOCKET_CONNECTION_MAX_RETRY; retry++) {
48     std::string setup_bcb = android::base::GetProperty(INIT_SVC_SETUP_BCB, "");
49     std::string clear_bcb = android::base::GetProperty(INIT_SVC_CLEAR_BCB, "");
50     std::string uncrypt = android::base::GetProperty(INIT_SVC_UNCRYPT, "");
51     GTEST_LOG_(INFO) << "setup-bcb: [" << setup_bcb << "] clear-bcb: [" << clear_bcb
52                      << "] uncrypt: [" << uncrypt << "]";
53     if (setup_bcb != "running" && clear_bcb != "running" && uncrypt != "running") {
54       success = true;
55       break;
56     }
57     sleep(1);
58   }
59 
60   ASSERT_TRUE(success) << "uncrypt service is not available.";
61 }
62 
63 class UncryptTest : public ::testing::Test {
64  protected:
UncryptTest()65   UncryptTest() : has_misc(true) {}
66 
SetUp()67   void SetUp() override {
68     std::string err;
69     has_misc = !get_bootloader_message_blk_device(&err).empty();
70   }
71 
TearDown()72   void TearDown() override {
73     // Clear the BCB.
74     if (has_misc) {
75       std::string err;
76       ASSERT_TRUE(clear_bootloader_message(&err)) << "Failed to clear BCB: " << err;
77     }
78   }
79 
SetupOrClearBcb(bool isSetup,const std::string & message,const std::string & message_in_bcb) const80   void SetupOrClearBcb(bool isSetup, const std::string& message,
81                        const std::string& message_in_bcb) const {
82     // Restart the setup-bcb service.
83     StopService();
84     ASSERT_TRUE(android::base::SetProperty("ctl.start", isSetup ? "setup-bcb" : "clear-bcb"));
85 
86     // Test tends to be flaky if proceeding immediately ("Transport endpoint is not connected").
87     sleep(1);
88 
89     sockaddr_un un = {};
90     un.sun_family = AF_UNIX;
91     strlcpy(un.sun_path, UNCRYPT_SOCKET.c_str(), sizeof(un.sun_path));
92 
93     int sockfd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
94     ASSERT_NE(-1, sockfd);
95 
96     // Connect to the uncrypt socket.
97     bool success = false;
98     for (int retry = 0; retry < SOCKET_CONNECTION_MAX_RETRY; retry++) {
99       if (connect(sockfd, reinterpret_cast<sockaddr*>(&un), sizeof(sockaddr_un)) != 0) {
100         success = true;
101         break;
102       }
103       sleep(1);
104     }
105     ASSERT_TRUE(success);
106 
107     if (isSetup) {
108       // Send out the BCB message.
109       int length = static_cast<int>(message.size());
110       int length_out = htonl(length);
111       ASSERT_TRUE(android::base::WriteFully(sockfd, &length_out, sizeof(int)))
112           << "Failed to write length: " << strerror(errno);
113       ASSERT_TRUE(android::base::WriteFully(sockfd, message.data(), length))
114           << "Failed to write message: " << strerror(errno);
115     }
116 
117     // Check the status code from uncrypt.
118     int status;
119     ASSERT_TRUE(android::base::ReadFully(sockfd, &status, sizeof(int)));
120     ASSERT_EQ(100U, ntohl(status));
121 
122     // Ack having received the status code.
123     int code = 0;
124     ASSERT_TRUE(android::base::WriteFully(sockfd, &code, sizeof(int)));
125 
126     ASSERT_EQ(0, close(sockfd));
127 
128     ASSERT_TRUE(android::base::SetProperty("ctl.stop", isSetup ? "setup-bcb" : "clear-bcb"));
129 
130     // Verify the message by reading from BCB directly.
131     bootloader_message boot;
132     std::string err;
133     ASSERT_TRUE(read_bootloader_message(&boot, &err)) << "Failed to read BCB: " << err;
134 
135     if (isSetup) {
136       ASSERT_EQ("boot-recovery", std::string(boot.command));
137       ASSERT_EQ(message_in_bcb, std::string(boot.recovery));
138 
139       // The rest of the boot.recovery message should be zero'd out.
140       ASSERT_LE(message_in_bcb.size(), sizeof(boot.recovery));
141       size_t left = sizeof(boot.recovery) - message_in_bcb.size();
142       ASSERT_EQ(std::string(left, '\0'), std::string(&boot.recovery[message_in_bcb.size()], left));
143 
144       // Clear the BCB.
145       ASSERT_TRUE(clear_bootloader_message(&err)) << "Failed to clear BCB: " << err;
146     } else {
147       // All the bytes should be cleared.
148       ASSERT_EQ(std::string(sizeof(boot), '\0'),
149                 std::string(reinterpret_cast<const char*>(&boot), sizeof(boot)));
150     }
151   }
152 
VerifyBootloaderMessage(const std::string & expected)153   void VerifyBootloaderMessage(const std::string& expected) {
154     std::string err;
155     bootloader_message boot;
156     ASSERT_TRUE(read_bootloader_message(&boot, &err)) << "Failed to read BCB: " << err;
157 
158     // Check that we have all the expected bytes.
159     ASSERT_EQ(expected, std::string(reinterpret_cast<const char*>(&boot), sizeof(boot)));
160   }
161 
162   bool has_misc;
163 };
164 
TEST_F(UncryptTest,setup_bcb)165 TEST_F(UncryptTest, setup_bcb) {
166   if (!has_misc) {
167     GTEST_LOG_(INFO) << "Test skipped due to no /misc partition found on the device.";
168     return;
169   }
170 
171   std::string random_data;
172   random_data.reserve(sizeof(bootloader_message));
173   generate_n(back_inserter(random_data), sizeof(bootloader_message), []() { return rand() % 128; });
174 
175   bootloader_message boot;
176   memcpy(&boot, random_data.c_str(), random_data.size());
177 
178   std::string err;
179   ASSERT_TRUE(write_bootloader_message(boot, &err)) << "Failed to write BCB: " << err;
180   VerifyBootloaderMessage(random_data);
181 
182   ASSERT_TRUE(clear_bootloader_message(&err)) << "Failed to clear BCB: " << err;
183   VerifyBootloaderMessage(std::string(sizeof(bootloader_message), '\0'));
184 
185   std::string message = "--update_message=abc value";
186   std::string message_in_bcb = "recovery\n--update_message=abc value\n";
187   SetupOrClearBcb(true, message, message_in_bcb);
188 
189   SetupOrClearBcb(false, "", "");
190 
191   TemporaryFile wipe_package;
192   ASSERT_TRUE(android::base::WriteStringToFile(std::string(345, 'a'), wipe_package.path));
193 
194   // It's expected to store a wipe package in /misc, with the package size passed to recovery.
195   message = "--wipe_ab\n--wipe_package="s + wipe_package.path + "\n--reason=wipePackage"s;
196   message_in_bcb = "recovery\n--wipe_ab\n--wipe_package_size=345\n--reason=wipePackage\n";
197   SetupOrClearBcb(true, message, message_in_bcb);
198 }
199