Merge branch working 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/wrt-dao-ro/global_config.h>
39 #include <dpl/utils/mime_type_utils.h>
40
41 #include <dpl/log/secure_log.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             BIO_write(b64, DecryptedString.get(), fileSize);
152             BIO_flush(b64);
153             BIO_get_mem_ptr(b64, &bptr);
154
155             std::string base64Enc((char *)bptr->data, bptr->length - 1);
156             BIO_free_all(b64);
157
158             return base64Enc;
159         }
160         return std::string();
161     }
162
163   public:
164     DecryptionSupportImplementation() :
165         m_initialized(false),
166         m_isEncrypted(false),
167         m_isPreload(false)
168     {
169     }
170
171     void initialize(WrtDB::TizenAppId appId)
172     {
173         _D("called");
174
175         m_appId = appId;
176         WrtDB::WidgetDAOReadOnly dao(m_appId);
177         dao.getEncryptedFileList(m_encryptedFiles);
178         if (!m_encryptedFiles.empty()) {
179           m_isEncrypted = true;
180           _D("encrypted application");
181         }
182         m_pkgId = dao.getTzPkgId();
183
184         std::string installedPath =
185             DPL::ToUTF8String(*dao.getWidgetInstalledPath());
186         std::string preloadPath(WrtDB::GlobalConfig::GetUserPreloadedWidgetPath());
187         if (0 == installedPath.compare(0, preloadPath.length(), preloadPath)) {
188             m_isPreload = true;
189             _D("preload application");
190         }
191
192         m_initialized = true;
193     }
194
195     void deinitialize(void)
196     {
197         _D("called");
198
199         m_encryptedFiles.clear();
200         m_targetIt = m_encryptedFiles.end();
201         m_isEncrypted = false;
202         m_appId = DPL::String(L"");
203         m_initialized = false;
204     }
205
206     bool isNeedDecryption(std::string url)
207     {
208         if (!m_initialized) {
209             _E("not initialized");
210             return false;
211         }
212
213         if (0 != strncmp(url.c_str(), SCHEME_FILE_SLASH, strlen(SCHEME_FILE_SLASH))) {
214             return false;
215         }
216
217         std::set<WrtDB::EncryptedFileInfo>::iterator it;
218         WrtDB::EncryptedFileInfo info;
219         std::string filePath = getFilePath(url);
220         info.fileName = DPL::FromUTF8String(filePath);
221         if (m_encryptedFiles.end() != (it = m_encryptedFiles.find(info))) {
222             _D(" info file name : %s", DPL::ToUTF8String(it->fileName).c_str());
223             _D(" info file size : %d", it->fileSize);
224             m_targetIt = it;
225             return true;
226         }
227         return false;
228     }
229
230     std::string decryptResource(std::string url)
231     {
232         if (!m_initialized) {
233             _E("not initialized");
234             return std::string();
235         }
236
237         std::string filePath = getFilePath(url);
238         if (filePath != DPL::ToUTF8String(m_targetIt->fileName)) {
239             if (!isNeedDecryption(filePath)) {
240                 return std::string();
241             }
242         }
243
244         std::string decryptString =
245             doDecrypt(DPL::ToUTF8String(m_targetIt->fileName),
246                       m_targetIt->fileSize);
247         if (!decryptString.empty()) {
248             std::string destString = DATA_STRING;
249
250             std::string mimeString =
251                 DPL::ToUTF8String(
252                     MimeTypeUtils::identifyFileMimeType(
253                         DPL::FromUTF8String(url)));
254
255             destString += mimeString;
256             destString += BASE64_STRING;
257
258             decryptString.insert(0, destString);
259         }
260         return decryptString;
261     }
262 };
263
264 DecryptionSupport::DecryptionSupport() :
265     m_impl(new DecryptionSupportImplementation)
266 {
267 }
268
269 DecryptionSupport::~DecryptionSupport()
270 {
271 }
272
273 void DecryptionSupport::initialize(WrtDB::TizenAppId appId)
274 {
275     m_impl->initialize(appId);
276 }
277
278 void DecryptionSupport::deinitialize(void)
279 {
280     m_impl->deinitialize();
281 }
282
283 bool DecryptionSupport::isNeedDecryption(std::string url)
284 {
285     return m_impl->isNeedDecryption(url);
286 }
287
288 std::string DecryptionSupport::decryptResource(std::string url)
289 {
290     return m_impl->decryptResource(url);
291 }
292 }  // namespace InjectedBundle