[Release] wrt-installer_0.1.114
[framework/web/wrt-installer.git] / src / jobs / widget_install / task_certify.cpp
1 /*
2  * Copyright (c) 2011 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    task_certify.cpp
18  * @author  Pawel Sikorski (p.sikorski@samgsung.com)
19  * @version
20  * @brief
21  */
22
23 //SYSTEM INCLUDES
24 #include <cstring>
25 #include <string>
26 #include <sstream>
27 #include <dpl/assert.h>
28 #include <appcore-common.h> //TODO is it necessary here?
29 #include <pcrecpp.h>
30
31 //WRT INCLUDES
32 #include <widget_install/task_certify.h>
33 #include <widget_install/job_widget_install.h>
34 #include <widget_install/widget_install_errors.h>
35 #include <widget_install/widget_install_context.h>
36 #include <dpl/log/log.h>
37 #include <dpl/wrt-dao-ro/global_config.h>
38 #include "wac_widget_id.h"
39
40 #include <vcore/Certificate.h>
41 #include <vcore/SignatureReader.h>
42 #include <vcore/SignatureFinder.h>
43 #include <vcore/WrtSignatureValidator.h>
44 #include <dpl/utils/wrt_global_settings.h>
45 #include <dpl/wrt-dao-ro/global_dao_read_only.h>
46
47 #include <ITapiModem.h>
48 #include <tapi_common.h>
49
50 using namespace ValidationCore;
51 using namespace WrtDB;
52
53 namespace {
54
55 WidgetCertificateData toWidgetCertificateData(const SignatureData &data,
56                                               bool root)
57 {
58     WidgetCertificateData result;
59
60     result.chainId = data.getSignatureNumber();
61     LogDebug("result.chainId : " << result.chainId);
62
63     result.owner = data.isAuthorSignature() ?
64         WidgetCertificateData::AUTHOR : WidgetCertificateData::DISTRIBUTOR;
65
66     result.type = root ?
67         WidgetCertificateData::ROOT : WidgetCertificateData::ENDENTITY;
68
69     CertificatePtr certificate;
70
71     if (root) {
72         certificate = data.getRootCaCertificatePtr();
73     } else {
74         certificate = data.getEndEntityCertificatePtr();
75     }
76
77     Assert(certificate && !certificate->getCommonName().IsNull() &&
78            "CommonName is Null");
79
80     result.strCommonName = *certificate->getCommonName();
81
82     result.strMD5Fingerprint = std::string("md5 ") +
83         Certificate::FingerprintToColonHex(
84             certificate->getFingerprint(Certificate::FINGERPRINT_MD5));
85
86     result.strSHA1Fingerprint = std::string("sha-1 ") +
87         Certificate::FingerprintToColonHex(
88             certificate->getFingerprint(Certificate::FINGERPRINT_SHA1));
89
90     return result;
91 }
92
93 CertificatePtr getOldAuthorSignerCertificate(DPL::String appid)
94 {
95     WidgetDAOReadOnly dao(appid);
96     CertificateChainList chainList = dao.getWidgetCertificate(SIGNATURE_AUTHOR);
97
98     FOREACH(it, chainList)
99     {
100         ValidationCore::CertificateCollection chain;
101         if (false == chain.load(*it)) {
102             LogError("Chain is broken");
103         }
104
105         if (!chain.sort()) {
106             LogError("Chain failed at sorting");
107         }
108
109         ValidationCore::CertificateList list = chain.getCertificateList();
110
111         FOREACH(cert, list)
112         {
113             if (!(*cert)->isRootCert() && !(*cert)->isCA()) {
114                 return *cert;
115             }
116         }
117     }
118     return CertificatePtr(NULL);
119 }
120 } // namespace anonymous
121
122 namespace Jobs {
123 namespace WidgetInstall {
124 TaskCertify::TaskCertify(InstallerContext &inCont) :
125     DPL::TaskDecl<TaskCertify>(this),
126     m_contextData(inCont)
127 {
128     AddStep(&TaskCertify::StartStep);
129     AddStep(&TaskCertify::stepSignature);
130     // certi comparison determines whether the update.
131     if (true == m_contextData.isUpdateMode) {
132         AddStep(&TaskCertify::stepVerifyUpdate);
133     }
134     AddStep(&TaskCertify::EndStep);
135 }
136
137 void TaskCertify::processDistributorSignature(const SignatureData &data)
138 {
139     // this signature is verified -
140     // no point in check domain WAC_ROOT and WAC_RECOGNIZED
141     m_contextData.widgetSecurity.setDistributorSigned(true);
142
143     CertificateCollection collection;
144     collection.load(data.getCertList());
145     Assert(collection.sort() &&
146            "Certificate collection can't sort");
147
148     Assert(collection.isChain() &&
149            "Certificate collection is not able to create chain. "
150            "It is not possible to verify this signature.");
151
152     m_contextData.widgetSecurity.getCertificateChainListRef().push_back(
153         collection);
154
155     if (data.getSignatureNumber() == 1) {
156         m_contextData.widgetSecurity.getCertificateListRef().push_back(
157             toWidgetCertificateData(data, true));
158         m_contextData.widgetSecurity.getCertificateListRef().push_back(
159             toWidgetCertificateData(data, false));
160     }
161 }
162
163 void TaskCertify::processAuthorSignature(const SignatureData &data)
164 {
165     using namespace ValidationCore;
166     LogDebug("DNS Identity match!");
167     // this signature is verified or widget is distributor signed
168     m_contextData.widgetSecurity.setAuthorCertificatePtr(data.getEndEntityCertificatePtr());
169     CertificatePtr test = m_contextData.widgetSecurity.getAuthorCertificatePtr();
170
171     m_contextData.widgetSecurity.getCertificateListRef().push_back(
172         toWidgetCertificateData(data, true));
173     m_contextData.widgetSecurity.getCertificateListRef().push_back(
174         toWidgetCertificateData(data, false));
175
176     // match widget_id with one from dns identity set
177     WacWidgetId widgetId(m_contextData.widgetConfig.configInfo.widget_id);
178
179     CertificatePtr cert = data.getEndEntityCertificatePtr();
180     Assert(cert);
181     Certificate::AltNameSet dnsIdentity = cert->getAlternativeNameDNS();
182
183     CertificateCollection collection;
184     collection.load(data.getCertList());
185     collection.sort();
186     Assert(collection.isChain() &&
187            "Certificate collection is not able to create chain. "
188            "It is not possible to verify this signature.");
189
190     m_contextData.widgetSecurity.getAuthorsCertificateChainListRef().push_back(
191         collection);
192
193     FOREACH(it, dnsIdentity){
194         if (widgetId.matchHost(*it)) {
195             m_contextData.widgetSecurity.setRecognized(true);
196             return;
197         }
198     }
199 }
200
201 void TaskCertify::getSignatureFiles(std::string path, SignatureFileInfoSet& file)
202 {
203     LogDebug("path : " << path);
204     SignatureFileInfoSet signatureFiles;
205     SignatureFinder signatureFinder(path);
206     if (SignatureFinder::NO_ERROR != signatureFinder.find(file)) {
207         LogError("Error in Signature Finder : " << path);
208         ThrowMsg(Exceptions::SignatureNotFound,
209                 "Error openig temporary widget directory");
210     }
211 }
212
213 void TaskCertify::stepSignature()
214 {
215     LogDebug("================ Step: <<Signature>> ENTER ===============");
216
217     std::string widgetPath;
218     widgetPath = m_contextData.locations->getTemporaryPackageDir() + "/";
219
220     if (m_contextData.mode.command ==
221             InstallMode::Command::REINSTALL)
222     {
223         widgetPath = m_contextData.locations->getPackageInstallationDir() + "/";
224     }
225
226     SignatureFileInfoSet signatureFiles;
227
228     Try {
229         getSignatureFiles(widgetPath, signatureFiles);
230
231         if (signatureFiles.size() <= 0) {
232             widgetPath += std::string(WrtDB::GlobalConfig::GetWidgetSrcPath())
233                 + "/";
234             if (0 == access(widgetPath.c_str(), F_OK)) {
235                 getSignatureFiles(widgetPath, signatureFiles);
236             }
237         }
238     } Catch(Exceptions::SignatureNotFound) {
239         ReThrowMsg(Exceptions::SignatureNotFound, widgetPath);
240     }
241
242     SignatureFileInfoSet::reverse_iterator iter = signatureFiles.rbegin();
243     LogDebug("Number of signatures: " << signatureFiles.size());
244
245     for (; iter != signatureFiles.rend(); ++iter) {
246         LogDebug("Checking signature with id=" << iter->getFileNumber());
247         SignatureData data(widgetPath + iter->getFileName(),
248                            iter->getFileNumber());
249
250         Try {
251             SignatureReader xml;
252             xml.initialize(data, GlobalConfig::GetSignatureXmlSchema());
253             xml.read(data);
254
255             WrtSignatureValidator::Result result;
256
257             WrtSignatureValidator validator(
258                     WrtSignatureValidator::TIZEN,
259                     !GlobalSettings::
260                     OCSPTestModeEnabled(),
261                     !GlobalSettings::
262                     CrlTestModeEnabled(),
263                     false);
264
265             result = validator.check(data, widgetPath);
266
267             if (m_contextData.mode.installTime
268                 ==  InstallMode::InstallTime::PRELOAD)
269             {
270                 result = WrtSignatureValidator::SIGNATURE_VERIFIED;
271             }
272
273             if (result == WrtSignatureValidator::SIGNATURE_REVOKED) {
274                 LogWarning("Certificate is REVOKED");
275                 ThrowMsg(Exceptions::CertificateExpired,
276                          "Certificate is REVOKED");
277             }
278
279             if (result == WrtSignatureValidator::SIGNATURE_INVALID &&
280                     iter->getFileNumber() <= 1) {
281                 LogWarning("Signature is INVALID");
282                 // TODO change exception name
283                 ThrowMsg(Exceptions::SignatureInvalid,
284                          "Invalid Package");
285             }
286
287             if (data.isAuthorSignature()) {
288                 if (result == WrtSignatureValidator::SIGNATURE_VERIFIED ) {
289                     processAuthorSignature(data);
290                 }
291             } else {
292                 if (result != WrtSignatureValidator::SIGNATURE_INVALID) {
293                     processDistributorSignature(data);
294                 }
295             }
296         } Catch(ParserSchemaException::Base) {
297             LogError("Error occured in ParserSchema.");
298             ReThrowMsg(Exceptions::SignatureInvalid,
299                        "Error occured in ParserSchema.");
300         }
301     }
302
303     if (signatureFiles.empty()) {
304         LogDebug("No signature files has been found.");
305     }
306
307     LogDebug("================ Step: <<Signature>> DONE ================");
308
309     m_contextData.job->UpdateProgress(
310         InstallerContext::INSTALL_DIGSIG_CHECK,
311         "Widget Signature checked");
312 }
313
314 bool TaskCertify::isTizenWebApp() const
315 {
316     bool ret = FALSE;
317     if (m_contextData.widgetConfig.webAppType.appType
318         == WrtDB::AppType::APP_TYPE_TIZENWEBAPP)
319     {
320         ret = TRUE;
321     }
322
323     return ret;
324 }
325
326 void TaskCertify::stepVerifyUpdate()
327 {
328     LogDebug("Step: <<Check Update>>");
329     CertificatePtr newCertificate =
330         m_contextData.widgetSecurity.getAuthorCertificatePtr();
331     CertificatePtr oldCertificate =
332         getOldAuthorSignerCertificate(m_contextData.widgetConfig.tzAppid);
333
334     if (!!newCertificate && !!oldCertificate) {
335         if (0 != newCertificate->getBase64().compare(oldCertificate->getBase64())) {
336             LogDebug("old widget's author signer certificate : " <<
337                     oldCertificate->getBase64());
338             LogDebug("new widget's author signer certificate : " <<
339                     newCertificate->getBase64());
340             ThrowMsg(Exceptions::NotMatchedCertification,
341                     "Author signer certificates doesn't match \
342                     between old widget and installing widget");
343         }
344     } else {
345         if (!(NULL == newCertificate.Get() && NULL == oldCertificate.Get())) {
346             ThrowMsg(Exceptions::NotMatchedCertification,
347                     "Author signer certificates doesn't match \
348                     between old widget and installing widget");
349         }
350     }
351 }
352
353 void TaskCertify::StartStep()
354 {
355     LogDebug("--------- <TaskCertify> : START ----------");
356 }
357
358 void TaskCertify::EndStep()
359 {
360     LogDebug("Step: <<CERTYFYING DONE>>");
361
362     m_contextData.job->UpdateProgress(
363         InstallerContext::INSTALL_CERT_CHECK,
364         "Widget Certification Check Finished");
365
366     LogDebug("--------- <TaskCertify> : END ----------");
367 }
368 } //namespace WidgetInstall
369 } //namespace Jobs
370