Merge "fix: use EINA_* booleans instread of TRUE/FALSE" into tizen
[platform/framework/web/wrt.git] / src / view / webkit / injected-bundle / injected_bundle_decryption_support.cpp
1 /*
2  * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
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  * @file    injected_bundle_decryption_support.cpp
18  * @author  Jihoon Chung (jihoon.chung@samsung.com)
19  * @version 1.0
20  */
21
22 #include "injected_bundle_decryption_support.h"
23
24 #include <memory>
25 #include <set>
26 #include <string>
27 #include <sys/stat.h>
28 #include <ss_manager.h>
29 #include <openssl/sha.h>
30 #include <openssl/hmac.h>
31 #include <openssl/evp.h>
32 #include <openssl/bio.h>
33 #include <openssl/buffer.h>
34
35 #include <dpl/assert.h>
36 #include <dpl/string.h>
37 #include <dpl/wrt-dao-ro/widget_dao_read_only.h>
38 #include <dpl/utils/mime_type_utils.h>
39
40 #include <dpl/log/secure_log.h>
41 #include <pkgmgr-info.h>
42
43 namespace InjectedBundle {
44 namespace {
45 const char * const SCHEME_FILE_SLASH = "file://";
46 const char * const DATA_STRING = "data:";
47 const char * const BASE64_STRING = ";base64,";
48 const char QUESTION_MARK = '?';
49 const char ASTERISK_MARK = '#';
50 }
51
52 //Implementation class
53 class DecryptionSupportImplementation
54 {
55   private:
56     bool m_initialized;
57
58     WrtDB::TizenAppId m_appId;
59     WrtDB::EncryptedFileList m_encryptedFiles;
60     bool m_isEncrypted;
61     std::set<WrtDB::EncryptedFileInfo>::iterator m_targetIt;
62     bool m_isPreload;
63     WrtDB::TizenPkgId m_pkgId;
64
65
66     std::string getFilePath(const std::string& url)
67     {
68         std::string filePath = url;
69
70         size_t pos = filePath.find_first_not_of(SCHEME_FILE_SLASH);
71         if (pos != std::string::npos) {
72             filePath = filePath.substr(pos - 1);
73         }
74
75         pos = filePath.find_first_of(ASTERISK_MARK);
76         if (pos != std::string::npos) {
77             filePath = filePath.substr(0, pos);
78         }
79
80         pos = filePath.find_first_of(QUESTION_MARK);
81         if (pos != std::string::npos) {
82             filePath = filePath.substr(0, pos);
83         }
84
85         return filePath;
86     }
87
88     int ssmDecrypt(const std::string pkgId, const char* inBuf, int inSize, char** outBuf, int* outSize)
89     {
90         if (m_isPreload) {
91             return ssm_decrypt_preloaded_application(inBuf, inSize, outBuf,
92                     outSize);
93         } else {
94             return ssm_decrypt(pkgId.c_str(), pkgId.length(), inBuf, inSize, outBuf, outSize);
95         }
96     }
97
98     std::string doDecrypt(std::string filePath, int size)
99     {
100         struct stat buf;
101         if (0 == stat(filePath.c_str(), &buf)) {
102             const std::size_t fileSize = buf.st_size;
103             std::unique_ptr<unsigned char[]> inChunk;
104
105             FILE* fp = fopen(filePath.c_str(), "rb");
106             if (NULL == fp) {
107                 _E("Couldnot open file : %s", filePath.c_str());
108                 return std::string();
109             }
110
111             std::unique_ptr<unsigned char[]> DecryptedString(new unsigned
112                     char[fileSize]);
113             std::string pkgid(DPL::ToUTF8String(m_pkgId));
114
115             int writeCount = 0;
116             do {
117                 unsigned char getDecSize[4];
118                 memset(getDecSize, 0x00, sizeof(getDecSize));
119
120                 size_t readSize = fread(getDecSize, sizeof(unsigned char), sizeof(getDecSize), fp);
121                 if (0 != readSize) {
122                     unsigned int readBufSize = 0;
123                     std::istringstream(std::string((char*)getDecSize)) >> readBufSize;
124                     inChunk.reset(new unsigned char[readBufSize]);
125
126                     size_t decReadSize = fread(inChunk.get(), sizeof(unsigned char), readBufSize, fp);
127
128                     if (0 != decReadSize) {
129                         char *outChunk = NULL;
130                         int outSize = 0;
131                         if (0 != ssmDecrypt(pkgid, (char*)inChunk.get(), (int)decReadSize, &outChunk, &outSize))
132                         {
133                             _E("Failed to get decrypted resource");
134                             fclose(fp);
135                             return std::string();
136                         }
137                         memcpy(DecryptedString.get() + writeCount, outChunk, outSize);
138                         writeCount += outSize;
139                     }
140                 }
141             } while( 0 == std::feof(fp));
142             fclose(fp);
143             memset(DecryptedString.get() + size, '\n', fileSize - size);
144
145             BIO *bmem, *b64;
146             BUF_MEM *bptr;
147
148             b64 = BIO_new(BIO_f_base64());
149             bmem = BIO_new(BIO_s_mem());
150             b64 = BIO_push(b64, bmem);
151             if (BIO_write(b64, DecryptedString.get(), fileSize) <= 0) {
152                 _E("No data has been written");
153             }
154             BIO_flush(b64);
155             BIO_get_mem_ptr(b64, &bptr);
156
157             std::string base64Enc((char *)bptr->data, bptr->length - 1);
158             BIO_free_all(b64);
159
160             return base64Enc;
161         }
162         return std::string();
163     }
164
165   public:
166     DecryptionSupportImplementation() :
167         m_initialized(false),
168         m_isEncrypted(false),
169         m_isPreload(false)
170     {
171     }
172
173     void initialize(WrtDB::TizenAppId appId)
174     {
175         _D("called");
176         m_initialized = true;
177
178         m_appId = appId;
179         WrtDB::WidgetDAOReadOnly dao(m_appId);
180         dao.getEncryptedFileList(m_encryptedFiles);
181         if (!m_encryptedFiles.empty()) {
182           m_isEncrypted = true;
183           _D("encrypted application");
184         }
185         m_pkgId = dao.getTzPkgId();
186
187         bool isPreload = false;
188         bool isUpdate = false;
189         pkgmgrinfo_pkginfo_h handle = NULL;
190         std::string tzPkgId = DPL::ToUTF8String(dao.getTizenPkgId());
191
192         if (PMINFO_R_OK != pkgmgrinfo_pkginfo_get_pkginfo(tzPkgId.c_str(), &handle)) {
193             _E("Can't get package information : %s", tzPkgId.c_str());
194             return;
195         }
196         if (PMINFO_R_OK != pkgmgrinfo_pkginfo_is_preload(handle, &isPreload)) {
197             _E("Can't get package information : %s", tzPkgId.c_str());
198             return;
199         }
200         if (PMINFO_R_OK != pkgmgrinfo_pkginfo_is_update(handle, &isUpdate)) {
201             _E("Can't get package information : %s", tzPkgId.c_str());
202             return;
203         }
204
205         if (isPreload && !isUpdate) {
206             m_isPreload = true;
207             _D("preload application");
208         }
209     }
210
211     void deinitialize(void)
212     {
213         _D("called");
214
215         m_encryptedFiles.clear();
216         m_targetIt = m_encryptedFiles.end();
217         m_isEncrypted = false;
218         m_appId = DPL::String(L"");
219         m_initialized = false;
220     }
221
222     bool isNeedDecryption(std::string url)
223     {
224         if (!m_initialized) {
225             _E("not initialized");
226             return false;
227         }
228
229         if (0 != strncmp(url.c_str(), SCHEME_FILE_SLASH, strlen(SCHEME_FILE_SLASH))) {
230             return false;
231         }
232
233         std::set<WrtDB::EncryptedFileInfo>::iterator it;
234         WrtDB::EncryptedFileInfo info;
235         std::string filePath = getFilePath(url);
236         info.fileName = DPL::FromUTF8String(filePath);
237         if (m_encryptedFiles.end() != (it = m_encryptedFiles.find(info))) {
238             _D(" info file name : %s", DPL::ToUTF8String(it->fileName).c_str());
239             _D(" info file size : %d", it->fileSize);
240             m_targetIt = it;
241             return true;
242         }
243         return false;
244     }
245
246     std::string decryptResource(std::string url)
247     {
248         if (!m_initialized) {
249             _E("not initialized");
250             return std::string();
251         }
252
253         std::string filePath = getFilePath(url);
254         if (filePath != DPL::ToUTF8String(m_targetIt->fileName)) {
255             if (!isNeedDecryption(filePath)) {
256                 return std::string();
257             }
258         }
259
260         std::string decryptString =
261             doDecrypt(DPL::ToUTF8String(m_targetIt->fileName),
262                       m_targetIt->fileSize);
263         if (!decryptString.empty()) {
264             std::string destString = DATA_STRING;
265
266             std::string mimeString =
267                 DPL::ToUTF8String(
268                     MimeTypeUtils::identifyFileMimeType(
269                         DPL::FromUTF8String(url)));
270
271             destString += mimeString;
272             destString += BASE64_STRING;
273
274             decryptString.insert(0, destString);
275         }
276         return decryptString;
277     }
278 };
279
280 DecryptionSupport::DecryptionSupport() :
281     m_impl(new DecryptionSupportImplementation)
282 {
283 }
284
285 DecryptionSupport::~DecryptionSupport()
286 {
287 }
288
289 void DecryptionSupport::initialize(WrtDB::TizenAppId appId)
290 {
291     m_impl->initialize(appId);
292 }
293
294 void DecryptionSupport::deinitialize(void)
295 {
296     m_impl->deinitialize();
297 }
298
299 bool DecryptionSupport::isNeedDecryption(std::string url)
300 {
301     return m_impl->isNeedDecryption(url);
302 }
303
304 std::string DecryptionSupport::decryptResource(std::string url)
305 {
306     return m_impl->decryptResource(url);
307 }
308 }  // namespace InjectedBundle