1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "dlp_file_kits.h"
17 #include <cstdlib>
18 #include <fcntl.h>
19 #include <string>
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23 #include <unordered_map>
24 #include "dlp_permission_log.h"
25 #include "dlp_zip.h"
26 #include "file_uri.h"
27 #include "securec.h"
28 #include "dlp_utils.h"
29 #include "dlp_permission.h"
30 
31 namespace OHOS {
32 namespace Security {
33 namespace DlpPermission {
34 namespace {
35     static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_DLP_PERMISSION, "DlpFileKits"};
36 } // namespace
37 using Want = OHOS::AAFwk::Want;
38 using WantParams = OHOS::AAFwk::WantParams;
39 
40 static const std::unordered_map<std::string, std::string> SUFFIX_MIMETYPE_MAP = {
41     {"txt", "text/plain"},
42     {"doc", "application/msword"},
43     {"docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
44     {"dot", "application/msword"},
45     {"dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
46     {"odt", "application/vnd.oasis.opendocument.text"},
47     {"pdf", "application/pdf"},
48     {"pot", "application/vnd.ms-powerpoint"},
49     {"potx", "application/vnd.openxmlformats-officedocument.presentationml.template"},
50     {"pps", "application/vnd.ms-powerpoint"},
51     {"ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
52     {"ppt", "application/vnd.ms-powerpoint"},
53     {"pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
54     {"rtf", "text/rtf"},
55     {"xls", "application/vnd.ms-excel"},
56     {"xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
57     {"xlt", "application/vnd.ms-excel"},
58     {"xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
59     {"xlam", "application/vnd.ms-excel.addin.macroEnabled.12"},
60     {"xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
61     {"xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"},
62     {"xltm", "application/vnd.ms-excel.template.macroEnabled.12"},
63     {"xml", "text/xml"},
64     {"ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"},
65     {"pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
66     {"ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
67     {"potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"},
68     {"docm", "application/vnd.ms-word.document.macroEnabled.12"},
69     {"dotm", "application/vnd.ms-word.template.macroEnabled.12"},
70     {"odp", "application/vnd.oasis.opendocument.presentation"},
71 };
72 
IsDlpFileName(const std::string & dlpFileName)73 static bool IsDlpFileName(const std::string& dlpFileName)
74 {
75     uint32_t dlpSuffixLen = DLP_FILE_SUFFIX.size();
76     uint32_t fileNameLen = dlpFileName.size();
77     if (fileNameLen <= dlpSuffixLen) {
78         return false;
79     }
80 
81     if (dlpFileName.substr(fileNameLen - dlpSuffixLen, dlpSuffixLen) != DLP_FILE_SUFFIX) {
82         return false;
83     }
84     return true;
85 }
86 
GetMimeTypeBySuffix(const std::string & suffix)87 static std::string GetMimeTypeBySuffix(const std::string& suffix)
88 {
89     std::string lower = DlpUtils::ToLowerString(suffix);
90     auto iter = SUFFIX_MIMETYPE_MAP.find(lower);
91     if (iter != SUFFIX_MIMETYPE_MAP.end()) {
92         return iter->second;
93     }
94     return DEFAULT_STRING;
95 }
96 
IsValidDlpHeader(const struct DlpHeader & head)97 static bool IsValidDlpHeader(const struct DlpHeader& head)
98 {
99     if (head.magic != DLP_FILE_MAGIC || head.certSize == 0 || head.certSize > DLP_MAX_CERT_SIZE ||
100         head.contactAccountSize == 0 || head.contactAccountSize > DLP_MAX_CERT_SIZE ||
101         head.certOffset != sizeof(struct DlpHeader)) {
102         DLP_LOG_ERROR(LABEL, "Parse dlp file header error. certSize=%{public}u, contactAccountSize=%{public}u",
103             head.certSize, head.contactAccountSize);
104         return false;
105     }
106     if (head.contactAccountOffset != (sizeof(struct DlpHeader) + head.certSize) ||
107         head.txtOffset != (sizeof(struct DlpHeader) + head.certSize + head.contactAccountSize + head.offlineCertSize) ||
108         head.txtSize > DLP_MAX_CONTENT_SIZE || head.offlineCertSize > DLP_MAX_CERT_SIZE) {
109         DLP_LOG_ERROR(LABEL, "Parse dlp file header error.");
110         return false;
111     }
112     return true;
113 }
114 
IsDlpFile(int32_t dlpFd)115 bool DlpFileKits::IsDlpFile(int32_t dlpFd)
116 {
117     if (dlpFd < 0) {
118         DLP_LOG_ERROR(LABEL, "dlp file fd is invalid");
119         return false;
120     }
121 
122     if (IsZipFile(dlpFd)) {
123         return CheckUnzipFileInfo(dlpFd);
124     }
125 
126     off_t curPos = lseek(dlpFd, 0, SEEK_CUR);
127     if (curPos < 0) {
128         DLP_LOG_ERROR(LABEL, "seek dlp file current failed, %{public}s", strerror(errno));
129         return false;
130     }
131 
132     if (lseek(dlpFd, 0, SEEK_SET) == static_cast<off_t>(-1)) {
133         DLP_LOG_ERROR(LABEL, "seek dlp file start failed, %{public}s", strerror(errno));
134         return false;
135     }
136     struct DlpHeader head;
137     if (read(dlpFd, &head, sizeof(struct DlpHeader)) != sizeof(struct DlpHeader)) {
138         DLP_LOG_ERROR(LABEL, "can not read dlp file head, %{public}s", strerror(errno));
139         return false;
140     }
141 
142     if (lseek(dlpFd, curPos, SEEK_SET) < 0) {
143         DLP_LOG_ERROR(LABEL, "seek dlp file back failed, %{public}s", strerror(errno));
144         return false;
145     }
146 
147     return IsValidDlpHeader(head);
148 }
149 
GetSandboxFlag(Want & want)150 bool DlpFileKits::GetSandboxFlag(Want& want)
151 {
152     std::string action = want.GetAction();
153     if (action != TAG_ACTION_VIEW && action != TAG_ACTION_EDIT) {
154         DLP_LOG_DEBUG(LABEL, "Action %{public}s is not dlp scene", action.c_str());
155         return false;
156     }
157 
158     std::string uri = want.GetUriString();
159     AppFileService::ModuleFileUri::FileUri fileUri(uri);
160     std::string fileName = fileUri.GetName();
161     if (fileName.empty() || !IsDlpFileName(fileName)) {
162         DLP_LOG_DEBUG(LABEL, "File name is not exist or not dlp, name=%{private}s", fileName.c_str());
163         return false;
164     }
165     std::string path = fileUri.GetRealPath();
166     int fd = open(path.c_str(), O_RDONLY);
167     if (fd == -1) {
168         DLP_LOG_ERROR(LABEL, "open file error, uri=%{private}s path=%{private}s error=%{public}d", uri.c_str(),
169             path.c_str(), errno);
170         return false;
171     }
172     if (!IsDlpFile(fd)) {
173         DLP_LOG_WARN(LABEL, "Fd %{public}d is not dlp file", fd);
174         close(fd);
175         return false;
176     }
177     close(fd);
178     fd = -1;
179     std::string realSuffix = DlpUtils::GetDlpFileRealSuffix(fileName);
180     if (realSuffix != DEFAULT_STRING) {
181         DLP_LOG_DEBUG(LABEL, "Real suffix is %{public}s", realSuffix.c_str());
182         std::string realType = GetMimeTypeBySuffix(realSuffix);
183         if (realType != DEFAULT_STRING) {
184             want.SetType(realType);
185         } else {
186             DLP_LOG_INFO(LABEL, "Real suffix %{public}s not match known type, using origin type %{public}s",
187                 realSuffix.c_str(), want.GetType().c_str());
188         }
189     }
190     DLP_LOG_INFO(LABEL, "Sanbox flag is true");
191     return true;
192 }
193 
ConvertAbilityInfoWithBundleName(const std::string & abilityName,const std::string & bundleName,std::vector<AppExecFwk::AbilityInfo> & abilityInfos)194 static int32_t ConvertAbilityInfoWithBundleName(const std::string &abilityName, const std::string &bundleName,
195     std::vector<AppExecFwk::AbilityInfo> &abilityInfos)
196 {
197     Want want;
198     AppExecFwk::ElementName name;
199     name.SetAbilityName(abilityName);
200     name.SetBundleName(bundleName);
201     want.SetElement(name);
202 
203     int32_t flags = static_cast<int32_t>(AppExecFwk::GetAbilityInfoFlag::GET_ABILITY_INFO_DEFAULT);
204     int32_t userId = 0;
205     int32_t ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
206     if (ret != ERR_OK) {
207         DLP_LOG_ERROR(LABEL, "Get os account localId error, %{public}d", ret);
208         return DLP_PARSE_ERROR_GET_ACCOUNT_FAIL;
209     }
210 
211     auto bundleMgrProxy = DlpUtils::GetBundleMgrProxy();
212     if (bundleMgrProxy == nullptr) {
213         return DLP_SERVICE_ERROR_IPC_REQUEST_FAIL;
214     }
215     ret = bundleMgrProxy->QueryAbilityInfosV9(want, flags, userId, abilityInfos);
216     if (ret != ERR_OK) {
217         DLP_LOG_ERROR(LABEL, "Get ability info error, %{public}d", ret);
218         return DLP_PARSE_ERROR_BMS_ERROR;
219     }
220     return DLP_OK;
221 }
222 
IsSupportDlp(const std::vector<std::string> & whitelist,const std::string & bundleName,const std::string & fileType)223 static bool IsSupportDlp(const std::vector<std::string> &whitelist,
224     const std::string &bundleName, const std::string &fileType)
225 {
226     auto it = std::find(whitelist.begin(), whitelist.end(), bundleName);
227     if (it != whitelist.end()) {
228         return true;
229     }
230     return false;
231 }
232 
ConvertAbilityInfoWithSupportDlp(const AAFwk::Want & want,std::vector<AppExecFwk::AbilityInfo> & abilityInfos)233 void DlpFileKits::ConvertAbilityInfoWithSupportDlp(const AAFwk::Want &want,
234     std::vector<AppExecFwk::AbilityInfo> &abilityInfos)
235 {
236     if (abilityInfos.size() == 0) {
237         DLP_LOG_INFO(LABEL, "ability size is zero.");
238         return;
239     }
240 
241     std::string uri = want.GetUriString();
242     AppFileService::ModuleFileUri::FileUri fileUri(uri);
243     std::string fileName = fileUri.GetName();
244     if (fileName.empty() || !IsDlpFileName(fileName)) {
245         DLP_LOG_ERROR(LABEL, "File name is not exist or not dlp, name=%{private}s", fileName.c_str());
246         return;
247     }
248 
249     std::string realSuffix = DlpUtils::GetDlpFileRealSuffix(fileName);
250     if (realSuffix == DEFAULT_STRING) {
251         return;
252     }
253     std::string fileType = DlpUtils::GetFileTypeBySuffix(realSuffix);
254     if (fileType == DEFAULT_STRING) {
255         DLP_LOG_ERROR(LABEL, "%{public}s is not support dlp.", realSuffix.c_str());
256         return;
257     }
258     std::vector<std::string> whitelist;
259     if (!DlpUtils::GetWhitelistWithType(DLP_WHITELIST, fileType, whitelist)) {
260         return;
261     }
262 
263     for (auto it = abilityInfos.begin(); it != abilityInfos.end();) {
264         if (!IsSupportDlp(whitelist, it->bundleName, fileType)) {
265             abilityInfos.erase(it);
266         } else {
267             ++it;
268         }
269     }
270 
271     if (abilityInfos.size() != 0) {
272         return;
273     }
274     std::vector<std::string> defalutWhitelist;
275     if (!DlpUtils::GetWhitelistWithType(DLP_WHITELIST, DLP_DEFAULT_WHITELIST, defalutWhitelist) ||
276         defalutWhitelist.size() <= 1) {
277         return;
278     }
279     int32_t ret = ConvertAbilityInfoWithBundleName(defalutWhitelist[0], defalutWhitelist[1], abilityInfos);
280     if (ret != DLP_OK) {
281         DLP_LOG_ERROR(LABEL, "Query ability info with bundleName error.");
282     }
283 }
284 }  // namespace DlpPermission
285 }  // namespace Security
286 }  // namespace OHOS
287