132e6a865e6bac9bb7ddf4fec73d4a0826a2f063
[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     std::string user;
174
175     buffer.Deserialize(command);
176     buffer.Deserialize(msgID);
177
178     // This is a workaround solution for locktype=None in Tizen 2.2.1
179     // When locktype is None, lockscreen app doesn't interfere with unlocking process.
180     // Therefor lockscreen app cannot notify unlock events to key-manager when locktype is None.
181     // So, to unlock user data when lock type is None, key-manager always try to unlock user data with null password.
182     // Even if the result is fail, it will be ignored.
183     Password nullPassword("");
184     m_logic->unlockUserKey(cred.clientUid, nullPassword);
185
186     LogDebug("Process storage. Command: " << command);
187
188     switch(static_cast<LogicCommand>(command)) {
189         case LogicCommand::SAVE:
190         {
191             RawBuffer rawData;
192             PolicySerializable policy;
193             buffer.Deserialize(tmpDataType, name, label, rawData, policy);
194             return m_logic->saveData(
195                 cred,
196                 msgID,
197                 name,
198                 label,
199                 rawData,
200                 DataType(tmpDataType),
201                 policy);
202         }
203         case LogicCommand::SAVE_PKCS12:
204         {
205             RawBuffer rawData;
206             PKCS12Serializable pkcs;
207             PolicySerializable keyPolicy, certPolicy;
208             buffer.Deserialize(name, label, pkcs, keyPolicy, certPolicy);
209             return m_logic->savePKCS12(
210                 cred,
211                 msgID,
212                 name,
213                 label,
214                 pkcs,
215                 keyPolicy,
216                 certPolicy);
217         }
218         case LogicCommand::REMOVE:
219         {
220             buffer.Deserialize(name, label);
221             return m_logic->removeData(
222                 cred,
223                 msgID,
224                 name,
225                 label);
226         }
227         case LogicCommand::GET:
228         {
229             Password password;
230             buffer.Deserialize(tmpDataType, name, label, password);
231             return m_logic->getData(
232                 cred,
233                 msgID,
234                 DataType(tmpDataType),
235                 name,
236                 label,
237                 password);
238         }
239         case LogicCommand::GET_PKCS12:
240         {
241             Password passKey;
242             Password passCert;
243             buffer.Deserialize(name,
244                                label,
245                                passKey,
246                                passCert);
247             return m_logic->getPKCS12(
248                 cred,
249                 msgID,
250                 name,
251                 label,
252                 passKey,
253                 passCert);
254         }
255         case LogicCommand::GET_LIST:
256         {
257             buffer.Deserialize(tmpDataType);
258             return m_logic->getDataList(
259                 cred,
260                 msgID,
261                 DataType(tmpDataType));
262         }
263         case LogicCommand::CREATE_KEY_AES:
264         {
265             int size = 0;
266             Name keyName;
267             Label keyLabel;
268             PolicySerializable policyKey;
269             buffer.Deserialize(size,
270                                policyKey,
271                                keyName,
272                                keyLabel);
273             return m_logic->createKeyAES(
274                 cred,
275                 msgID,
276                 size,
277                 keyName,
278                 keyLabel,
279                 policyKey);
280         }
281         case LogicCommand::CREATE_KEY_PAIR:
282         {
283             CryptoAlgorithmSerializable keyGenAlgorithm;
284             Name privateKeyName;
285             Label privateKeyLabel;
286             Name publicKeyName;
287             Label publicKeyLabel;
288             PolicySerializable policyPrivateKey;
289             PolicySerializable policyPublicKey;
290             buffer.Deserialize(keyGenAlgorithm,
291                                policyPrivateKey,
292                                policyPublicKey,
293                                privateKeyName,
294                                privateKeyLabel,
295                                publicKeyName,
296                                publicKeyLabel);
297             return m_logic->createKeyPair(
298                 cred,
299                 msgID,
300                 keyGenAlgorithm,
301                 privateKeyName,
302                 privateKeyLabel,
303                 publicKeyName,
304                 publicKeyLabel,
305                 policyPrivateKey,
306                 policyPublicKey);
307         }
308         case LogicCommand::GET_CHAIN_CERT:
309         {
310             RawBuffer certificate;
311             RawBufferVector untrustedVector;
312             RawBufferVector trustedVector;
313             bool systemCerts = false;
314             buffer.Deserialize(certificate, untrustedVector, trustedVector, systemCerts);
315             return m_logic->getCertificateChain(
316                 cred,
317                 msgID,
318                 certificate,
319                 untrustedVector,
320                 trustedVector,
321                 systemCerts);
322         }
323         case LogicCommand::GET_CHAIN_ALIAS:
324         {
325             RawBuffer certificate;
326             LabelNameVector untrustedVector;
327             LabelNameVector trustedVector;
328             bool systemCerts = false;
329             buffer.Deserialize(certificate, untrustedVector, trustedVector, systemCerts);
330             return m_logic->getCertificateChain(
331                 cred,
332                 msgID,
333                 certificate,
334                 untrustedVector,
335                 trustedVector,
336                 systemCerts);
337         }
338         case LogicCommand::CREATE_SIGNATURE:
339         {
340             Password password;        // password for private_key
341             RawBuffer message;
342             int padding = 0, hash = 0;
343             buffer.Deserialize(name, label, password, message, hash, padding);
344             return m_logic->createSignature(
345                   cred,
346                   msgID,
347                   name,
348                   label,
349                   password,           // password for private_key
350                   message,
351                   static_cast<HashAlgorithm>(hash),
352                   static_cast<RSAPaddingAlgorithm>(padding));
353         }
354         case LogicCommand::VERIFY_SIGNATURE:
355         {
356             Password password;           // password for public_key (optional)
357             RawBuffer message;
358             RawBuffer signature;
359             //HashAlgorithm hash;
360             //RSAPaddingAlgorithm padding;
361             int padding = 0, hash = 0;
362             buffer.Deserialize(name,
363                                label,
364                                password,
365                                message,
366                                signature,
367                                hash,
368                                padding);
369             return m_logic->verifySignature(
370                 cred,
371                 msgID,
372                 name,
373                 label,
374                 password,           // password for public_key (optional)
375                 message,
376                 signature,
377                 static_cast<const HashAlgorithm>(hash),
378                 static_cast<const RSAPaddingAlgorithm>(padding));
379         }
380         case LogicCommand::SET_PERMISSION:
381         {
382             PermissionMask permissionMask = 0;
383             buffer.Deserialize(name, label, accessorLabel, permissionMask);
384             return m_logic->setPermission(
385                 cred,
386                 command,
387                 msgID,
388                 name,
389                 label,
390                 accessorLabel,
391                 permissionMask);
392         }
393         default:
394             Throw(Exception::BrokenProtocol);
395     }
396 }
397
398 void CKMService::ProcessMessage(MsgKeyRequest msg)
399 {
400     Crypto::GKeyShPtr key;
401     int ret = m_logic->getKeyForService(msg.cred,
402                                         msg.name,
403                                         msg.label,
404                                         msg.password,
405                                         key);
406     MsgKeyResponse kResp(msg.id, key, ret);
407     try {
408         if (!m_commMgr->SendMessage(kResp))
409             LogError("No listener found"); // can't do much more
410     } catch (...) {
411         LogError("Uncaught exception in SendMessage. Check listeners.");
412     }
413 }
414
415 void CKMService::CustomHandle(const ReadEvent &event) {
416     LogDebug("Read event");
417     auto &info = m_connectionInfoMap[event.connectionID.counter];
418     info.buffer.Push(event.rawBuffer);
419     while(ProcessOne(event.connectionID, info, true));
420 }
421
422 void CKMService::CustomHandle(const SecurityEvent & /*event*/) {
423     LogError("This should not happend! SecurityEvent was called on CKMService!");
424 }
425
426 } // namespace CKM
427