[Release] wrt-installer_0.1.28
[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 <dpl/assert.h>
27 #include <appcore-common.h> //TODO is it necessary here?
28 #include <pcrecpp.h>
29
30 //WRT INCLUDES
31 #include <widget_install/task_certify.h>
32 #include <widget_install/job_widget_install.h>
33 #include <widget_install/widget_install_errors.h>
34 #include <widget_install/widget_install_context.h>
35 #include <dpl/log/log.h>
36 #include <dpl/wrt-dao-ro/global_config.h>
37 #include "wac_widget_id.h"
38
39 #include <vcore/Certificate.h>
40 #include <vcore/SignatureReader.h>
41 #include <vcore/SignatureFinder.h>
42 #include <vcore/WrtSignatureValidator.h>
43 #include <dpl/utils/wrt_global_settings.h>
44 #include <dpl/wrt-dao-ro/global_dao_read_only.h>
45
46 #include <ITapiModem.h>
47 #include <tapi_common.h>
48
49 using namespace ValidationCore;
50 using namespace WrtDB;
51
52 namespace {
53 const std::string LABEL_NEW_LINE = "<br>";
54 const std::string LABEL_NEW_LINE_2 = "<br><br>";
55 const std::string UNTRUSTED_WIDGET = "It is an Untrusted Widget";
56 const char *QUESTION = "Do you wanto to install?";
57
58 WidgetCertificateData toWidgetCertificateData(const SignatureData &data,
59                                               bool root)
60 {
61     WidgetCertificateData result;
62
63     result.chainId = data.getSignatureNumber();
64     LogDebug("result.chainId : " << result.chainId);
65
66     result.owner = data.isAuthorSignature() ?
67         WidgetCertificateData::AUTHOR : WidgetCertificateData::DISTRIBUTOR;
68
69     result.type = root ?
70         WidgetCertificateData::ROOT : WidgetCertificateData::ENDENTITY;
71
72     CertificatePtr certificate;
73
74     if (root) {
75         certificate = data.getRootCaCertificatePtr();
76     } else {
77         certificate = data.getEndEntityCertificatePtr();
78     }
79
80     Assert(certificate && !certificate->getCommonName().IsNull() &&
81            "CommonName is Null");
82
83     result.strCommonName = *certificate->getCommonName();
84
85     result.strMD5Fingerprint = std::string("md5 ") +
86         Certificate::FingerprintToColonHex(
87             certificate->getFingerprint(Certificate::FINGERPRINT_MD5));
88
89     result.strSHA1Fingerprint = std::string("sha-1 ") +
90         Certificate::FingerprintToColonHex(
91             certificate->getFingerprint(Certificate::FINGERPRINT_SHA1));
92
93     return result;
94 }
95
96 CertificatePtr getOldAuthorSignerCertificate(DPL::String appid)
97 {
98     WidgetDAOReadOnly dao(appid);
99     CertificateChainList chainList = dao.getWidgetCertificate(SIGNATURE_AUTHOR);
100
101     FOREACH(it, chainList)
102     {
103         ValidationCore::CertificateCollection chain;
104         if (false == chain.load(*it)) {
105             LogError("Chain is broken");
106         }
107
108         if (!chain.sort()) {
109             LogError("Chain failed at sorting");
110         }
111
112         ValidationCore::CertificateList list = chain.getCertificateList();
113
114         FOREACH(cert, list)
115         {
116             if (!(*cert)->isRootCert() && !(*cert)->isCA()) {
117                 return *cert;
118             }
119         }
120     }
121     return CertificatePtr(NULL);
122 }
123 } // namespace anonymous
124
125 namespace Jobs {
126 namespace WidgetInstall {
127 TaskCertify::TaskCertify(InstallerContext &inCont) :
128     DPL::TaskDecl<TaskCertify>(this),
129     WidgetInstallPopup(inCont),
130     m_contextData(inCont)
131 {
132     AddStep(&TaskCertify::stepSignature);
133     // certi comparison determines whether the update.
134     if (true == m_contextData.isUpdateMode) {
135         AddStep(&TaskCertify::stepVerifyUpdate);
136     }
137
138     // Block until fixed popup issues
139     if (!GlobalSettings::PopupsTestModeEnabled()
140         && !m_installContext.m_quiet && !isTizenWebApp())
141     {
142         AddStep(&TaskCertify::stepWarningPopup);
143         AddStep(&TaskCertify::stepWarningPopupAnswer);
144         AddStep(&TaskCertify::stepAuthorInfoPopup);
145         AddStep(&TaskCertify::stepAuthorInfoPopupAnswer);
146         AddStep(&TaskCertify::StepDeletePopupWin);
147     }
148     AddStep(&TaskCertify::stepFinalize);
149 }
150
151 void TaskCertify::processDistributorSignature(const SignatureData &data)
152 {
153     // this signature is verified -
154     // no point in check domain WAC_ROOT and WAC_RECOGNIZED
155     m_contextData.wacSecurity.setDistributorSigned(true);
156
157     CertificateCollection collection;
158     collection.load(data.getCertList());
159     Assert(collection.sort() &&
160            "Certificate collection can't sort");
161
162     Assert(collection.isChain() &&
163            "Certificate collection is not able to create chain. "
164            "It is not possible to verify this signature.");
165
166     m_contextData.wacSecurity.getCertificateChainListRef().push_back(
167         collection);
168
169     if (data.getSignatureNumber() == 1) {
170         m_contextData.wacSecurity.getCertificateListRef().push_back(
171             toWidgetCertificateData(data, true));
172         m_contextData.wacSecurity.getCertificateListRef().push_back(
173             toWidgetCertificateData(data, false));
174     }
175 }
176
177 void TaskCertify::processAuthorSignature(const SignatureData &data)
178 {
179     using namespace ValidationCore;
180     LogInfo("DNS Identity match!");
181     // this signature is verified or widget is distributor signed
182     m_contextData.wacSecurity.setAuthorCertificatePtr(data.getEndEntityCertificatePtr());
183     CertificatePtr test = m_contextData.wacSecurity.getAuthorCertificatePtr();
184
185     m_contextData.wacSecurity.getCertificateListRef().push_back(
186         toWidgetCertificateData(data, true));
187     m_contextData.wacSecurity.getCertificateListRef().push_back(
188         toWidgetCertificateData(data, false));
189
190     // match widget_id with one from dns identity set
191     WacWidgetId widgetId(m_contextData.widgetConfig.configInfo.widget_id);
192
193     CertificatePtr cert = data.getEndEntityCertificatePtr();
194     Assert(cert);
195     Certificate::AltNameSet dnsIdentity = cert->getAlternativeNameDNS();
196
197     CertificateCollection collection;
198     collection.load(data.getCertList());
199     collection.sort();
200     Assert(collection.isChain() &&
201            "Certificate collection is not able to create chain. "
202            "It is not possible to verify this signature.");
203
204     m_contextData.wacSecurity.getAuthorsCertificateChainListRef().push_back(
205         collection);
206
207     FOREACH(it, dnsIdentity){
208         if (widgetId.matchHost(*it)) {
209             m_contextData.wacSecurity.setRecognized(true);
210             return;
211         }
212     }
213 }
214
215 void TaskCertify::stepSignature()
216 {
217     LogInfo("================ Step: <<Signature>> ENTER ===============");
218
219     std::string widgetPath;
220     if (m_contextData.widgetConfig.packagingType ==
221         WrtDB::PKG_TYPE_DIRECTORY_WEB_APP)
222     {
223         widgetPath = m_contextData.locations->getSourceDir() + "/";
224     } else {
225         widgetPath = m_contextData.locations->getTemporaryPackageDir() + "/";
226     }
227
228     SignatureFileInfoSet signatureFiles;
229     SignatureFinder signatureFinder(widgetPath);
230     if (SignatureFinder::NO_ERROR != signatureFinder.find(signatureFiles)) {
231         LogError("Error in Signature Finder");
232         ThrowMsg(Exceptions::SignatureNotFound,
233                  "Error openig temporary widget directory");
234     }
235
236     SignatureFileInfoSet::reverse_iterator iter = signatureFiles.rbegin();
237     LogInfo("Number of signatures: " << signatureFiles.size());
238
239     bool complianceMode = GlobalDAOReadOnly::getComplianceMode();
240
241     for (; iter != signatureFiles.rend(); ++iter) {
242         LogInfo("Checking signature with id=" << iter->getFileNumber());
243         SignatureData data(widgetPath + iter->getFileName(),
244                            iter->getFileNumber());
245
246         Try {
247             SignatureReader xml;
248             xml.initialize(data, GlobalConfig::GetSignatureXmlSchema());
249             xml.read(data);
250
251             WrtSignatureValidator::AppType appType =
252                 WrtSignatureValidator::WAC20;
253
254             if (m_installContext.widgetConfig.webAppType ==
255                 APP_TYPE_TIZENWEBAPP)
256             {
257                 appType = WrtSignatureValidator::TIZEN;
258             }
259
260             WrtSignatureValidator::Result result;
261
262             WrtSignatureValidator validator(
263                     appType,
264                     !GlobalSettings::
265                     OCSPTestModeEnabled(),
266                     !GlobalSettings::
267                     CrlTestModeEnabled(),
268                     complianceMode);
269
270             result = validator.check(data, widgetPath);
271
272             if (m_contextData.widgetConfig.packagingType
273                 == WrtDB::PKG_TYPE_DIRECTORY_WEB_APP)
274             {
275                 // In directory installation mode, the validation is skipped.
276
277                 result = WrtSignatureValidator::SIGNATURE_VERIFIED;
278             }
279
280             if (result == WrtSignatureValidator::SIGNATURE_REVOKED) {
281                 LogWarning("Certificate is REVOKED");
282                 ThrowMsg(Exceptions::CertificateExpired,
283                          "Certificate is REVOKED");
284             }
285
286             if (result == WrtSignatureValidator::SIGNATURE_INVALID) {
287                 LogWarning("Signature is INVALID");
288                 // TODO change exception name
289                 ThrowMsg(Exceptions::SignatureInvalid,
290                          "Invalid Package");
291             }
292
293             if (data.isAuthorSignature()) {
294                 if (result == WrtSignatureValidator::SIGNATURE_VERIFIED ||
295                     m_contextData.wacSecurity.isDistributorSigned())
296                 {
297                     processAuthorSignature(data);
298                 } else if (result ==
299                            WrtSignatureValidator::SIGNATURE_DISREGARD)
300                 {
301                     continue;
302                 }
303             } else {
304                 // now signature _must_ be verified
305                 processDistributorSignature(data);
306             }
307         } Catch(ParserSchemaException::Base) {
308             LogError("Error occured in ParserSchema.");
309             ReThrowMsg(Exceptions::SignatureInvalid,
310                        "Error occured in ParserSchema.");
311         }
312     }
313
314     if (signatureFiles.empty()) {
315         LogInfo("No signature files has been found.");
316     }
317
318     LogInfo("================ Step: <<Signature>> DONE ================");
319
320     m_contextData.job->UpdateProgress(
321         InstallerContext::INSTALL_DIGSIG_CHECK,
322         "Widget Signature checked");
323 }
324
325 void TaskCertify::createInstallPopup(PopupType type, const std::string &label)
326 {
327     m_contextData.job->Pause();
328     if (m_popup) {
329         destroyPopup();
330     }
331     bool ret = createPopup();
332     if (ret) {
333         loadPopup(type, label);
334         showPopup();
335     }
336 }
337 void TaskCertify::StepDeletePopupWin()
338 {
339     destroyPopup();
340 }
341
342 void TaskCertify::stepWarningPopup()
343 {
344     LogInfo("Step:: <<Warning Popup>>");
345     // SP-2151: If widget is not recognized (OCSP status of any of certificates
346     //          it is signed with is not recognized) WRT must notify user that
347     //          widget cannot be installed as a trusted application, and let the
348     //          user decide whether it should be installed as an untrusted
349     //          application.
350     if (!m_contextData.wacSecurity.isDistributorSigned()) {
351         std::string label = UNTRUSTED_WIDGET +
352             LABEL_NEW_LINE_2 +
353             QUESTION;
354         createInstallPopup(PopupType::WIDGET_UNRECOGNIZED, label);
355     }
356 }
357
358 std::string TaskCertify::createAuthorWidgetInfo() const
359 {
360     std::string authorInfo;
361     if (m_contextData.wacSecurity.isRecognized()) {
362         //authorInfo += _("IDS_IM_WIDGET_RECOGNISED");
363         authorInfo += _("WIDGET RECOGNISED");
364     } else {
365         //authorInfo += _("IDS_IM_WIDGET_UNRECOGNISED");
366         authorInfo += _("WIDGET UNRECOGNISED");
367     }
368
369     authorInfo += LABEL_NEW_LINE_2;
370     ValidationCore::CertificatePtr authorCert =
371         m_contextData.wacSecurity.getAuthorCertificatePtr();
372     if (!!authorCert) {
373         DPL::Optional < DPL::String > organizationName =
374             authorCert->getOrganizationName();
375
376         //authorInfo += _("IDS_IM_WIDGET_AUTHOR_ORGANIZATION_NAME");
377         authorInfo += _("AUTHOR ORGANIZATION NAME");
378         authorInfo += LABEL_NEW_LINE;
379
380         if (!organizationName.IsNull()) {
381             authorInfo += DPL::ToUTF8String(*organizationName);
382         } else {
383             //authorInfo += _("IDS_IM_WIDGET_ORGANIZATION_UNKNOWN");
384             authorInfo += _("WIDGET ORGANIZATION UNKNOWN");
385         }
386
387         authorInfo += LABEL_NEW_LINE_2;
388
389         DPL::Optional < DPL::String > countryName =
390             authorCert->getCountryName();
391
392         //authorInfo += _("IDS_IM_WIDGET_COUNTRY_NAME");
393         authorInfo += _("WIDGET COUNTRY NAME");
394         authorInfo += LABEL_NEW_LINE;
395
396         if (!countryName.IsNull()) {
397             authorInfo += DPL::ToUTF8String(*countryName);
398         } else {
399             //authorInfo += _("IDS_IM_WIDGET_COUNTRY_UNKNOWN");
400             authorInfo += _("WIDGET COUNTRY UNKNOWN");
401         }
402     } else {
403         authorInfo +=
404             //_("IDS_IM_WIDGET_DOES_NOT_CONTAIN_RECOGNIZED_AUTHOR_SIGNATURE");
405             _("Widget does not contain recognized author signature");
406     }
407     return authorInfo;
408 }
409
410 void TaskCertify::stepAuthorInfoPopup()
411 {
412     LogInfo("Step:: <<Author Popup Information>>");
413     std::string label
414         = createAuthorWidgetInfo() + LABEL_NEW_LINE_2 + QUESTION;
415     createInstallPopup(PopupType::WIDGET_AUTHOR_INFO, label);
416 }
417
418 void TaskCertify::stepFinalize()
419 {
420     LogInfo("Step: <<CERTYFYING DONE>>");
421
422     m_contextData.job->UpdateProgress(
423         InstallerContext::INSTALL_CERT_CHECK,
424         "Widget Certification Check Finished");
425 }
426
427 void TaskCertify::stepWarningPopupAnswer()
428 {
429     LogInfo("Step: <<Warning Popup Answer>>");
430     if (false == m_contextData.wacSecurity.isDistributorSigned() &&
431         WRT_POPUP_BUTTON_CANCEL == m_installCancel)
432     {
433         LogWarning("User does not agreed to install unsigned widgets!");
434         m_installCancel = WRT_POPUP_BUTTON;
435         destroyPopup();
436         ThrowMsg(Exceptions::NotAllowed, "Widget not allowed");
437     }
438 }
439
440 void TaskCertify::stepAuthorInfoPopupAnswer()
441 {
442     LogInfo("Step: <<Author Info Popup Answer>>");
443     if (WRT_POPUP_BUTTON_CANCEL == m_installCancel) {
444         LogWarning("User does not agreed to install widget!");
445         m_installCancel = WRT_POPUP_BUTTON;
446         destroyPopup();
447         ThrowMsg(Exceptions::NotAllowed, "Widget not allowed");
448     }
449 }
450
451 bool TaskCertify::isTizenWebApp() const
452 {
453     bool ret = FALSE;
454     if (m_installContext.widgetConfig.webAppType.appType
455         == WrtDB::AppType::APP_TYPE_TIZENWEBAPP)
456     {
457         ret = TRUE;
458     }
459
460     return ret;
461 }
462
463 void TaskCertify::stepVerifyUpdate()
464 {
465     LogInfo("Step: <<Check Update>>");
466     CertificatePtr newCertificate =
467         m_contextData.wacSecurity.getAuthorCertificatePtr();
468     CertificatePtr oldCertificate =
469         getOldAuthorSignerCertificate(m_installContext.widgetConfig.tzAppid);
470
471     if (!!newCertificate && !!oldCertificate) {
472         if (0 != newCertificate->getBase64().compare(oldCertificate->getBase64())) {
473             LogDebug("old widget's author signer certificate : " <<
474                     oldCertificate->getBase64());
475             LogDebug("new widget's author signer certificate : " <<
476                     newCertificate->getBase64());
477             ThrowMsg(Exceptions::NotMatchedCertification,
478                     "Author signer certificates doesn't match \
479                     between old widget and installing widget");
480         }
481     } else {
482         if (!(NULL == newCertificate.Get() && NULL == oldCertificate.Get())) {
483             ThrowMsg(Exceptions::NotMatchedCertification,
484                     "Author signer certificates doesn't match \
485                     between old widget and installing widget");
486         }
487     }
488 }
489 } //namespace WidgetInstall
490 } //namespace Jobs
491