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