xref: /aosp_15_r20/system/security/identity/fuzzers/credstore_service_fuzzer.cpp (revision e1997b9af69e3155ead6e072d106a0077849ffba)
1 /*
2  * Copyright (C) 2023 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 <android-base/logging.h>
18 #include <fuzzbinder/libbinder_driver.h>
19 #include <sys/stat.h>
20 
21 #include "CredentialStoreFactory.h"
22 
23 using android::security::identity::CredentialStoreFactory;
24 using namespace android;
25 
clearDirectory(const char * dirpath,bool recursive)26 void clearDirectory(const char* dirpath, bool recursive) {
27     DIR* dir = opendir(dirpath);
28     CHECK(dir != nullptr);
29     dirent* e;
30     struct stat s;
31     while ((e = readdir(dir)) != nullptr) {
32         if ((strcmp(e->d_name, ".") == 0) || (strcmp(e->d_name, "..") == 0)) {
33             continue;
34         }
35         std::string filename(dirpath);
36         filename.push_back('/');
37         filename.append(e->d_name);
38         int stat_result = lstat(filename.c_str(), &s);
39         CHECK_EQ(0, stat_result) << "unable to stat " << filename;
40         if (S_ISDIR(s.st_mode)) {
41             if (recursive) {
42                 clearDirectory(filename.c_str(), true);
43                 int rmdir_result = rmdir(filename.c_str());
44                 CHECK_EQ(0, rmdir_result) << filename;
45             }
46         } else {
47             int unlink_result = unlink(filename.c_str());
48             CHECK_EQ(0, unlink_result) << filename;
49         }
50     }
51     closedir(dir);
52 }
53 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)54 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
55     std::string dataDir = "/data/cred_store_fuzzer";
56     mkdir(dataDir.c_str(), 0700);
57     sp<CredentialStoreFactory> service = sp<CredentialStoreFactory>::make(dataDir);
58     fuzzService(service, FuzzedDataProvider(data, size));
59     clearDirectory(dataDir.c_str(), true);
60     rmdir(dataDir.c_str());
61     return 0;
62 }
63