1 /*
2  * Copyright (C) 2021 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 "../FileUtils.h"
18 
19 #include <android-base/logging.h>
20 #include <binder/Binder.h>
21 #include <binder/Parcel.h>
22 #include <binder/RpcServer.h>
23 #include <binder/RpcTlsTestUtils.h>
24 #include <binder/RpcTransport.h>
25 #include <binder/RpcTransportRaw.h>
26 #include <binder/RpcTransportTls.h>
27 #include <binder/unique_fd.h>
28 #include <fuzzer/FuzzedDataProvider.h>
29 #include <openssl/rand.h>
30 #include <openssl/ssl.h>
31 
32 #include <sys/resource.h>
33 #include <sys/socket.h>
34 #include <sys/un.h>
35 
36 using android::binder::GetExecutableDirectory;
37 using android::binder::unique_fd;
38 
39 namespace android {
40 
41 static const std::string kSock = std::string(getenv("TMPDIR") ?: "/tmp") +
42         "/binderRpcFuzzerSocket_" + std::to_string(getpid());
43 
44 class SomeBinder : public BBinder {
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags=0)45     status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags = 0) {
46         (void)flags;
47 
48         if ((code & 1) == 0) {
49             sp<IBinder> binder;
50             (void)data.readStrongBinder(&binder);
51             if (binder != nullptr) {
52                 (void)binder->pingBinder();
53             }
54         }
55         if ((code & 2) == 0) {
56             (void)data.readInt32();
57         }
58         if ((code & 4) == 0) {
59             (void)reply->writeStrongBinder(sp<BBinder>::make());
60         }
61 
62         return OK;
63     }
64 };
65 
passwordCallback(char * buf,int size,int,void *)66 int passwordCallback(char* buf, int size, int /*rwflag*/, void* /*u*/) {
67     constexpr const char pass[] = "xxxx"; // See create_certs.sh
68     if (size <= 0) return 0;
69     int numCopy = std::min<int>(size, sizeof(pass));
70     (void)memcpy(buf, pass, numCopy);
71     return numCopy;
72 }
73 
74 struct ServerAuth {
75     bssl::UniquePtr<EVP_PKEY> pkey;
76     bssl::UniquePtr<X509> cert;
77 };
78 
79 // Use pre-configured keys because runtime generated keys / certificates are not
80 // deterministic, and the algorithm is time consuming.
readServerKeyAndCert()81 ServerAuth readServerKeyAndCert() {
82     ServerAuth ret;
83 
84     auto keyPath = GetExecutableDirectory() + "/data/server.key";
85     bssl::UniquePtr<BIO> keyBio(BIO_new_file(keyPath.c_str(), "r"));
86     ret.pkey.reset(PEM_read_bio_PrivateKey(keyBio.get(), nullptr, passwordCallback, nullptr));
87     CHECK_NE(ret.pkey.get(), nullptr);
88 
89     auto certPath = GetExecutableDirectory() + "/data/server.crt";
90     bssl::UniquePtr<BIO> certBio(BIO_new_file(certPath.c_str(), "r"));
91     ret.cert.reset(PEM_read_bio_X509(certBio.get(), nullptr, nullptr, nullptr));
92     CHECK_NE(ret.cert.get(), nullptr);
93 
94     return ret;
95 }
96 
createServerRpcAuth()97 std::unique_ptr<RpcAuth> createServerRpcAuth() {
98     static auto sAuth = readServerKeyAndCert();
99 
100     CHECK(EVP_PKEY_up_ref(sAuth.pkey.get()));
101     bssl::UniquePtr<EVP_PKEY> pkey(sAuth.pkey.get());
102     CHECK(X509_up_ref(sAuth.cert.get()));
103     bssl::UniquePtr<X509> cert(sAuth.cert.get());
104 
105     return std::make_unique<RpcAuthPreSigned>(std::move(pkey), std::move(cert));
106 }
107 
makeTransportCtxFactory(FuzzedDataProvider * provider)108 std::unique_ptr<RpcTransportCtxFactory> makeTransportCtxFactory(FuzzedDataProvider* provider) {
109     bool isTls = provider->ConsumeBool();
110     if (!isTls) {
111         return RpcTransportCtxFactoryRaw::make();
112     }
113     status_t verifyStatus = provider->ConsumeIntegral<status_t>();
114     auto verifier = std::make_shared<RpcCertificateVerifierNoOp>(verifyStatus);
115     return RpcTransportCtxFactoryTls::make(verifier, createServerRpcAuth());
116 }
117 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)118 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
119     if (size > 50000) return 0;
120     FuzzedDataProvider provider(data, size);
121     RAND_reset_for_fuzzing();
122 
123     unlink(kSock.c_str());
124 
125     sp<RpcServer> server = RpcServer::make(makeTransportCtxFactory(&provider));
126     server->setRootObject(sp<SomeBinder>::make());
127     CHECK_EQ(OK, server->setupUnixDomainServer(kSock.c_str()));
128 
129     std::thread serverThread([=] { (void)server->join(); });
130 
131     sockaddr_un addr{
132             .sun_family = AF_UNIX,
133     };
134     CHECK_LT(kSock.size(), sizeof(addr.sun_path));
135     memcpy(&addr.sun_path, kSock.c_str(), kSock.size());
136 
137     std::vector<unique_fd> connections;
138 
139     bool hangupBeforeShutdown = provider.ConsumeBool();
140 
141     // b/260736889 - limit arbitrarily, due to thread resource exhaustion, which currently
142     // aborts. Servers should consider RpcServer::setConnectionFilter instead.
143     constexpr size_t kMaxConnections = 10;
144 
145     while (provider.remaining_bytes() > 0) {
146         if (connections.empty() ||
147             (connections.size() < kMaxConnections && provider.ConsumeBool())) {
148             unique_fd fd(TEMP_FAILURE_RETRY(socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)));
149             CHECK_NE(fd.get(), -1);
150             CHECK_EQ(0,
151                      TEMP_FAILURE_RETRY(
152                              connect(fd.get(), reinterpret_cast<sockaddr*>(&addr), sizeof(addr))))
153                     << strerror(errno);
154             connections.push_back(std::move(fd));
155         } else {
156             size_t idx = provider.ConsumeIntegralInRange<size_t>(0, connections.size() - 1);
157 
158             if (provider.ConsumeBool()) {
159                 std::string writeData = provider.ConsumeRandomLengthString();
160                 ssize_t size = TEMP_FAILURE_RETRY(send(connections.at(idx).get(), writeData.data(),
161                                                        writeData.size(), MSG_NOSIGNAL));
162                 CHECK(errno == EPIPE || size == writeData.size())
163                         << size << " " << writeData.size() << " " << strerror(errno);
164             } else {
165                 connections.erase(connections.begin() + idx); // hang up
166             }
167         }
168     }
169 
170     if (hangupBeforeShutdown) {
171         connections.clear();
172         while (!server->listSessions().empty() || server->numUninitializedSessions()) {
173             // wait for all threads to finish processing existing information
174             usleep(1);
175         }
176     }
177 
178     while (server->hasActiveRequests()) {
179         usleep(10);
180     }
181 
182     while (!server->shutdown()) usleep(1);
183     serverThread.join();
184 
185     return 0;
186 }
187 
188 } // namespace android
189