Tizen 2.1 base
[framework/web/wrt-commons.git] / modules / vcore / src / vcore / OCSP.h
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  * @author      Tomasz Morawski(t.morawski@samsung.com)
18  * @author      Michal Ciepielski(m.ciepielski@samsung.com)
19  * @author      Piotr Marcinkiewicz(p.marcinkiew@samsung.com)
20  * @version     0.4
21  * @file        OCPS.h
22  * @brief       Routines for certificate validation over OCSP
23  */
24
25 #ifndef WRT_ENGINE_SRC_VALIDATION_CORE_ENGINE_OCSP_H_
26 #define WRT_ENGINE_SRC_VALIDATION_CORE_ENGINE_OCSP_H_
27
28 #include <openssl/pem.h>
29 #include <openssl/ocsp.h>
30 #include <libsoup/soup.h>
31
32 #include <string>
33 #include <vector>
34 #include <list>
35 #include <utility>
36 #include <map>
37
38 #include <dpl/assert.h>
39 #include <dpl/exception.h>
40 #include <dpl/optional_typedefs.h>
41
42 #include <vcore/scoped_gpointer.h>
43
44 #include "OCSPCertMgrUtil.h"
45 #include "CertificateCollection.h"
46 #include "CertificateStorage.h"
47 #include "VerificationStatus.h"
48 #include "SSLContainers.h"
49
50 #include "SoupMessageSendBase.h"
51 #include "SoupMessageSendSync.h"
52 /*
53  * The WRT MUST NOT allow installation of widgets with revoked signatures.
54  *
55  * The WRT MUST NOT allow use of widgets with revoked signatures.
56  *
57  * The WRT MUST support checking for revocation of widget signatures via
58  * OCSP [RFC 2560] at widget installation time, according to the following:
59  *
60  * At widget installation time, the WRT shall make several attempts
61  * (5 attempts at 6 seconds apart recommended) to establish contact with
62  * the OCSP server.
63  *
64  * If connectivity is successful and the application is validated, the
65  * installation process shall continue.
66  *
67  * If connectivity is successful and if the widget signature is
68  * determined to be revoked, the WRT shall issue a suitable error message
69  * and cancel installation.
70  *
71  * If connectivity is successful and revocation status is unknown or if
72  * connectivity is unsuccessful, the user must be notified that the
73  * widget was unable to be installed as trusted - the certification of
74  * the widget signature has not been validated -, and prompt the user to allow
75  * the user to install the widget as an untrusted application, or reject
76  * the installation.
77  *
78  * The WRT MUST support checking for revocation of widget signatures via OCSP
79  * [RFC 2560] at widget runtime.
80  *
81  * The WRT MUST support OCSP access policy.
82  */
83
84 namespace ValidationCore {
85
86 class OCSP
87 //  : public RevocationCheckerBase
88 {
89   public:
90     static const char* DEFAULT_RESPONDER_URI_ENV;
91
92     VerificationStatus checkEndEntity(const CertificateCollection &certList);
93     OCSP();
94
95     enum DigestAlgorithm
96     {
97         SHA1,
98         SHA224,
99         SHA256,
100         SHA384,
101         SHA512
102     };
103     typedef std::map <DigestAlgorithm, const EVP_MD*> DigestAlgorithmMap;
104     /**
105      * Sets digest algorithm for certid in ocsp request
106      */
107     void setDigestAlgorithmForCertId(DigestAlgorithm alg);
108
109     /**
110      * Sets digest algorithm for certid in ocsp request
111      */
112     void setDigestAlgorithmForRequest(DigestAlgorithm alg);
113
114     void setTrustedStore(const CertificateList& certs);
115
116     VerificationStatusSet validateCertificateList(const CertificateList &certs);
117
118     VerificationStatus validateCertificate(CertificatePtr argCert,
119                                            CertificatePtr argIssuer);
120
121     void setDefaultResponder(const char* uri)
122     {
123         Assert(uri);
124         m_strResponderURI = DPL::FromUTF8String(uri);
125     }
126
127     void setUseDefaultResponder(bool value)
128     {
129         m_bUseDefResponder = value;
130     }
131
132     /**
133      * @return time when response will become invalid - for list of
134      * certificates, this is the minimum of all validities; value is
135      * valid only for not-revoked certificates (non error validation result)
136      */
137     time_t getResponseValidity()
138     {
139         return m_responseValidity;
140     }
141
142   private:
143     typedef WRT::ScopedGPointer<SoupSession> ScopedSoupSession;
144     typedef WRT::ScopedGPointer<SoupMessage> ScopedSoupMessage;
145
146     void handleInvalidResponse(int result);
147     void sendHTTPRequest(ScopedSoupSession& session,
148                          ScopedSoupMessage& msg,
149                          const char* host,
150                          const char* port,
151                          const char* path,
152                          char* requestBuffer,
153                          size_t reqestSize);
154     void sendRequest(const std::string& uri,
155                      char* requestBuffer,
156                      size_t requestSize,
157                      char** responseBuffer,
158                      size_t* responseSize);
159
160     class Exception
161     {
162       public:
163         DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
164         DECLARE_EXCEPTION_TYPE(Base, ConnectionError)
165         DECLARE_EXCEPTION_TYPE(Base, CertificateRevoked)
166         DECLARE_EXCEPTION_TYPE(Base, CertificateUnknown)
167         DECLARE_EXCEPTION_TYPE(Base, VerificationError)
168         DECLARE_EXCEPTION_TYPE(Base, RetrieveCertFromStoreError)
169         DECLARE_EXCEPTION_TYPE(Base, VerificationNotSupport)
170     };
171
172     const EVP_MD* m_pCertIdDigestAlg;
173     const EVP_MD* m_pRequestDigestAlg;
174     static DigestAlgorithmMap m_sDigestAlgMap;
175
176     typedef std::pair<char*, size_t> HttpResponseBuffer;
177
178     SoupWrapper::SoupMessageSendBase::RequestStatus sendOcspRequest(
179             OCSP_REQUEST* argRequest,
180             const DPL::OptionalString& argUri);
181
182     //! Validates a single certificate
183     /*!
184      * @param cert The certificate to check
185      * @param issuer A certificate used to sign the certificate to check.
186      */
187
188     struct CreateRequestResult
189     {
190         bool success;
191         OCSP_REQUEST* ocspRequest;
192         OCSP_CERTID* ocspCertId;
193         CreateRequestResult(bool argSuccess = false,
194                             OCSP_REQUEST* argOcspRequest = NULL,
195                             OCSP_CERTID* argOcspCertId = NULL) :
196             success(argSuccess),
197             ocspRequest(argOcspRequest),
198             ocspCertId(argOcspCertId)
199         {
200         }
201     };
202
203     //! Creates a OCSP request
204     /*!
205      * @param request Returns created OCSP_REQUEST
206      * @param id Returns CertId that is used to find proper OCSP result in
207      * the OCSP response (@see checkRevocationStatus for more details).
208      *
209      */
210     CreateRequestResult createRequest(CertificatePtr argCert,
211                                       CertificatePtr argIssuer);
212
213     OCSP_CERTID* addSerial(CertificatePtr argCert,
214                            CertificatePtr argIssuer);
215
216     void validateResponse(OCSP_REQUEST* argRequest,
217                           OCSP_RESPONSE* argResponse,
218                           OCSP_CERTID* argCertId);
219
220     //! Create a X509 store
221     bool verifyResponse(OCSP_BASICRESP* argResponse);
222
223     void  checkRevocationStatus(OCSP_BASICRESP* argBasicResponse,
224                                 OCSP_CERTID* argCertId);
225
226     typedef std::pair<bool, OCSP_RESPONSE*> OcspResponse;
227
228     OcspResponse convertToResponse();
229
230     time_t m_responseValidity;
231     bool m_bUseNonce;
232     bool m_bUseDefResponder;
233     DPL::String m_strResponderURI;
234     bool m_bSignRequest;
235     EVP_PKEY*                       m_pSignKey;
236     CertificatePtr m_pSignCert;
237     SSLSmartContainer <X509_STORE>  m_pTrustedStore;
238     SoupWrapper::SoupMessageSendSync m_soupMessage;
239 };
240 } // ValidationCore
241
242 #endif //ifndef WRT_ENGINE_SRC_VALIDATION_CORE_ENGINE_OCSP_H_