Fix SVACE
[platform/core/security/cert-svc.git] / src / server / src / cert-server-logic.c
1 /**
2  * Copyright (c) 2016 - 2019 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     cert-server-logic.c
18  * @author   Madhan A K (madhan.ak@samsung.com)
19  *           Kyungwook Tak (k.tak@samsung.com)
20  * @version  1.0
21  * @brief    cert-server logic.
22  */
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <fcntl.h>
30 #include <errno.h>
31 #include <stdbool.h>
32 #include <string.h>
33 #include <dirent.h>
34 #include <sys/socket.h>
35
36 #include <ckmc/ckmc-manager.h>
37 #include <ckmc/ckmc-error.h>
38
39 #include <cert-svc/cerror.h>
40 #include <cert-svc/ccert.h>
41 #include <vcore/Client.h>
42
43 #include <cert-server-debug.h>
44 #include <cert-server-logic.h>
45 #include <cert-server-db.h>
46
47 static CertStatus int_to_CertStatus(int intval)
48 {
49         switch (intval) {
50         case 1:
51                 return ENABLED;
52
53         case 0:
54         default:
55                 return DISABLED;
56         }
57 }
58
59 static int CertStatus_to_int(CertStatus status)
60 {
61         switch (status) {
62         case ENABLED:
63                 return 1;
64
65         case DISABLED:
66         default:
67                 return 0;
68         }
69 }
70
71 static const char *storetype_to_string(CertStoreType type)
72 {
73         switch (type) {
74         case VPN_STORE:
75                 return "vpn";
76
77         case EMAIL_STORE:
78                 return "email";
79
80         case WIFI_STORE:
81                 return "wifi";
82
83         case SYSTEM_STORE:
84                 return "ssl";
85
86         default:
87                 return NULL;
88         }
89 }
90
91 static CertStoreType nextStore(CertStoreType type)
92 {
93         switch (type) {
94         case NONE_STORE:
95                 return VPN_STORE;
96
97         case VPN_STORE:
98                 return WIFI_STORE;
99
100         case WIFI_STORE:
101                 return EMAIL_STORE;
102
103         case EMAIL_STORE:
104                 return SYSTEM_STORE;
105
106         case SYSTEM_STORE:
107                 return NONE_STORE;
108
109         default:
110                 return NONE_STORE;
111         }
112 }
113
114 static bool hasStore(CertStoreType types, CertStoreType type)
115 {
116         return (types & type) != 0 ? true : false;
117 }
118
119 char *add_shared_owner_prefix(const char *name)
120 {
121         char *ckm_alias = NULL;
122         int result = asprintf(&ckm_alias, "%s%s%s", ckmc_owner_id_system,
123                                                   ckmc_owner_id_separator, name);
124
125         if (result < 0 || ckm_alias == NULL) {
126                 SLOGE("Failed to allocate memory");
127                 return NULL;
128         }
129
130         return ckm_alias;
131 }
132
133 int ckmc_remove_alias_with_shared_owner_prefix(const char *name)
134 {
135         char *ckm_alias = add_shared_owner_prefix(name);
136
137         if (!ckm_alias) {
138                 SLOGE("Failed to allocate memory");
139                 return CKMC_ERROR_OUT_OF_MEMORY;
140         }
141
142         int result = ckmc_remove_alias(ckm_alias);
143         free(ckm_alias);
144         return result;
145 }
146
147 char *get_complete_path(const char *str1, const char *str2)
148 {
149         char *result = NULL;
150         int as_result;
151
152         if (!str1 || !str2)
153                 return NULL;
154
155         if (str1[strlen(str1) - 1] != '/')
156                 as_result = asprintf(&result, "%s/%s", str1, str2);
157         else
158                 as_result = asprintf(&result, "%s%s", str1, str2);
159
160         if (as_result < 0)
161                 return NULL;
162
163         return result;
164 }
165
166 int add_file_to_system_cert_dir(const char *gname)
167 {
168         int ret = CERTSVC_SUCCESS;
169         /* find certificate which filehash name is gname in root ca certs path. */
170         char *target = get_complete_path(TZ_SYS_CA_CERTS_ORIG, gname);
171         char *link = get_complete_path(TZ_SYS_CA_CERTS, gname);
172
173         if (target == NULL || link == NULL) {
174                 SLOGE("Failed to get complete path.");
175                 ret = CERTSVC_BAD_ALLOC;
176                 goto out;
177         }
178
179         if (symlink(target, link) != 0) {
180                 SLOGE("Failed to make symlink from[%s] to[%s]", target, link);
181                 ret = CERTSVC_FAIL;
182                 goto out;
183         }
184
185 out:
186         free(target);
187         free(link);
188         return ret;
189 }
190
191 int del_file_from_system_cert_dir(const char *gname)
192 {
193         int ret = CERTSVC_SUCCESS;
194         char *link = NULL;
195         link = get_complete_path(TZ_SYS_CA_CERTS, gname);
196
197         if (!link)   {
198                 SLOGE("Failed to construct source file path.");
199                 return CERTSVC_FAIL;
200         }
201
202         if (unlink(link) != 0) {
203                 SLOGE("unlink %s failed. errno : %d", link, errno);
204                 ret = CERTSVC_FAIL;
205                 goto out;
206         }
207
208 out:
209         free(link);
210         return ret;
211 }
212
213 int write_to_ca_cert_crt_file(const char *mode, const char *cert)
214 {
215         int result = CERTSVC_SUCCESS;
216         FILE *fp = NULL;
217
218         if (cert == NULL || strlen(cert) == 0) {
219                 SLOGE("Input buffer is NULL.");
220                 return CERTSVC_WRONG_ARGUMENT;
221         }
222
223         if (!(fp = fopen(TZ_SYS_CA_BUNDLE, mode))) {
224                 SLOGE("Failed to open the file for writing, [%s].", TZ_SYS_CA_BUNDLE);
225                 return CERTSVC_FAIL;
226         }
227
228         /* if mode of writing is to append, then goto end of file */
229         if (strcmp(mode, "ab") == 0) {
230                 if (fseek(fp, 0L, SEEK_END) != 0) {
231                         SLOGE("Fail in fseek.");
232                         result = CERTSVC_FAIL;
233                         goto error;
234                 }
235         }
236
237         size_t cert_len = strlen(cert);
238
239         if (fwrite(cert, sizeof(char), cert_len, fp) != cert_len) {
240                 SLOGE("Fail to write into file.");
241                 result = CERTSVC_FAIL;
242                 goto error;
243         }
244
245         /* adding empty line at the end */
246         fwrite("\n", sizeof(char), 1, fp);
247 error:
248
249         if (fp)
250                 fclose(fp);
251
252         return result;
253 }
254
255 int saveCertificateToStore(const char *gname, const char *cert)
256 {
257         if (!gname || !cert) {
258                 SLOGE("Invalid input parameter passed.");
259                 return CERTSVC_WRONG_ARGUMENT;
260         }
261
262         ckmc_policy_s cert_policy;
263         cert_policy.password = NULL;
264         cert_policy.extractable = true;
265         ckmc_raw_buffer_s cert_data;
266         cert_data.data = (unsigned char *)cert;
267         cert_data.size = strlen(cert);
268         char *ckm_alias = add_shared_owner_prefix(gname);
269
270         if (!ckm_alias) {
271                 SLOGE("Failed to make alias. memory allocation error.");
272                 return CERTSVC_BAD_ALLOC;
273         }
274
275         int result = ckmc_save_data(ckm_alias, cert_data, cert_policy);
276         free(ckm_alias);
277
278         if (result == CKMC_ERROR_DB_ALIAS_EXISTS) {
279                 SLOGI("same alias with gname[%s] alrady exist in ckm. Maybe other store type have it. skip.",
280                           gname);
281                 return CERTSVC_SUCCESS;
282         }
283
284         if (result != CKMC_ERROR_NONE) {
285                 SLOGE("Failed to save trusted data. ckm errcode[%d]", result);
286                 return CERTSVC_FAIL;
287         }
288
289         return CERTSVC_SUCCESS;
290 }
291
292 int saveCertificateToSystemStore(const char *gname)
293 {
294         if (!gname) {
295                 SLOGE("Invalid input parameter passed.");
296                 return CERTSVC_WRONG_ARGUMENT;
297         }
298
299         int result = add_file_to_system_cert_dir(gname);
300
301         if (result != CERTSVC_SUCCESS)
302                 SLOGE("Failed to store the certificate in store.");
303
304         return result;
305 }
306
307 int get_certificate_buffer_from_store(CertStoreType storeType,
308                                                                           const char *gname, char **pcert)
309 {
310         int result = CERTSVC_SUCCESS;
311         int records = 0;
312         char *tempBuffer = NULL;
313         char *query = NULL;
314         sqlite3_stmt *stmt = NULL;
315
316         if (!gname) {
317                 SLOGE("Invalid input parameter passed.");
318                 return CERTSVC_WRONG_ARGUMENT;
319         }
320
321         if (storeType != SYSTEM_STORE)
322                 query = sqlite3_mprintf("select * from %Q where gname=%Q and enabled=%d and is_root_app_enabled=%d",
323                                                                 storetype_to_string(storeType), gname, ENABLED, ENABLED);
324         else
325                 query = sqlite3_mprintf("select certificate from ssl where gname=%Q and enabled=%d and is_root_app_enabled=%d",
326                                                                 gname, ENABLED, ENABLED);
327
328         result = execute_select_query(query, &stmt);
329
330         if (result != CERTSVC_SUCCESS) {
331                 SLOGE("Querying database failed.");
332                 result = CERTSVC_FAIL;
333                 goto error;
334         }
335
336         records = sqlite3_step(stmt);
337
338         if (records != SQLITE_ROW || records == SQLITE_DONE) {
339                 SLOGE("No valid records found for given gname [%s].", gname);
340                 result = CERTSVC_FAIL;
341                 goto error;
342         }
343
344         tempBuffer = (char *)malloc(sizeof(char) * VCORE_MAX_RECV_DATA_SIZE);
345
346         if (!tempBuffer) {
347                 SLOGE("Fail to allocate memory");
348                 result = CERTSVC_FAIL;
349                 goto error;
350         }
351
352         memset(tempBuffer, 0x00, VCORE_MAX_RECV_DATA_SIZE);
353
354         if (storeType == SYSTEM_STORE)
355                 result = getCertificateDetailFromSystemStore(gname, tempBuffer);
356         else
357                 result = getCertificateDetailFromStore(storeType, PEM_CRT, gname, tempBuffer);
358
359         if (result != CERTSVC_SUCCESS) {
360                 SLOGE("Failed to set request data.");
361                 result = CERTSVC_WRONG_ARGUMENT;
362                 goto error;
363         }
364
365         *pcert = tempBuffer;
366 error:
367
368         if (result != CERTSVC_SUCCESS)
369                 free(tempBuffer);
370
371         sqlite3_free(query);
372         sqlite3_finalize(stmt);
373
374         return result;
375 }
376
377 int update_ca_certificate_file(char *cert)
378 {
379         int result = CERTSVC_SUCCESS;
380         int records = 0;
381         int counter = 0;
382         char *gname = NULL;
383         char *query = NULL;
384         const char *text;
385         sqlite3_stmt *stmt = NULL;
386         CertStoreType storeType;
387
388         /*
389          * During install of a root certificate, the root certificate gets appended at
390          * the end to optimise the write operation onto ca-certificate.crt file.
391          */
392         if (cert != NULL && strlen(cert) > 0) {
393                 result = write_to_ca_cert_crt_file("ab", cert);
394
395                 if (result != CERTSVC_SUCCESS) {
396                         SLOGE("Failed to write to file. result[%d]", result);
397                         return result;
398                 }
399
400                 SLOGD("Successfully update bundle file.");
401                 return CERTSVC_SUCCESS;
402         }
403
404         for (storeType = VPN_STORE; storeType != NONE_STORE;
405                         storeType = nextStore(storeType)) {
406                 if (storeType == SYSTEM_STORE)
407                         query = sqlite3_mprintf("select certificate from ssl where enabled=%d and is_root_app_enabled=%d",
408                                                                         ENABLED, ENABLED);
409                 else
410                         query = sqlite3_mprintf("select gname from %Q where is_root_cert=%d and enabled=%d and is_root_app_enabled=%d",
411                                                                         storetype_to_string(storeType), ENABLED, ENABLED, ENABLED);
412
413                 result = execute_select_query(query, &stmt);
414
415                 sqlite3_free(query);
416                 query = NULL;
417
418                 if (result != CERTSVC_SUCCESS) {
419                         SLOGE("Querying database failed.");
420                         goto error_and_exit;
421                 }
422
423                 /* update the ca-certificate.crt file */
424                 while (1) {
425                         records = sqlite3_step(stmt);
426
427                         if (records == SQLITE_DONE) {
428                                 result = CERTSVC_SUCCESS;
429                                 break;
430                         }
431
432                         if (records != SQLITE_ROW) {
433                                 SLOGE("DB query error when select. result[%d].", records);
434                                 result = CERTSVC_FAIL;
435                                 goto error_and_exit;
436                         }
437
438                         cert = NULL;
439                         gname = NULL;
440
441                         if (storeType == SYSTEM_STORE) {
442                                 text = (const char *)sqlite3_column_text(stmt, 0);
443
444                                 if (text)
445                                         cert = strndup(text, strlen(text));
446                         } else {
447                                 text = (const char *)sqlite3_column_text(stmt, 0);
448
449                                 if (text)
450                                         gname = strndup(text, strlen(text));
451
452                                 result = get_certificate_buffer_from_store(storeType, gname, &cert);
453
454                                 if (result != CERTSVC_SUCCESS) {
455                                         SLOGE("Failed to get certificate buffer from key-manager. gname[%s]", gname);
456                                         goto error_and_exit;
457                                 }
458                         }
459
460                         if (cert == NULL) {
461                                 SLOGE("Failed to extract cert buffer to update ca-certificate.");
462                                 result = CERTSVC_FAIL;
463                                 goto error_and_exit;
464                         }
465
466                         if (counter++ == 0)
467                                 result = write_to_ca_cert_crt_file("wb", cert);
468                         else
469                                 result = write_to_ca_cert_crt_file("ab", cert);
470                         free(cert);
471
472                         if (result != CERTSVC_SUCCESS) {
473                                 SLOGE("Failed to write to file.");
474                                 result = CERTSVC_FAIL;
475                                 goto error_and_exit;
476                         }
477                 }
478         }
479
480         SLOGD("Successfully updated ca-certificate.crt file. added cert num[%d]",
481                   counter);
482 error_and_exit:
483
484         sqlite3_finalize(stmt);
485
486         return result;
487 }
488
489 int enable_disable_cert_status(
490         CertStoreType storeType,
491         int is_root_app,
492         const char *gname,
493         CertStatus status)
494 {
495         int result = CERTSVC_SUCCESS;
496         int records = 0;
497         char *cert = NULL;
498         char *query = NULL;
499         const char *text = NULL;
500         sqlite3_stmt *stmt = NULL;
501
502         if (status != DISABLED && status != ENABLED) {
503                 SLOGE("Invalid cert status");
504                 return CERTSVC_INVALID_STATUS;
505         }
506
507         query = sqlite3_mprintf("select * from %Q where gname=%Q",
508                                                         storetype_to_string(storeType), gname);
509
510         if (!query) {
511                 SLOGE("Failed to generate query");
512                 return CERTSVC_BAD_ALLOC;
513         }
514
515         result = execute_select_query(query, &stmt);
516         sqlite3_free(query);
517
518         if (result != CERTSVC_SUCCESS || !stmt) {
519                 SLOGE("Querying database failed.");
520                 return CERTSVC_FAIL;
521         }
522
523         records = sqlite3_step(stmt);
524         sqlite3_finalize(stmt);
525         stmt = NULL;
526
527         if (records != SQLITE_ROW) {
528                 SLOGE("No valid records found.");
529                 return CERTSVC_FAIL;
530         }
531
532         if (status == DISABLED) {
533                 /* check certificate presence in disabled_certs table before inserting */
534                 query = sqlite3_mprintf("select * from disabled_certs where gname=%Q", gname);
535
536                 if (!query) {
537                         SLOGE("Failed to generate query");
538                         return CERTSVC_BAD_ALLOC;
539                 }
540
541                 result = execute_select_query(query, &stmt);
542                 sqlite3_free(query);
543                 query = NULL;
544
545                 if (result != CERTSVC_SUCCESS) {
546                         SLOGE("Querying database failed.");
547                         return CERTSVC_FAIL;
548                 }
549
550                 records = sqlite3_step(stmt);
551                 sqlite3_finalize(stmt);
552                 stmt = NULL;
553
554                 if (records == SQLITE_ROW) {
555                         SLOGE("Selected certificate identifier is already disabled. [%s]", gname);
556                         return CERTSVC_FAIL;
557                 }
558
559                 /* get certificate from keymanager*/
560                 result = get_certificate_buffer_from_store(storeType, gname, &cert);
561
562                 if (result != CERTSVC_SUCCESS) {
563                         SLOGE("Failed to get certificate buffer. result[%d]", result);
564                         return result;
565                 }
566
567                 /* inserting the disabled certificate to disabled_certs table */
568                 query = sqlite3_mprintf("insert into disabled_certs (gname, certificate) values (%Q, %Q)",
569                                                                 gname, cert);
570                 free(cert);
571
572                 if (!query) {
573                         SLOGE("Failed to generate query");
574                         return CERTSVC_BAD_ALLOC;
575                 }
576
577                 result = execute_insert_update_query(query);
578                 sqlite3_free(query);
579
580                 if (result != CERTSVC_SUCCESS) {
581                         SLOGE("Insert to database failed.");
582                         return result;
583                 }
584
585                 if (storeType != SYSTEM_STORE) {
586                         result = ckmc_remove_alias_with_shared_owner_prefix(gname);
587
588                         if (result != CKMC_ERROR_NONE) {
589                                 SLOGE("Failed to delete certificate from key-manager. ckmc_result[%d]", result);
590                                 return CERTSVC_FAIL;
591                         }
592                 } else {
593                         result = del_file_from_system_cert_dir(gname);
594
595                         if (result != CERTSVC_SUCCESS) {
596                                 SLOGE("Error in del_file_from_system_cert_dir. ret[%d]", result);
597                                 return result;
598                         }
599                 }
600         } else { /* moving the certificate to enabled state */
601                 query = sqlite3_mprintf("select certificate from disabled_certs where gname=%Q",
602                                                                 gname);
603
604                 if (!query) {
605                         SLOGE("Failed to generate query");
606                         return CERTSVC_BAD_ALLOC;
607                 }
608
609                 result = execute_select_query(query, &stmt);
610                 sqlite3_free(query);
611
612                 if (result != CERTSVC_SUCCESS) {
613                         SLOGE("Querying database failed.");
614                         return CERTSVC_FAIL;
615                 }
616
617                 records = sqlite3_step(stmt);
618
619                 if (records == SQLITE_ROW) {
620                         text = (const char *)sqlite3_column_text(stmt, 0);
621
622                         if (!text) {
623                                 SLOGE("Invalid column text");
624                                 sqlite3_finalize(stmt);
625                                 return CERTSVC_FAIL;
626                         }
627
628                         cert = strndup(text, strlen(text));
629                         sqlite3_finalize(stmt);
630
631                         if (!cert) {
632                                 SLOGE("Failed to allocate memory");
633                                 return CERTSVC_BAD_ALLOC;
634                         }
635
636                         if (storeType == SYSTEM_STORE)
637                                 result = saveCertificateToSystemStore(gname);
638                         else
639                                 result = saveCertificateToStore(gname, cert);
640
641                         free(cert);
642
643                         if (result != CERTSVC_SUCCESS) {
644                                 SLOGE("Failed to save certificate to key-manager. ret[%d]", result);
645                                 return result;
646                         }
647
648                         query = sqlite3_mprintf("delete from disabled_certs where gname=%Q", gname);
649
650                         if (!query) {
651                                 SLOGE("Failed to generate query");
652                                 return CERTSVC_BAD_ALLOC;
653                         }
654
655                         result = execute_insert_update_query(query);
656                         sqlite3_free(query);
657
658                         if (result != CERTSVC_SUCCESS) {
659                                 SLOGE("Unable to delete certificate entry from database. ret[%d]", result);
660                                 return result;
661                         }
662                 }
663         }
664
665         if (is_root_app == ENABLED)
666                 query = sqlite3_mprintf("update %Q set is_root_app_enabled=%d , enabled=%d where gname=%Q",
667                                                                 storetype_to_string(storeType), CertStatus_to_int(status), status, gname);
668         else
669                 query = sqlite3_mprintf("update %Q set enabled=%d where gname=%Q",
670                                                                 storetype_to_string(storeType), CertStatus_to_int(status), gname);
671
672         if (!query) {
673                 SLOGE("Failed to generate query");
674                 return CERTSVC_BAD_ALLOC;
675         }
676
677         result = execute_insert_update_query(query);
678         sqlite3_free(query);
679
680         if (result != CERTSVC_SUCCESS) {
681                 SLOGE("Update failed. ret[%d]", result);
682                 return result;
683         }
684
685         return result;
686 }
687
688 int setCertificateStatusToStore(
689         CertStoreType storeType,
690         int is_root_app,
691         const char *gname,
692         CertStatus status)
693 {
694         if (!gname) {
695                 SLOGE("Invalid input parameter passed.");
696                 return CERTSVC_WRONG_ARGUMENT;
697         }
698
699         int result = enable_disable_cert_status(storeType, is_root_app, gname, status);
700
701         if (result != CERTSVC_SUCCESS) {
702                 SLOGE("Failed to disable certificate.");
703                 return result;
704         }
705
706         SLOGD("Successfully updated the certificate status from %s to %s.",
707                   (status == DISABLED) ? "ENABLED" : "DISABLED",
708                   (status == DISABLED) ? "DISABLED" : "ENABLED");
709         return CERTSVC_SUCCESS;
710 }
711
712 int getCertificateStatusFromStore(
713         CertStoreType storeType,
714         const char *gname,
715         CertStatus *status)
716 {
717         if (!gname) {
718                 SLOGE("Invalid input parameter passed.");
719                 return CERTSVC_WRONG_ARGUMENT;
720         }
721
722         char *query =
723                 sqlite3_mprintf("select gname, common_name, enabled from %Q where gname=%Q",
724                                                 storetype_to_string(storeType), gname);
725
726         if (!query) {
727                 SLOGE("Failed to generate query");
728                 return CERTSVC_BAD_ALLOC;
729         }
730
731         sqlite3_stmt *stmt = NULL;
732         int result = execute_select_query(query, &stmt);
733         sqlite3_free(query);
734
735         if (result != CERTSVC_SUCCESS || !stmt) {
736                 SLOGE("Querying database failed.");
737                 *status = DISABLED;
738                 return CERTSVC_FAIL;
739         }
740
741         result = sqlite3_step(stmt);
742
743         if (result != SQLITE_ROW || result == SQLITE_DONE) {
744                 SLOGE("No valid records found.");
745                 *status = DISABLED;
746                 sqlite3_finalize(stmt);
747                 return CERTSVC_FAIL;
748         }
749
750         *status = int_to_CertStatus(sqlite3_column_int(stmt, 2));
751         sqlite3_finalize(stmt);
752         return CERTSVC_SUCCESS;
753 }
754
755 int check_alias_exist_in_database(
756         CertStoreType storeTypes,
757         const char *alias,
758         int *punique)
759 {
760         char *query = NULL;
761         sqlite3_stmt *stmt = NULL;
762         int result = CERTSVC_SUCCESS;
763         CertStoreType storeType;
764         bool unique = false;
765
766         if (!alias || !punique) {
767                 SLOGE("Invalid input parameter passed.");
768                 return CERTSVC_WRONG_ARGUMENT;
769         }
770
771         for (storeType = VPN_STORE; storeType < SYSTEM_STORE;
772                         storeType = nextStore(storeType)) {
773                 if (!hasStore(storeTypes, storeType))
774                         continue;
775
776                 query = sqlite3_mprintf("select * from %Q where common_name=%Q",
777                                                                 storetype_to_string(storeType), alias);
778
779                 if (!query) {
780                         SLOGE("Failed to generate query");
781                         return CERTSVC_BAD_ALLOC;
782                 }
783
784                 result = execute_select_query(query, &stmt);
785                 sqlite3_free(query);
786                 query = NULL;
787
788                 if (result != CERTSVC_SUCCESS || !stmt) {
789                         SLOGE("Querying database failed. result[%d]", result);
790                         return CERTSVC_FAIL;
791                 }
792
793                 result = sqlite3_step(stmt);
794                 sqlite3_finalize(stmt);
795                 stmt = NULL;
796
797                 if (result == SQLITE_DONE) {
798                         unique = true;
799                         break;
800                 }
801         }
802
803         *punique = unique ? CERTSVC_TRUE : CERTSVC_FALSE;
804         return CERTSVC_SUCCESS;
805 }
806
807 int installCertificateToStore(
808         CertStoreType storeType,
809         const char *gname,
810         const char *common_name,
811         const char *private_key_gname,
812         const char *associated_gname,
813         const char *dataBlock,
814         CertType certType)
815 {
816         if ((!gname)
817                         || (certType == P12_END_USER && !common_name && !private_key_gname)
818                         || (certType != P12_END_USER && !common_name && !associated_gname)) {
819                 SLOGE("Invalid input parameter passed.");
820                 return CERTSVC_WRONG_ARGUMENT;
821         }
822
823         int result = CERTSVC_SUCCESS;
824
825         if (storeType != SYSTEM_STORE) {
826                 result = saveCertificateToStore(gname, dataBlock);
827
828                 if (result != CERTSVC_SUCCESS) {
829                         SLOGE("FAIL to save certificate to key-manager. result[%d]", result);
830                         return CERTSVC_FAIL;
831                 }
832         }
833
834         if (certType == P12_PKEY) {
835                 SLOGD("Don't save private key in store");
836                 return CERTSVC_SUCCESS;
837         }
838
839         char *query = NULL;
840
841         if (certType == P12_END_USER && private_key_gname) {
842                 query = sqlite3_mprintf("insert into %Q (gname, common_name, private_key_gname, associated_gname, enabled, is_root_app_enabled) "\
843                                                                 "values (%Q, %Q, %Q, %Q, %d, %d)", storetype_to_string(storeType), gname,
844                                                                 common_name, private_key_gname,
845                                                                 gname, ENABLED, ENABLED);
846         } else if (certType == PEM_CRT || certType == P12_TRUSTED) {
847                 query = sqlite3_mprintf("insert into %Q (gname, common_name, is_root_cert, associated_gname, enabled, is_root_app_enabled) values "\
848                                                                 "(%Q, %Q, %d, %Q, %d, %d)", storetype_to_string(storeType), gname, common_name,
849                                                                 ENABLED,
850                                                                 associated_gname, ENABLED, ENABLED);
851         } else if (certType == P12_INTERMEDIATE) {
852                 query = sqlite3_mprintf("insert into %Q (gname, common_name, associated_gname, enabled, is_root_app_enabled) values (%Q, %Q, %Q, %d, %d)",
853                                                                 storetype_to_string(storeType), gname, common_name, associated_gname, ENABLED,
854                                                                 ENABLED);
855         }
856
857         if (!query) {
858                 SLOGE("Failed to generate query");
859                 return CERTSVC_BAD_ALLOC;
860         }
861
862         result = execute_insert_update_query(query);
863         sqlite3_free(query);
864
865         if (result != CERTSVC_SUCCESS) {
866                 SLOGE("Insert to database failed.");
867                 return CERTSVC_FAIL;
868         }
869
870         return CERTSVC_SUCCESS;
871 }
872
873 int checkAliasExistsInStore(CertStoreType storeType, const char *alias,
874                                                         int *punique)
875 {
876         if (!alias) {
877                 SLOGE("Invalid input parameter passed.");
878                 return CERTSVC_WRONG_ARGUMENT;
879         }
880
881         *punique = CERTSVC_FAIL;
882         int result = check_alias_exist_in_database(storeType, alias, punique);
883
884         if (result != CERTSVC_SUCCESS) {
885                 SLOGE("Failed to check_alias_exist_in_database. err[%d]", result);
886                 return CERTSVC_FAIL;
887         }
888
889         if (*punique == CERTSVC_TRUE)
890                 SLOGD("Alias (%s) does not exist in store(%d).", alias, storeType);
891         else
892                 SLOGD("Alias (%s) exist in store(%d).", alias, storeType);
893
894         return CERTSVC_SUCCESS;
895 }
896
897 int getCertificateDetailFromStore(
898         CertStoreType storeType,
899         CertType certType,
900         const char *gname,
901         char *pOutData)
902 {
903         int result = CERTSVC_SUCCESS;
904         int records = 0;
905         char *query = NULL;
906         const char *text = NULL;
907         sqlite3_stmt *stmt = NULL;
908         ckmc_raw_buffer_s *cert_data = NULL;
909
910         if (!gname || !pOutData) {
911                 SLOGE("Invalid input parameter passed.");
912                 return CERTSVC_WRONG_ARGUMENT;
913         }
914
915         /* start constructing query */
916         if (certType == P12_PKEY) {
917                 /* From the given certificate identifier, get the associated_gname for the certificate.
918                  * Then query the database for records matching the associated_gname to get the private key */
919                 query = sqlite3_mprintf("select associated_gname from %Q where gname=%Q",
920                                                                 storetype_to_string(storeType), gname);
921
922                 if (!query) {
923                         SLOGE("Failed to generate query");
924                         return CERTSVC_BAD_ALLOC;
925                 }
926
927                 result = execute_select_query(query, &stmt);
928                 sqlite3_free(query);
929
930                 if (result != CERTSVC_SUCCESS) {
931                         SLOGE("Querying database failed.");
932                         return result;
933                 }
934
935                 records = sqlite3_step(stmt);
936
937                 if (records != SQLITE_ROW) {
938                         SLOGE("No valid records found.");
939                         sqlite3_finalize(stmt);
940                         return CERTSVC_FAIL;
941                 }
942
943                 text = (const char *)sqlite3_column_text(stmt, 0);
944
945                 if (!text) {
946                         SLOGE("No valid column text");
947                         sqlite3_finalize(stmt);
948                         return CERTSVC_FAIL;
949                 }
950
951                 query = sqlite3_mprintf("select private_key_gname from %Q where gname=%Q and enabled=%d and is_root_app_enabled=%d",
952                                                                 storetype_to_string(storeType), text, ENABLED, ENABLED);
953                 sqlite3_finalize(stmt);
954         } else if (storeType != SYSTEM_STORE) {
955                 query = sqlite3_mprintf("select * from %Q where gname=%Q and enabled=%d and is_root_app_enabled=%d",
956                                                                 storetype_to_string(storeType), gname, ENABLED, ENABLED);
957         }
958
959         if (!query) {
960                 SLOGE("Failed to generate query");
961                 return CERTSVC_BAD_ALLOC;
962         }
963
964         result = execute_select_query(query, &stmt);
965         sqlite3_free(query);
966
967         if (result != CERTSVC_SUCCESS) {
968                 SLOGE("Querying database failed.");
969                 return result;
970         }
971
972         records = sqlite3_step(stmt);
973
974         if (records != SQLITE_ROW) {
975                 SLOGE("No valid records found.");
976                 sqlite3_finalize(stmt);
977                 return CERTSVC_FAIL;
978         }
979
980         if (certType == P12_PKEY) {
981                 if (!(text = (const char *)sqlite3_column_text(stmt, 0))) {
982                         SLOGE("No valid column text");
983                         sqlite3_finalize(stmt);
984                         return CERTSVC_FAIL;
985                 }
986
987                 gname = text;
988         }
989
990         char *ckm_alias = add_shared_owner_prefix(gname);
991
992         if (!ckm_alias) {
993                 SLOGE("Failed to make alias. memory allocation error.");
994                 sqlite3_finalize(stmt);
995                 return CERTSVC_BAD_ALLOC;
996         }
997
998         result = ckmc_get_data(ckm_alias, NULL, &cert_data);
999         free(ckm_alias);
1000         sqlite3_finalize(stmt);
1001
1002         if (result != CKMC_ERROR_NONE) {
1003                 SLOGE("Failed to get certificate from key-manager. ckm ret[%d]", result);
1004                 return CERTSVC_FAIL;
1005         }
1006
1007         memcpy(pOutData, cert_data->data, cert_data->size);
1008         pOutData[cert_data->size] = 0;
1009         ckmc_buffer_free(cert_data);
1010         return CERTSVC_SUCCESS;
1011 }
1012
1013 int getCertificateDetailFromSystemStore(const char *gname, char *pOutData)
1014 {
1015         int result = CERTSVC_SUCCESS;
1016         int records = 0;
1017         char *query = NULL;
1018         const char *text = NULL;
1019         sqlite3_stmt *stmt = NULL;
1020
1021         if (!gname) {
1022                 SLOGE("Invalid input parameter passed.");
1023                 return CERTSVC_WRONG_ARGUMENT;
1024         }
1025
1026         query = sqlite3_mprintf("select certificate from ssl where gname=%Q and is_root_app_enabled=%d",
1027                                                         gname, ENABLED, ENABLED);
1028
1029         if (!query) {
1030                 SLOGE("Query is NULL.");
1031                 return CERTSVC_FAIL;
1032         }
1033
1034         result = execute_select_query(query, &stmt);
1035         sqlite3_free(query);
1036
1037         if (result != CERTSVC_SUCCESS) {
1038                 SLOGE("Querying database failed.");
1039                 return result;
1040         }
1041
1042         records = sqlite3_step(stmt);
1043
1044         if (records != SQLITE_ROW) {
1045                 SLOGE("No valid records found for passed gname [%s].", gname);
1046                 sqlite3_finalize(stmt);
1047                 return CERTSVC_FAIL;
1048         }
1049
1050         text = (const char *)sqlite3_column_text(stmt, 0);
1051
1052         if (!text) {
1053                 SLOGE("Fail to sqlite3_column_text");
1054                 sqlite3_finalize(stmt);
1055                 return CERTSVC_FAIL;
1056         }
1057
1058         size_t cert_len = strlen(text);
1059
1060         if (cert_len >= 4096) {
1061                 sqlite3_finalize(stmt);
1062                 SLOGE("certificate is too long");
1063                 return CERTSVC_FAIL;
1064         }
1065
1066         memcpy(pOutData, text, cert_len);
1067         pOutData[cert_len] = '\0';
1068         sqlite3_finalize(stmt);
1069         return CERTSVC_SUCCESS;
1070 }
1071
1072 int deleteCertificateFromStore(CertStoreType storeType, const char *gname)
1073 {
1074         int result = CERTSVC_SUCCESS;
1075         int records = 0;
1076         char *query = NULL;
1077         char *private_key_name = NULL;
1078         sqlite3_stmt *stmt = NULL;
1079         SLOGD("Remove certificate of gname[%s] in store[%d]", gname, storeType);
1080
1081         if (!gname) {
1082                 SLOGE("Invalid input parameter passed.");
1083                 return CERTSVC_WRONG_ARGUMENT;
1084         }
1085
1086         if (storeType == SYSTEM_STORE) {
1087                 SLOGE("Invalid store type passed.");
1088                 return CERTSVC_INVALID_STORE_TYPE;
1089         }
1090
1091         /* start constructing query */
1092         query = sqlite3_mprintf("select private_key_gname from %Q where gname=%Q",
1093                                                         storetype_to_string(storeType), gname);
1094         result = execute_select_query(query, &stmt);
1095
1096         if (result != CERTSVC_SUCCESS) {
1097                 SLOGE("Querying database failed.");
1098                 result = CERTSVC_FAIL;
1099                 goto error;
1100         }
1101
1102         records = sqlite3_step(stmt);
1103
1104         if (records != SQLITE_ROW) {
1105                 SLOGE("No valid records found for passed gname [%s]. result[%d].", gname,
1106                           records);
1107                 result = CERTSVC_FAIL;
1108                 goto error;
1109         }
1110
1111         /* if a cert is having private-key in it, the private key should
1112          * be deleted first from key-manager, then the actual cert */
1113         if (sqlite3_column_text(stmt, 0) != NULL)
1114                 private_key_name = strdup((const char *)sqlite3_column_text(stmt, 0));
1115
1116         sqlite3_free(query);
1117
1118         query = sqlite3_mprintf("delete from disabled_certs where gname=%Q", gname);
1119         result = execute_insert_update_query(query);
1120
1121         if (result != CERTSVC_SUCCESS) {
1122                 SLOGE("Unable to delete certificate entry from database. result[%d]", result);
1123                 goto error;
1124         }
1125
1126         sqlite3_free(query);
1127         query = NULL;
1128
1129         sqlite3_finalize(stmt);
1130         stmt = NULL;
1131
1132         query = sqlite3_mprintf("delete from %Q where gname=%Q",
1133                                                         storetype_to_string(storeType), gname);
1134         result = execute_insert_update_query(query);
1135
1136         if (result != CERTSVC_SUCCESS) {
1137                 SLOGE("Unable to delete certificate entry from database. result[%d]", result);
1138                 goto error;
1139         }
1140
1141         sqlite3_free(query);
1142         query = NULL;
1143
1144         CertStoreType other = ALL_STORE & ~SYSTEM_STORE & ~storeType;
1145         CertStoreType current;
1146         int gname_exist = 0;
1147
1148         for (current = VPN_STORE; current < SYSTEM_STORE;
1149                         current = nextStore(current)) {
1150                 if (!hasStore(other, current))
1151                         continue;
1152
1153                 query = sqlite3_mprintf("select * from %Q where gname=%Q",
1154                                                                 storetype_to_string(current), gname);
1155                 result = execute_select_query(query, &stmt);
1156
1157                 if (result != CERTSVC_SUCCESS) {
1158                         SLOGE("Querying database failed.");
1159                         result = CERTSVC_FAIL;
1160                         goto error;
1161                 }
1162
1163                 records = sqlite3_step(stmt);
1164
1165                 if (records == SQLITE_ROW) {
1166                         SLOGI("Same gname[%s] exist on store[%d].", gname, current);
1167                         gname_exist = 1;
1168                         break;
1169                 }
1170
1171                 sqlite3_free(query);
1172                 sqlite3_finalize(stmt);
1173                 query = NULL;
1174                 stmt = NULL;
1175         }
1176
1177         if (!gname_exist) {
1178                 SLOGD("The gname[%s] which is in store[%d] is the last one. so remove it from ckm either.",
1179                           gname, current);
1180
1181                 if (private_key_name != NULL) {
1182                         result = ckmc_remove_alias_with_shared_owner_prefix(private_key_name);
1183
1184                         if (result != CKMC_ERROR_NONE) {
1185                                 SLOGE("Failed to delete certificate from key-manager. ckmc_result[%d]", result);
1186                                 result = CERTSVC_FAIL;
1187                                 goto error;
1188                         }
1189                 }
1190
1191                 /* removing the actual cert */
1192                 result = ckmc_remove_alias_with_shared_owner_prefix(gname);
1193
1194                 if (result != CKMC_ERROR_NONE) {
1195                         SLOGE("Failed to remove data in ckm with gname[%s]. ckm_result[%d]", gname,
1196                                   result);
1197                         result = CERTSVC_FAIL;
1198                         goto error;
1199                 }
1200         }
1201
1202         SLOGD("Success in deleting the certificate from store.");
1203         result = CERTSVC_SUCCESS;
1204 error:
1205
1206
1207         sqlite3_free(query);
1208         sqlite3_finalize(stmt);
1209
1210         free(private_key_name);
1211         return result;
1212 }
1213
1214 static int makeCertListNode(
1215         CertStoreType storeType,
1216         const char *gname,
1217         const char *title,
1218         int statusInt,
1219         CertSvcStoreCertList **out)
1220 {
1221         CertSvcStoreCertList *node = NULL;
1222         int result = CERTSVC_SUCCESS;
1223         size_t gname_len = 0;
1224         size_t title_len = 0;
1225
1226         if (out == NULL || gname == NULL || title == NULL) {
1227                 SLOGE("Failed to read texts from records");
1228                 return CERTSVC_WRONG_ARGUMENT;
1229         }
1230
1231         node = (CertSvcStoreCertList *)malloc(sizeof(CertSvcStoreCertList));
1232
1233         if (node == NULL) {
1234                 SLOGE("Failed to allocate memory.");
1235                 return CERTSVC_BAD_ALLOC;
1236         }
1237
1238         gname_len = strlen(gname);
1239         title_len = strlen(title);
1240         node->gname = (char *)malloc(sizeof(char) * (gname_len + 1));
1241         node->title = (char *)malloc(sizeof(char) * (title_len + 1));
1242
1243         if (node->title == NULL || node->gname == NULL) {
1244                 SLOGE("Failed to allocate memory");
1245                 result = CERTSVC_BAD_ALLOC;
1246                 goto error;
1247         }
1248
1249         memcpy(node->gname, gname, gname_len);
1250         memcpy(node->title, title, title_len);
1251         node->gname[gname_len] = '\0';
1252         node->title[title_len] = '\0';
1253         node->storeType = storeType;
1254         node->status = int_to_CertStatus(statusInt);
1255         node->next = NULL;
1256         *out = node;
1257         return CERTSVC_SUCCESS;
1258 error:
1259
1260         if (node != NULL) {
1261                 free(node->gname);
1262                 free(node->title);
1263         }
1264
1265         free(node);
1266         return result;
1267 }
1268
1269 int getCertificateListFromStore(
1270         int reqType,
1271         CertStoreType storeTypes,
1272         int is_root_app,
1273         char **certListBuffer,
1274         size_t *bufferLen,
1275         size_t *certCount)
1276 {
1277         int result = CERTSVC_SUCCESS;
1278         CertSvcStoreCertList *rootCertHead = NULL;
1279         CertSvcStoreCertList *tmpNode = NULL;
1280         CertSvcStoreCertList *currentNode = NULL;
1281         sqlite3_stmt *stmt = NULL;
1282         char *query = NULL;
1283         int records = 0;
1284         size_t count = 0;
1285         size_t i = 0;
1286         CertStoreType storeType;
1287
1288         for (storeType = VPN_STORE; storeType != NONE_STORE;
1289                         storeType = nextStore(storeType)) {
1290                 if (!hasStore(storeTypes, storeType))
1291                         continue;
1292
1293                 SLOGD("Processing storetype [%s]", storetype_to_string(storeType));
1294
1295                 if (reqType == CERTSVC_GET_ROOT_CERTIFICATE_LIST) {
1296                         if (storeType == SYSTEM_STORE) {
1297                                 query = sqlite3_mprintf("select gname, common_name, enabled from %Q where enabled=%d "\
1298                                                                                 "and is_root_app_enabled=%d and order by common_name asc", "ssl", ENABLED,
1299                                                                                 ENABLED);
1300                         } else {
1301                                 query = sqlite3_mprintf("select gname, common_name, enabled from %Q where "\
1302                                                                                 "is_root_cert IS NOT NULL and is_root_app_enabled=%d and enabled=%d",
1303                                                                                 storetype_to_string(storeType), ENABLED, ENABLED);
1304                         }
1305                 } else if (reqType == CERTSVC_GET_USER_CERTIFICATE_LIST) {
1306                         if (storeType == SYSTEM_STORE) {
1307                                 SLOGE("Invalid store type passed.");
1308                                 result = CERTSVC_WRONG_ARGUMENT;
1309                                 goto error;
1310                         } else {
1311                                 query = sqlite3_mprintf("select gname, common_name, enabled from %Q where "\
1312                                                                                 "private_key_gname IS NOT NULL and is_root_app_enabled=%d and enabled=%d",
1313                                                                                 storetype_to_string(storeType), ENABLED, ENABLED);
1314                         }
1315                 } else {
1316                         if (is_root_app != ENABLED) {
1317                                 /* Gets only the list of certificates where is_root_app = 1 (which are enabled by the master application) */
1318                                 if (storeType == SYSTEM_STORE) {
1319                                         query = sqlite3_mprintf("select gname, common_name, enabled from %Q where "\
1320                                                                                         "is_root_app_enabled=%d order by common_name asc",
1321                                                                                         storetype_to_string(storeType), ENABLED, ENABLED);
1322                                 } else {
1323                                         query = sqlite3_mprintf("select gname, common_name, enabled from %Q where is_root_app_enabled=%d",
1324                                                                                         storetype_to_string(storeType), ENABLED, ENABLED);
1325                                 }
1326                         } else {
1327                                 /* Gets all the certificates from store without any restrictions */
1328                                 if (storeType == SYSTEM_STORE) {
1329                                         query = sqlite3_mprintf("select gname, common_name, enabled from %Q order by common_name asc",
1330                                                                                         storetype_to_string(storeType), ENABLED);
1331                                 } else {
1332                                         query = sqlite3_mprintf("select gname, common_name, enabled from %Q",
1333                                                                                         storetype_to_string(storeType), ENABLED);
1334                                 }
1335                         }
1336                 }
1337
1338                 result = execute_select_query(query, &stmt);
1339
1340                 if (result != CERTSVC_SUCCESS) {
1341                         SLOGE("Querying database failed.");
1342                         result = CERTSVC_FAIL;
1343                         goto error;
1344                 }
1345
1346                 while ((records = sqlite3_step(stmt)) == SQLITE_ROW) {
1347                         result = makeCertListNode(
1348                                                  storeType,
1349                                                  (const char *)sqlite3_column_text(stmt, 0),
1350                                                  (const char *)sqlite3_column_text(stmt, 1),
1351                                                  (int)sqlite3_column_int(stmt, 2),
1352                                                  &tmpNode);
1353
1354                         if (result != CERTSVC_SUCCESS) {
1355                                 SLOGE("Failed to make new cert list node. result[%d]", result);
1356                                 goto error;
1357                         }
1358
1359                         if (count == 0)
1360                                 rootCertHead = tmpNode;
1361                         else
1362                                 currentNode->next = tmpNode;
1363
1364                         currentNode = tmpNode;
1365                         tmpNode = NULL;
1366                         count++;
1367                 }
1368
1369                 if (records != SQLITE_DONE) {
1370                         SLOGE("Error in getting data from sqlite3 statement. result[%d]", records);
1371                         result = CERTSVC_FAIL;
1372                         goto error;
1373                 }
1374
1375                 sqlite3_free(query);
1376                 query = NULL;
1377
1378                 sqlite3_finalize(stmt);
1379                 stmt = NULL;
1380         }
1381
1382         *certCount = count;
1383         VcoreCertResponseData *respCertData = (VcoreCertResponseData *)malloc(
1384                         count * sizeof(VcoreCertResponseData));
1385
1386         if (!respCertData) {
1387                 SLOGE("Failed to allocate memory");
1388                 result = CERTSVC_BAD_ALLOC;
1389                 goto error;
1390         }
1391
1392         if (count > 0)
1393                 memset(respCertData, 0x00, count * sizeof(VcoreCertResponseData));
1394
1395         VcoreCertResponseData *currRespCertData = NULL;
1396         currentNode = rootCertHead;
1397
1398         for (i = 0; i < count; i++) {
1399                 tmpNode = currentNode->next;
1400                 currRespCertData = respCertData + i;
1401
1402                 if (strlen(currentNode->gname) > sizeof(currRespCertData->gname)
1403                                 || strlen(currentNode->title) > sizeof(currRespCertData->title)) {
1404                         SLOGE("String is too long. [%s], [%s]", currentNode->gname, currentNode->title);
1405                         result = CERTSVC_FAIL;
1406                         *certListBuffer = NULL;
1407                         free(respCertData);
1408                         goto error;
1409                 }
1410
1411                 strncpy(currRespCertData->gname, currentNode->gname,
1412                                 strlen(currentNode->gname));
1413                 strncpy(currRespCertData->title, currentNode->title,
1414                                 strlen(currentNode->title));
1415                 currRespCertData->status = currentNode->status;
1416                 currRespCertData->storeType = currentNode->storeType;
1417                 currentNode = tmpNode;
1418         }
1419
1420         *certListBuffer = (char *) respCertData;
1421         *bufferLen = count * sizeof(VcoreCertResponseData);
1422         SLOGD("Success to create certificate list. cert_count=%d", count);
1423         result = CERTSVC_SUCCESS;
1424 error:
1425
1426         sqlite3_free(query);
1427         sqlite3_finalize(stmt);
1428
1429         if (rootCertHead) {
1430                 currentNode = rootCertHead;
1431
1432                 while (currentNode) {
1433                         tmpNode = currentNode->next;
1434                         free(currentNode->title);
1435                         free(currentNode->gname);
1436                         free(currentNode);
1437                         currentNode = tmpNode;
1438                 }
1439         }
1440
1441         return result;
1442 }
1443
1444 int getCertificateAliasFromStore(CertStoreType storeType, const char *gname,
1445                                                                  char *alias, size_t aliasSize)
1446 {
1447         int result = CERTSVC_SUCCESS;
1448         int records = 0;
1449         sqlite3_stmt *stmt = NULL;
1450         char *query = NULL;
1451         const char *text = NULL;
1452         query = sqlite3_mprintf("select common_name from %Q where gname=%Q",
1453                                                         storetype_to_string(storeType), gname);
1454         result = execute_select_query(query, &stmt);
1455
1456         if (result != CERTSVC_SUCCESS) {
1457                 SLOGE("Querying database failed.");
1458                 result = CERTSVC_FAIL;
1459                 goto error;
1460         }
1461
1462         records = sqlite3_step(stmt);
1463
1464         if (records != SQLITE_ROW || records == SQLITE_DONE) {
1465                 SLOGE("No valid records found for gname passed [%s].", gname);
1466                 result = CERTSVC_FAIL;
1467                 goto error;
1468         }
1469
1470         if (!(text = (const char *)sqlite3_column_text(stmt, 0))) {
1471                 SLOGE("No column text in returned records");
1472                 result = CERTSVC_FAIL;
1473                 goto error;
1474         }
1475
1476         if (strlen(text) >= aliasSize) {
1477                 SLOGE("Unable to get the alias name for the gname passed, common_name too long.");
1478                 result = CERTSVC_FAIL;
1479                 goto error;
1480         }
1481
1482         strncpy(alias, text, aliasSize);
1483
1484         if (strlen(alias) == 0) {
1485                 SLOGE("Unable to get the alias name for the gname passed.");
1486                 result = CERTSVC_FAIL;
1487                 goto error;
1488         }
1489
1490         result = CERTSVC_SUCCESS;
1491         SLOGD("success : getCertificateAliasFromStore");
1492 error:
1493
1494         sqlite3_free(query);
1495         sqlite3_finalize(stmt);
1496
1497         return result;
1498 }
1499
1500 int loadCertificatesFromStore(
1501         CertStoreType storeType,
1502         const char *gname,
1503         char **ppCertBlockBuffer,
1504         size_t *bufferLen,
1505         size_t *certBlockCount)
1506 {
1507         sqlite3_stmt *stmt = NULL;
1508         char **certs = NULL;
1509         size_t gnameSize = 0;
1510         char *columnText = NULL;
1511         /* Get associated_gname from store */
1512         char *query = sqlite3_mprintf("select associated_gname from %Q "
1513                                                                   "where gname=%Q",
1514                                                                   storetype_to_string(storeType),
1515                                                                   gname);
1516         int result = execute_select_query(query, &stmt);
1517
1518         if (result != CERTSVC_SUCCESS) {
1519                 SLOGE("Querying database failed.");
1520                 goto error;
1521         }
1522
1523         int records = sqlite3_step(stmt);
1524
1525         if (records != SQLITE_ROW) {
1526                 SLOGE("No valid records found for gname passed [%s].", gname);
1527                 result = CERTSVC_FAIL;
1528                 goto error;
1529         }
1530
1531         columnText = strdup((const char *)sqlite3_column_text(stmt, 0));
1532
1533         if (!columnText) {
1534                 SLOGE("Failed to get associated_gname.");
1535                 result = CERTSVC_FAIL;
1536                 goto error;
1537         }
1538
1539         sqlite3_free(query);
1540         sqlite3_finalize(stmt);
1541         /* Get gnames from store */
1542         query = sqlite3_mprintf("select gname from %Q "
1543                                                         "where associated_gname=%Q and enabled=%d and "
1544                                                         "is_root_app_enabled=%d",
1545                                                         storetype_to_string(storeType),
1546                                                         columnText,
1547                                                         ENABLED,
1548                                                         ENABLED);
1549         result = execute_select_query(query, &stmt);
1550
1551         if (result != CERTSVC_SUCCESS) {
1552                 SLOGE("Querying database failed.");
1553                 goto error;
1554         }
1555
1556         certs = (char **)malloc(4 * sizeof(char *));
1557
1558         if (!certs) {
1559                 SLOGE("Failed to allocate memory.");
1560                 result = CERTSVC_BAD_ALLOC;
1561                 goto error;
1562         }
1563
1564         memset(certs, 0x00, 4 * sizeof(char *));
1565
1566         while (1) {
1567                 records = sqlite3_step(stmt);
1568
1569                 if (records == SQLITE_DONE)
1570                         break;
1571
1572                 if (records != SQLITE_ROW) {
1573                         SLOGE("Querying database failed.");
1574                         result = CERTSVC_FAIL;
1575                         goto error;
1576                 }
1577
1578                 const char *tmpText = (const char *)sqlite3_column_text(stmt, 0);
1579
1580                 if (!tmpText) {
1581                         SLOGE("Failed to sqlite3_column_text.");
1582                         result = CERTSVC_FAIL;
1583                         goto error;
1584                 }
1585
1586                 if (!((certs)[gnameSize++] = strdup(tmpText))) {
1587                         SLOGE("Failed to allocate memory");
1588                         result = CERTSVC_BAD_ALLOC;
1589                         goto error;
1590                 }
1591         }
1592
1593         if (gnameSize == 0) {
1594                 SLOGE("No valid records found for the gname passed [%s].", gname);
1595                 result = CERTSVC_FAIL;
1596                 goto error;
1597         }
1598
1599         *certBlockCount = gnameSize;
1600         *bufferLen = gnameSize * sizeof(ResponseCertBlock);
1601         ResponseCertBlock *certBlockList = (ResponseCertBlock *)malloc(*bufferLen);
1602
1603         if (!certBlockList) {
1604                 SLOGE("Failed to allocate memory for ResponseCertBlock");
1605                 result = CERTSVC_BAD_ALLOC;
1606                 goto error;
1607         }
1608
1609         memset(certBlockList, 0x00, *bufferLen);
1610         ResponseCertBlock *currentBlock = NULL;
1611         size_t i;
1612
1613         for (i = 0; i < gnameSize; i++) {
1614                 currentBlock = certBlockList + i;
1615
1616                 if (sizeof(currentBlock->dataBlock) < strlen(certs[i])) {
1617                         SLOGE("src is longer than dst. src[%s] dst size[%d]",
1618                                   certs[i],
1619                                   sizeof(currentBlock->dataBlock));
1620                         free(certBlockList);
1621                         result = CERTSVC_FAIL;
1622                         goto error;
1623                 }
1624
1625                 strncpy(currentBlock->dataBlock, certs[i], strlen(certs[i]));
1626                 currentBlock->dataBlockLen = strlen(certs[i]);
1627         }
1628
1629         *ppCertBlockBuffer = (char *)certBlockList;
1630         result = CERTSVC_SUCCESS;
1631         SLOGD("success: loadCertificatesFromStore. CERT_COUNT=%d", gnameSize);
1632 error:
1633
1634         sqlite3_free(query);
1635         sqlite3_finalize(stmt);
1636         free(columnText);
1637
1638         if (certs) {
1639                 for (i = 0; i < gnameSize; i++)
1640                         free(certs[i]);
1641
1642                 free(certs);
1643         }
1644
1645         return result;
1646 }