clean cert about wac
[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.existingWidgetInfo.isExist) {
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::InvalidPackage,
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::InvalidPackage,
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::InvalidPackage,
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                 if (result == WrtSignatureValidator::SIGNATURE_DISREGARD) {
305                     continue;
306                 }
307                 // now signature _must_ be verified
308                 processDistributorSignature(data);
309             }
310
311         } Catch(ParserSchemaException::Base) {
312             LogError("Error occured in ParserSchema.");
313             ReThrowMsg(Exceptions::InvalidPackage,
314                        "Error occured in ParserSchema.");
315         }
316     }
317
318     if (signatureFiles.empty()) {
319         LogInfo("No signature files has been found.");
320     }
321
322     LogInfo("================ Step: <<Signature>> DONE ================");
323
324     m_contextData.job->UpdateProgress(
325         InstallerContext::INSTALL_DIGSIG_CHECK,
326         "Widget Signature checked");
327 }
328
329 void TaskCertify::createInstallPopup(PopupType type, const std::string &label)
330 {
331     m_contextData.job->Pause();
332     if (m_popup) {
333         destroyPopup();
334     }
335     bool ret = createPopup();
336     if (ret) {
337         loadPopup(type, label);
338         showPopup();
339     }
340 }
341 void TaskCertify::StepDeletePopupWin()
342 {
343     destroyPopup();
344 }
345
346 void TaskCertify::stepWarningPopup()
347 {
348     LogInfo("Step:: <<Warning Popup>>");
349     // SP-2151: If widget is not recognized (OCSP status of any of certificates
350     //          it is signed with is not recognized) WRT must notify user that
351     //          widget cannot be installed as a trusted application, and let the
352     //          user decide whether it should be installed as an untrusted
353     //          application.
354     if (!m_contextData.wacSecurity.isDistributorSigned()) {
355         std::string label = UNTRUSTED_WIDGET +
356             LABEL_NEW_LINE_2 +
357             QUESTION;
358         createInstallPopup(PopupType::WIDGET_UNRECOGNIZED, label);
359     }
360 }
361
362 std::string TaskCertify::createAuthorWidgetInfo() const
363 {
364     std::string authorInfo;
365     if (m_contextData.wacSecurity.isRecognized()) {
366         //authorInfo += _("IDS_IM_WIDGET_RECOGNISED");
367         authorInfo += _("WIDGET RECOGNISED");
368     } else {
369         //authorInfo += _("IDS_IM_WIDGET_UNRECOGNISED");
370         authorInfo += _("WIDGET UNRECOGNISED");
371     }
372
373     authorInfo += LABEL_NEW_LINE_2;
374     ValidationCore::CertificatePtr authorCert =
375         m_contextData.wacSecurity.getAuthorCertificatePtr();
376     if (!!authorCert) {
377         DPL::Optional < DPL::String > organizationName =
378             authorCert->getOrganizationName();
379
380         //authorInfo += _("IDS_IM_WIDGET_AUTHOR_ORGANIZATION_NAME");
381         authorInfo += _("AUTHOR ORGANIZATION NAME");
382         authorInfo += LABEL_NEW_LINE;
383
384         if (!organizationName.IsNull()) {
385             authorInfo += DPL::ToUTF8String(*organizationName);
386         } else {
387             //authorInfo += _("IDS_IM_WIDGET_ORGANIZATION_UNKNOWN");
388             authorInfo += _("WIDGET ORGANIZATION UNKNOWN");
389         }
390
391         authorInfo += LABEL_NEW_LINE_2;
392
393         DPL::Optional < DPL::String > countryName =
394             authorCert->getCountryName();
395
396         //authorInfo += _("IDS_IM_WIDGET_COUNTRY_NAME");
397         authorInfo += _("WIDGET COUNTRY NAME");
398         authorInfo += LABEL_NEW_LINE;
399
400         if (!countryName.IsNull()) {
401             authorInfo += DPL::ToUTF8String(*countryName);
402         } else {
403             //authorInfo += _("IDS_IM_WIDGET_COUNTRY_UNKNOWN");
404             authorInfo += _("WIDGET COUNTRY UNKNOWN");
405         }
406     } else {
407         authorInfo +=
408             //_("IDS_IM_WIDGET_DOES_NOT_CONTAIN_RECOGNIZED_AUTHOR_SIGNATURE");
409             _("Widget does not contain recognized author signature");
410     }
411     return authorInfo;
412 }
413
414 void TaskCertify::stepAuthorInfoPopup()
415 {
416     LogInfo("Step:: <<Author Popup Information>>");
417     std::string label
418         = createAuthorWidgetInfo() + LABEL_NEW_LINE_2 + QUESTION;
419     createInstallPopup(PopupType::WIDGET_AUTHOR_INFO, label);
420 }
421
422 void TaskCertify::stepFinalize()
423 {
424     LogInfo("Step: <<CERTYFYING DONE>>");
425
426     m_contextData.job->UpdateProgress(
427         InstallerContext::INSTALL_CERT_CHECK,
428         "Widget Certification Check Finished");
429 }
430
431 void TaskCertify::stepWarningPopupAnswer()
432 {
433     LogInfo("Step: <<Warning Popup Answer>>");
434     if (false == m_contextData.wacSecurity.isDistributorSigned() &&
435         WRT_POPUP_BUTTON_CANCEL == m_installCancel)
436     {
437         LogWarning("User does not agreed to install unsigned widgets!");
438         m_installCancel = WRT_POPUP_BUTTON;
439         destroyPopup();
440         ThrowMsg(Exceptions::NotAllowed, "Widget not allowed");
441     }
442 }
443
444 void TaskCertify::stepAuthorInfoPopupAnswer()
445 {
446     LogInfo("Step: <<Author Info Popup Answer>>");
447     if (WRT_POPUP_BUTTON_CANCEL == m_installCancel) {
448         LogWarning("User does not agreed to install widget!");
449         m_installCancel = WRT_POPUP_BUTTON;
450         destroyPopup();
451         ThrowMsg(Exceptions::NotAllowed, "Widget not allowed");
452     }
453 }
454
455 bool TaskCertify::isTizenWebApp() const
456 {
457     bool ret = FALSE;
458     if (m_installContext.widgetConfig.webAppType.appType
459         == WrtDB::AppType::APP_TYPE_TIZENWEBAPP)
460     {
461         ret = TRUE;
462     }
463
464     return ret;
465 }
466
467 void TaskCertify::stepVerifyUpdate()
468 {
469     LogInfo("Step: <<Check Update>>");
470     CertificatePtr newCertificate =
471         m_contextData.wacSecurity.getAuthorCertificatePtr();
472     CertificatePtr oldCertificate =
473         getOldAuthorSignerCertificate(m_installContext.widgetConfig.tzAppid);
474
475     if (!!newCertificate && !!oldCertificate) {
476         if (0 != newCertificate->getBase64().compare(oldCertificate->getBase64())) {
477             LogDebug("old widget's author signer certificate : " <<
478                     oldCertificate->getBase64());
479             LogDebug("new widget's author signer certificate : " <<
480                     newCertificate->getBase64());
481             ThrowMsg(Exceptions::InvalidPackage,
482                     "Author signer certificates doesn't match \
483                     between old widget and installing widget");
484         }
485     } else {
486         if (!(NULL == newCertificate.Get() && NULL == oldCertificate.Get())) {
487             ThrowMsg(Exceptions::InvalidPackage,
488                     "Author signer certificates doesn't match \
489                     between old widget and installing widget");
490         }
491     }
492 }
493 } //namespace WidgetInstall
494 } //namespace Jobs
495