Add support for binary data to GStore
[platform/core/security/key-manager.git] / src / manager / service / ckm-service.cpp
1 /*
2  *  Copyright (c) 2000 - 2015 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        ckm-service.cpp
18  * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
19  * @version     1.0
20  * @brief       CKM service implementation.
21  */
22
23 #include <protocols.h>
24
25 #include <dpl/serialization.h>
26 #include <dpl/log/log.h>
27
28 #include <ckm-service.h>
29 #include <ckm-logic.h>
30
31 namespace {
32 const CKM::InterfaceID SOCKET_ID_CONTROL = 0;
33 const CKM::InterfaceID SOCKET_ID_STORAGE = 1;
34 } // namespace anonymous
35
36 namespace CKM {
37
38 CKMService::CKMService()
39   : m_logic(new CKMLogic)
40 {}
41
42 CKMService::~CKMService() {
43     delete m_logic;
44 }
45
46 void CKMService::Start() {
47     Create();
48 }
49
50 void CKMService::Stop() {
51     Join();
52 }
53
54 GenericSocketService::ServiceDescriptionVector CKMService::GetServiceDescription()
55 {
56     return ServiceDescriptionVector {
57         {SERVICE_SOCKET_CKM_CONTROL, "http://tizen.org/privilege/keymanager.admin", SOCKET_ID_CONTROL},
58         {SERVICE_SOCKET_CKM_STORAGE, "http://tizen.org/privilege/keymanager", SOCKET_ID_STORAGE}
59     };
60 }
61
62 void CKMService::SetCommManager(CommMgr *manager)
63 {
64     ThreadService::SetCommManager(manager);
65     Register(*manager);
66 }
67
68 // CKMService does not support security check
69 // so 3rd parameter is not used
70 bool CKMService::ProcessOne(
71     const ConnectionID &conn,
72     ConnectionInfo &info,
73     bool /*allowed*/)
74 {
75     LogDebug ("process One");
76     RawBuffer response;
77
78     Try {
79         if (!info.buffer.Ready())
80             return false;
81
82         if (info.interfaceID == SOCKET_ID_CONTROL)
83             response = ProcessControl(info.buffer);
84         else
85             response = ProcessStorage(info.credentials, info.buffer);
86
87         m_serviceManager->Write(conn, response);
88
89         return true;
90     } Catch (MessageBuffer::Exception::Base) {
91         LogError("Broken protocol. Closing socket.");
92     } Catch (Exception::BrokenProtocol) {
93         LogError("Broken protocol. Closing socket.");
94     } catch (const DataType::Exception::Base &e) {
95         LogError("Closing socket. DBDataType::Exception: " << e.DumpToString());
96     } catch (const std::string &e) {
97         LogError("String exception(" << e << "). Closing socket");
98     } catch (const std::exception &e) {
99         LogError("Std exception:: " << e.what());
100     } catch (...) {
101         LogError("Unknown exception. Closing socket.");
102     }
103
104     m_serviceManager->Close(conn);
105     return false;
106 }
107
108 RawBuffer CKMService::ProcessControl(MessageBuffer &buffer) {
109     int command = 0;
110     uid_t user = 0;
111     ControlCommand cc;
112     Password newPass, oldPass;
113     Label smackLabel;
114
115     buffer.Deserialize(command);
116
117     LogDebug("Process control. Command: " << command);
118
119     cc = static_cast<ControlCommand>(command);
120
121     switch(cc) {
122     case ControlCommand::UNLOCK_USER_KEY:
123         buffer.Deserialize(user, newPass);
124         return m_logic->unlockUserKey(user, newPass);
125     case ControlCommand::LOCK_USER_KEY:
126         buffer.Deserialize(user);
127         return m_logic->lockUserKey(user);
128     case ControlCommand::REMOVE_USER_DATA:
129         buffer.Deserialize(user);
130         return m_logic->removeUserData(user);
131     case ControlCommand::CHANGE_USER_PASSWORD:
132         buffer.Deserialize(user, oldPass, newPass);
133         return m_logic->changeUserPassword(user, oldPass, newPass);
134     case ControlCommand::RESET_USER_PASSWORD:
135         buffer.Deserialize(user, newPass);
136         return m_logic->resetUserPassword(user, newPass);
137     case ControlCommand::REMOVE_APP_DATA:
138         buffer.Deserialize(smackLabel);
139         return m_logic->removeApplicationData(smackLabel);
140     case ControlCommand::UPDATE_CC_MODE:
141         return m_logic->updateCCMode();
142     case ControlCommand::SET_PERMISSION:
143     {
144         Name name;
145         Label label;
146         Label accessorLabel;
147         PermissionMask permissionMask = 0;
148
149         buffer.Deserialize(user, name, label, accessorLabel, permissionMask);
150
151         Credentials cred(user, label);
152         return m_logic->setPermission(
153             cred,
154             command,
155             0, // dummy
156             name,
157             label,
158             accessorLabel,
159             permissionMask);
160     }
161     default:
162         Throw(Exception::BrokenProtocol);
163     }
164 }
165
166 RawBuffer CKMService::ProcessStorage(Credentials &cred, MessageBuffer &buffer)
167 {
168     int command = 0;
169     int msgID = 0;
170     int tmpDataType = 0;
171     Name name;
172     Label label, accessorLabel;
173
174     buffer.Deserialize(command);
175     buffer.Deserialize(msgID);
176
177     // This is a workaround solution for locktype=None in Tizen 2.2.1
178     // When locktype is None, lockscreen app doesn't interfere with unlocking process.
179     // Therefor lockscreen app cannot notify unlock events to key-manager when locktype is None.
180     // So, to unlock user data when lock type is None, key-manager always try to unlock user data with null password.
181     // Even if the result is fail, it will be ignored.
182     Password nullPassword("");
183     m_logic->unlockUserKey(cred.clientUid, nullPassword);
184
185     LogDebug("Process storage. Command: " << command);
186
187     switch(static_cast<LogicCommand>(command)) {
188         case LogicCommand::SAVE:
189         {
190             RawBuffer rawData;
191             PolicySerializable policy;
192             buffer.Deserialize(tmpDataType, name, label, rawData, policy);
193             return m_logic->saveData(
194                 cred,
195                 msgID,
196                 name,
197                 label,
198                 rawData,
199                 DataType(tmpDataType),
200                 policy);
201         }
202         case LogicCommand::SAVE_PKCS12:
203         {
204             RawBuffer rawData;
205             PKCS12Serializable pkcs;
206             PolicySerializable keyPolicy, certPolicy;
207             buffer.Deserialize(name, label, pkcs, keyPolicy, certPolicy);
208             return m_logic->savePKCS12(
209                 cred,
210                 msgID,
211                 name,
212                 label,
213                 pkcs,
214                 keyPolicy,
215                 certPolicy);
216         }
217         case LogicCommand::REMOVE:
218         {
219             buffer.Deserialize(name, label);
220             return m_logic->removeData(
221                 cred,
222                 msgID,
223                 name,
224                 label);
225         }
226         case LogicCommand::GET:
227         {
228             Password password;
229             buffer.Deserialize(tmpDataType, name, label, password);
230             return m_logic->getData(
231                 cred,
232                 msgID,
233                 DataType(tmpDataType),
234                 name,
235                 label,
236                 password);
237         }
238         case LogicCommand::GET_PKCS12:
239         {
240             Password passKey;
241             Password passCert;
242             buffer.Deserialize(name,
243                                label,
244                                passKey,
245                                passCert);
246             return m_logic->getPKCS12(
247                 cred,
248                 msgID,
249                 name,
250                 label,
251                 passKey,
252                 passCert);
253         }
254         case LogicCommand::GET_LIST:
255         {
256             buffer.Deserialize(tmpDataType);
257             return m_logic->getDataList(
258                 cred,
259                 msgID,
260                 DataType(tmpDataType));
261         }
262         case LogicCommand::CREATE_KEY_AES:
263         {
264             int size = 0;
265             Name keyName;
266             Label keyLabel;
267             PolicySerializable policyKey;
268             buffer.Deserialize(size,
269                                policyKey,
270                                keyName,
271                                keyLabel);
272             return m_logic->createKeyAES(
273                 cred,
274                 msgID,
275                 size,
276                 keyName,
277                 keyLabel,
278                 policyKey);
279         }
280         case LogicCommand::CREATE_KEY_PAIR:
281         {
282             CryptoAlgorithmSerializable keyGenAlgorithm;
283             Name privateKeyName;
284             Label privateKeyLabel;
285             Name publicKeyName;
286             Label publicKeyLabel;
287             PolicySerializable policyPrivateKey;
288             PolicySerializable policyPublicKey;
289             buffer.Deserialize(keyGenAlgorithm,
290                                policyPrivateKey,
291                                policyPublicKey,
292                                privateKeyName,
293                                privateKeyLabel,
294                                publicKeyName,
295                                publicKeyLabel);
296             return m_logic->createKeyPair(
297                 cred,
298                 msgID,
299                 keyGenAlgorithm,
300                 privateKeyName,
301                 privateKeyLabel,
302                 publicKeyName,
303                 publicKeyLabel,
304                 policyPrivateKey,
305                 policyPublicKey);
306         }
307         case LogicCommand::GET_CHAIN_CERT:
308         {
309             RawBuffer certificate;
310             RawBufferVector untrustedVector;
311             RawBufferVector trustedVector;
312             bool systemCerts = false;
313             buffer.Deserialize(certificate, untrustedVector, trustedVector, systemCerts);
314             return m_logic->getCertificateChain(
315                 cred,
316                 msgID,
317                 certificate,
318                 untrustedVector,
319                 trustedVector,
320                 systemCerts);
321         }
322         case LogicCommand::GET_CHAIN_ALIAS:
323         {
324             RawBuffer certificate;
325             LabelNameVector untrustedVector;
326             LabelNameVector trustedVector;
327             bool systemCerts = false;
328             buffer.Deserialize(certificate, untrustedVector, trustedVector, systemCerts);
329             return m_logic->getCertificateChain(
330                 cred,
331                 msgID,
332                 certificate,
333                 untrustedVector,
334                 trustedVector,
335                 systemCerts);
336         }
337         case LogicCommand::CREATE_SIGNATURE:
338         {
339             Password password;        // password for private_key
340             RawBuffer message;
341             int padding = 0, hash = 0;
342             buffer.Deserialize(name, label, password, message, hash, padding);
343             return m_logic->createSignature(
344                   cred,
345                   msgID,
346                   name,
347                   label,
348                   password,           // password for private_key
349                   message,
350                   static_cast<HashAlgorithm>(hash),
351                   static_cast<RSAPaddingAlgorithm>(padding));
352         }
353         case LogicCommand::VERIFY_SIGNATURE:
354         {
355             Password password;           // password for public_key (optional)
356             RawBuffer message;
357             RawBuffer signature;
358             //HashAlgorithm hash;
359             //RSAPaddingAlgorithm padding;
360             int padding = 0, hash = 0;
361             buffer.Deserialize(name,
362                                label,
363                                password,
364                                message,
365                                signature,
366                                hash,
367                                padding);
368             return m_logic->verifySignature(
369                 cred,
370                 msgID,
371                 name,
372                 label,
373                 password,           // password for public_key (optional)
374                 message,
375                 signature,
376                 static_cast<const HashAlgorithm>(hash),
377                 static_cast<const RSAPaddingAlgorithm>(padding));
378         }
379         case LogicCommand::SET_PERMISSION:
380         {
381             PermissionMask permissionMask = 0;
382             buffer.Deserialize(name, label, accessorLabel, permissionMask);
383             return m_logic->setPermission(
384                 cred,
385                 command,
386                 msgID,
387                 name,
388                 label,
389                 accessorLabel,
390                 permissionMask);
391         }
392         default:
393             Throw(Exception::BrokenProtocol);
394     }
395 }
396
397 void CKMService::ProcessMessage(MsgKeyRequest msg)
398 {
399     Crypto::GObjShPtr key;
400     int ret = m_logic->getKeyForService(msg.cred,
401                                         msg.name,
402                                         msg.label,
403                                         msg.password,
404                                         key);
405     MsgKeyResponse kResp(msg.id, key, ret);
406     try {
407         if (!m_commMgr->SendMessage(kResp))
408             LogError("No listener found"); // can't do much more
409     } catch (...) {
410         LogError("Uncaught exception in SendMessage. Check listeners.");
411     }
412 }
413
414 void CKMService::CustomHandle(const ReadEvent &event) {
415     LogDebug("Read event");
416     auto &info = m_connectionInfoMap[event.connectionID.counter];
417     info.buffer.Push(event.rawBuffer);
418     while(ProcessOne(event.connectionID, info, true));
419 }
420
421 void CKMService::CustomHandle(const SecurityEvent & /*event*/) {
422     LogError("This should not happend! SecurityEvent was called on CKMService!");
423 }
424
425 } // namespace CKM
426