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