summaryrefslogtreecommitdiff
path: root/src/manager/service/db-crypto.cpp
blob: 8a5b57b473655d48f5587a114f8e5f87e953207c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
/*
 * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
/*
 * @file        db-crypto.cpp
 * @author      Zofia Abramowska (z.abramowska@samsung.com)
 * @version     1.0
 * @brief       Implementation of encrypted db access layer
 */

#include <fstream>
#include <db-crypto.h>
#include <dpl/db/sql_connection.h>
#include <dpl/log/log.h>
#include <ckm/ckm-error.h>

#pragma GCC diagnostic push
#pragma GCC diagnostic warning "-Wdeprecated-declarations"

namespace {
    const CKM::PermissionMask DEFAULT_PERMISSIONS =
                        static_cast<CKM::PermissionMask>(CKM::Permission::READ | CKM::Permission::REMOVE);

    const char *SCRIPTS_PATH = "/usr/share/ckm/scripts/";

    enum DBVersion : int {
        DB_VERSION_1                   = 1,
        DB_VERSION_2                   = 2,
        /* ... since version 3, there is no need to manually
         * recognize database version.
         * Remember only that if doing changes to the database,
         * increment and update DB_VERSION_CURRENT,
         * then provide migration mechanism!
         */
        DB_VERSION_CURRENT             = 4
    };

    const char *SCRIPT_CREATE_SCHEMA                = "create_schema";
    const char *SCRIPT_DROP_ALL_ITEMS               = "drop_all";
    const char *SCRIPT_MIGRATE                      = "migrate_";

    // common substitutions:
    // 100 - idx
    // 101 - name
    // 102 - label
    // 103 - value
    // 104 - permissionLabel
    // 105 - permissionMask
    const char *DB_CMD_SCHEMA_SET =
            "REPLACE INTO SCHEMA_INFO(name, value) "
            "   VALUES(?101, ?103);";

    const char *DB_CMD_SCHEMA_GET =
            "SELECT * FROM SCHEMA_INFO WHERE name=?101;";

    const char *DB_SCHEMA_VERSION_FIELD = "schema_version";


    const char *DB_CMD_NAME_INSERT =
            "INSERT INTO NAMES("
            "   name, label) "
            "   VALUES(?101, ?102);";

    const char *DB_CMD_NAME_COUNT_ROWS =
            "SELECT COUNT(idx) FROM NAMES WHERE name=?101 AND label=?102;";

    const char *DB_CMD_NAME_DELETE =
            "DELETE FROM NAMES WHERE name=?101 AND label=?102;";

    const char *DB_CMD_NAME_DELETE_BY_LABEL =
            "DELETE FROM NAMES WHERE label=?102;";


    const char *DB_CMD_OBJECT_INSERT =
            "INSERT INTO OBJECTS("
            "   exportable, dataType,"
            "   algorithmType, encryptionScheme,"
            "   iv, dataSize, data, tag, idx, backendId) "
            "   VALUES(?001, ?002, ?003, ?004, ?005, "
            "          ?006, ?007, ?008,"
            "          (SELECT idx FROM NAMES WHERE name=?101 and label=?102),"
            "          ?009"
            "         );";

    const char *DB_CMD_OBJECT_SELECT_BY_NAME_AND_LABEL =
            "SELECT * FROM [join_name_object_tables] "
            " WHERE (dataType BETWEEN ?001 AND ?002) "
            " AND name=?101 and label=?102;";


    const char *DB_CMD_KEY_INSERT =
            "INSERT INTO KEYS(label, key) VALUES (?, ?);";
    const char *DB_CMD_KEY_SELECT =
            "SELECT key FROM KEYS WHERE label=?;";
    const char *DB_CMD_KEY_DELETE =
            "DELETE FROM KEYS WHERE label=?";


    const char *DB_CMD_PERMISSION_SET = // SQLite does not support updating views
            "REPLACE INTO PERMISSIONS(permissionLabel, permissionMask, idx) "
            " VALUES (?104, ?105, (SELECT idx FROM NAMES WHERE name=?101 and label=?102));";

    const char *DB_CMD_PERMISSION_SELECT =
            "SELECT permissionMask FROM [join_name_permission_tables] "
            " WHERE permissionLabel=?104 "
            " AND name=?101 and label=?102;";

    const char *DB_CMD_PERMISSION_DELETE = // SQLite does not support updating views
            "DELETE FROM PERMISSIONS WHERE permissionLabel=?104 AND "
            " idx=(SELECT idx FROM NAMES WHERE name=?101 and label=?102);";


    /*
     * GROUP BY is necessary because of the following case:
     * -There are several permissions to L1, N1 (label, name) from other accessors. When listing
     *  objects accessible by L1 the query will produce one result (L1, N1) for each allowed
     *  accessor but GROUP BY will reduce them to one so L1 will have (L1, N1) on its list only once
     */
    const char *DB_CMD_NAME_SELECT_BY_TYPE_AND_PERMISSION =
            "SELECT label, name FROM [join_all_tables] "
            " WHERE dataType>=?001 AND dataType<=?002 "
            " AND permissionLabel=?104 AND permissionMask&?004!=0 GROUP BY idx;";
}

namespace CKM {
namespace DB {
    Crypto::Crypto(const std::string& path, const RawBuffer &rawPass)
    {
        m_connection = NULL;
        m_inUserTransaction = false;
        Try {
            m_connection = new SqlConnection(path, SqlConnection::Flag::Option::CRW);
            m_connection->SetKey(rawPass);
            initDatabase();
            m_connection->ExecCommand("VACUUM;");
        } Catch(SqlConnection::Exception::ConnectionBroken) {
            LogError("Couldn't connect to database: " << path);
            ReThrow(Crypto::Exception::InternalError);
        } Catch(SqlConnection::Exception::InvalidArguments) {
            LogError("Couldn't set the key for database");
            ReThrow(Crypto::Exception::InternalError);
        } Catch(SqlConnection::Exception::SyntaxError) {
            LogError("Couldn't initiate the database");
            ReThrow(Crypto::Exception::InternalError);
        } Catch(SqlConnection::Exception::InternalError) {
            LogError("Couldn't create the database");
            ReThrow(Crypto::Exception::InternalError);
        }
    }

    Crypto::Crypto(Crypto &&other) :
            m_connection(other.m_connection),
            m_inUserTransaction(other.m_inUserTransaction)
    {
        other.m_connection = NULL;
        other.m_inUserTransaction = false;
    }

    Crypto::~Crypto() {
        delete m_connection;
    }

    Crypto& Crypto::operator=(Crypto&& other) {
        if (this == &other)
            return *this;
        delete m_connection;

        m_connection = other.m_connection;
        other.m_connection = NULL;

        m_inUserTransaction = other.m_inUserTransaction;
        other.m_inUserTransaction = false;

        return *this;
    }

    void Crypto::createTable(
            const char* create_cmd,
            const char *table_name)
    {
        Try {
            m_connection->ExecCommand(create_cmd);
        } Catch(SqlConnection::Exception::SyntaxError) {
            LogError("Couldn't create table : " << table_name << "!");
            throw;
        } Catch(SqlConnection::Exception::InternalError) {
            LogError("Sqlite got into infinite busy state");
            throw;
        }
    }

    void Crypto::createView(
            const char* create_cmd)
    {
        Try {
            m_connection->ExecCommand(create_cmd);
        } Catch(SqlConnection::Exception::SyntaxError) {
            LogError("Couldn't create view!");
            throw;
        } Catch(SqlConnection::Exception::InternalError) {
            LogError("Sqlite got into infinite busy state");
            throw;
        }
    }

    bool Crypto::getDBVersion(int & schemaVersion)
    {
        SchemaInfo SchemaInfo(this);
        if(SchemaInfo.getVersionInfo(schemaVersion)) {
            LogDebug("Current DB version: " << schemaVersion);
            return true;
        }
        else
        {
            LogDebug("No DB version known or DB not present");

            // special case: old CKM_TABLE exists
            if(m_connection->CheckTableExist("CKM_TABLE")) {
                schemaVersion = DB_VERSION_1;
                return true;
            }

            // special case: new scheme exists, but no SCHEMA_INFO table present
            else if(m_connection->CheckTableExist("NAME_TABLE")) {
                schemaVersion = DB_VERSION_2;
                return true;
            }
        }
        // not recognized - proceed with an empty DBs
        return false;
    }

    void Crypto::initDatabase()
    {
        // run migration if old database is present
        int schemaVersion;
        if( getDBVersion(schemaVersion)==false ||       // DB empty or corrupted
            schemaVersion > DB_VERSION_CURRENT)         // or too new scheme
        {
            LogDebug("no database or database corrupted, initializing the DB");
            resetDB();
        }
        else
        {
            // migration needed
            LogDebug("DB migration from version " << schemaVersion << " to version " << DB_VERSION_CURRENT << " started.");
            Transaction transaction(this);
            for(int vi=schemaVersion; vi<DB_VERSION_CURRENT; vi++)
            {
                ScriptOptional script = getMigrationScript(vi);
                if(!script)
                {
                    LogError("Error, script to migrate database from version: " << vi <<
                             " to version: " << vi+1 << " not available, resetting the DB");
                    resetDB();
                    break;
                }

                LogInfo("migrating from version " << vi << " to version " << vi+1);
                m_connection->ExecCommand((*script).c_str());
            }
            // update DB version info
            SchemaInfo SchemaInfo(this);
            SchemaInfo.setVersionInfo();
            transaction.commit();
        }
    }

    Crypto::ScriptOptional Crypto::getScript(const std::string &scriptName) const
    {
        std::string scriptPath = SCRIPTS_PATH + scriptName + std::string(".sql");
        std::ifstream is(scriptPath);
        if(is.fail()) {
            LogError("Script " << scriptPath << " not found!");
            return ScriptOptional();
        }

        std::istreambuf_iterator<char> begin(is),end;
        return ScriptOptional(std::string(begin, end));
    }

    Crypto::ScriptOptional Crypto::getMigrationScript(int db_version) const
    {
        std::string scriptPath = std::string(SCRIPT_MIGRATE) + std::to_string(db_version);
        return getScript(scriptPath);
    }

    void Crypto::createDBSchema() {
        Transaction transaction(this);

        ScriptOptional script = getScript(SCRIPT_CREATE_SCHEMA);
        if(!script)
        {
            std::string errmsg = "Can not create the database schema: no initialization script";
            LogError(errmsg);
            ThrowMsg(Exception::InternalError, errmsg);
        }

        m_connection->ExecCommand((*script).c_str());
        SchemaInfo SchemaInfo(this);
        SchemaInfo.setVersionInfo();
        transaction.commit();
    }

    void Crypto::resetDB() {
        Transaction transaction(this);
        ScriptOptional script = getScript(SCRIPT_DROP_ALL_ITEMS);
        if(!script)
        {
            std::string errmsg = "Can not clear the database: no clearing script";
            LogError(errmsg);
            ThrowMsg(Exception::InternalError, errmsg);
        }

        m_connection->ExecCommand((*script).c_str());
        createDBSchema();
        transaction.commit();
    }

    bool Crypto::isNameLabelPresent(const Name &name, const Label &owner) const {
        Try {
            NameTable nameTable(this->m_connection);
            return nameTable.isPresent(name, owner);
        } Catch(SqlConnection::Exception::SyntaxError) {
            LogError("Couldn't prepare insert statement");
        } Catch(SqlConnection::Exception::InternalError) {
            LogError("Couldn't execute insert statement");
        }
        ThrowMsg(Crypto::Exception::InternalError,
                "Couldn't check if name and label pair is present");
    }

    void Crypto::saveRows(const Name &name, const Label &owner, const RowVector &rows)
    {
        Try {
            // transaction is present in the layer above
            NameTable nameTable(this->m_connection);
            ObjectTable objectTable(this->m_connection);
            PermissionTable permissionTable(this->m_connection);
            nameTable.addRow(name, owner);
            for (const auto &i: rows)
                objectTable.addRow(i);
            permissionTable.setPermission(name,
                                          owner,
                                          owner,
                                          static_cast<int>(DEFAULT_PERMISSIONS));
            return;
        } Catch(SqlConnection::Exception::SyntaxError) {
            LogError("Couldn't prepare insert statement");
        } Catch(SqlConnection::Exception::InternalError) {
            LogError("Couldn't execute insert statement: " << _rethrown_exception.GetMessage());
        }
        ThrowMsg(Crypto::Exception::InternalError,
                "Couldn't save Row");
    }

    void Crypto::saveRow(const Row &row) {
        Try {
            // transaction is present in the layer above
            NameTable nameTable(this->m_connection);
            ObjectTable objectTable(this->m_connection);
            PermissionTable permissionTable(this->m_connection);
            nameTable.addRow(row.name, row.ownerLabel);
            objectTable.addRow(row);
            permissionTable.setPermission(row.name,
                                          row.ownerLabel,
                                          row.ownerLabel,
                                          static_cast<int>(DEFAULT_PERMISSIONS));
            return;
        } Catch(SqlConnection::Exception::SyntaxError) {
            LogError("Couldn't prepare insert statement");
        } Catch(SqlConnection::Exception::InternalError) {
            LogError("Couldn't execute insert statement");
        }
        ThrowMsg(Crypto::Exception::InternalError,
                "Couldn't save Row");
    }

    bool Crypto::deleteRow(
            const Name &name,
            const Label &ownerLabel)
    {
        Try {
            // transaction is present in the layer above
            NameTable nameTable(this->m_connection);
            if(nameTable.isPresent(name, ownerLabel))
            {
                nameTable.deleteRow(name, ownerLabel);
                return true;
            }
            return false;
        } Catch (SqlConnection::Exception::SyntaxError) {
            LogError("Couldn't prepare delete statement");
        } Catch (SqlConnection::Exception::InternalError) {
            LogError("Couldn't execute delete statement");
        }
        ThrowMsg(Crypto::Exception::InternalError,
                "Couldn't delete Row for name " << name << " using ownerLabel " << ownerLabel);
    }

    Row Crypto::getRow(
            const SqlConnection::DataCommandUniquePtr &selectCommand) const {
        Row row;
        row.name = selectCommand->GetColumnString(0);
        row.ownerLabel = selectCommand->GetColumnString(1);
        row.exportable = selectCommand->GetColumnInteger(2);
        row.dataType = DataType(selectCommand->GetColumnInteger(3));
        row.algorithmType = static_cast<DBCMAlgType>(selectCommand->GetColumnInteger(4));
        row.encryptionScheme = selectCommand->GetColumnInteger(5);
        row.iv = selectCommand->GetColumnBlob(6);
        row.dataSize = selectCommand->GetColumnInteger(7);
        row.data = selectCommand->GetColumnBlob(8);
        row.tag = selectCommand->GetColumnBlob(9);
        row.backendId = static_cast<CryptoBackend>(selectCommand->GetColumnInteger(11));
        return row;
    }

    PermissionMaskOptional Crypto::getPermissionRow(
        const Name &name,
        const Label &ownerLabel,
        const Label &accessorLabel) const
    {
        Try {
            PermissionTable permissionTable(this->m_connection);
            return permissionTable.getPermissionRow(name, ownerLabel, accessorLabel);
        } Catch (SqlConnection::Exception::InvalidColumn) {
            LogError("Select statement invalid column error");
        } Catch (SqlConnection::Exception::SyntaxError) {
            LogError("Couldn't prepare select statement");
        } Catch (SqlConnection::Exception::InternalError) {
            LogError("Couldn't execute select statement");
        }
        return PermissionMaskOptional();
    }

    Crypto::RowOptional Crypto::getRow(
        const Name &name,
        const Label &ownerLabel,
        DataType type)
    {
        return getRow(name, ownerLabel, type, type);
    }

    Crypto::RowOptional Crypto::getRow(
        const Name &name,
        const Label &ownerLabel,
        DataType typeRangeStart,
        DataType typeRangeStop)
    {
        Try {
            SqlConnection::DataCommandUniquePtr selectCommand =
                    m_connection->PrepareDataCommand(DB_CMD_OBJECT_SELECT_BY_NAME_AND_LABEL);
            selectCommand->BindInteger(1, typeRangeStart);
            selectCommand->BindInteger(2, typeRangeStop);

            // name table reference
            selectCommand->BindString (101, name.c_str());
            selectCommand->BindString (102, ownerLabel.c_str());

            if(selectCommand->Step())
            {
                // extract data
                Row current_row = getRow(selectCommand);

                // all okay, proceed
                return RowOptional(current_row);
            } else {
                return RowOptional();
            }
        } Catch (SqlConnection::Exception::InvalidColumn) {
            LogError("Select statement invalid column error");
        } Catch (SqlConnection::Exception::SyntaxError) {
            LogError("Couldn't prepare select statement");
        } Catch (SqlConnection::Exception::InternalError) {
            LogError("Couldn't execute select statement");
        }
        ThrowMsg(Crypto::Exception::InternalError,
                "Couldn't get row of type <" <<
                static_cast<int>(typeRangeStart) << "," <<
                static_cast<int>(typeRangeStop)  << ">" <<
                " name " << name << " with owner label " << ownerLabel);
    }

    void Crypto::getRows(
        const Name &name,
        const Label &ownerLabel,
        DataType type,
        RowVector &output)
    {
        getRows(name, ownerLabel, type, type, output);
    }

    void Crypto::getRows(
        const Name &name,
        const Label &ownerLabel,
        DataType typeRangeStart,
        DataType typeRangeStop,
        RowVector &output)
    {
        Try {
            SqlConnection::DataCommandUniquePtr selectCommand =
                    m_connection->PrepareDataCommand(DB_CMD_OBJECT_SELECT_BY_NAME_AND_LABEL);
            selectCommand->BindInteger(1, typeRangeStart);
            selectCommand->BindInteger(2, typeRangeStop);

            // name table reference
            selectCommand->BindString (101, name.c_str());
            selectCommand->BindString (102, ownerLabel.c_str());

            while(selectCommand->Step())
            {
                // extract data
                output.push_back(getRow(selectCommand));
            }
            return;
        } Catch (SqlConnection::Exception::InvalidColumn) {
            LogError("Select statement invalid column error");
        } Catch (SqlConnection::Exception::SyntaxError) {
            LogError("Couldn't prepare select statement");
        } Catch (SqlConnection::Exception::InternalError) {
            LogError("Couldn't execute select statement");
        }
        ThrowMsg(Crypto::Exception::InternalError,
                "Couldn't get row of type <" <<
                static_cast<int>(typeRangeStart) << "," <<
                static_cast<int>(typeRangeStop)  << ">" <<
                " name " << name << " with owner label " << ownerLabel);
    }

    void Crypto::listNames(
        const Label &smackLabel,
        LabelNameVector& labelNameVector,
        DataType type)
    {
        listNames(smackLabel, labelNameVector, type, type);
    }

    void Crypto::listNames(
        const Label &smackLabel,
        LabelNameVector& labelNameVector,
        DataType typeRangeStart,
        DataType typeRangeStop)
    {
        Try{
            Transaction transaction(this);
            SqlConnection::DataCommandUniquePtr selectCommand =
                            m_connection->PrepareDataCommand(DB_CMD_NAME_SELECT_BY_TYPE_AND_PERMISSION);
            selectCommand->BindInteger(1, static_cast<int>(typeRangeStart));
            selectCommand->BindInteger(2, static_cast<int>(typeRangeStop));
            selectCommand->BindString(104, smackLabel.c_str());
            selectCommand->BindInteger(4, static_cast<int>(Permission::READ | Permission::REMOVE));

            while(selectCommand->Step()) {
                Label ownerLabel = selectCommand->GetColumnString(0);
                Name name = selectCommand->GetColumnString(1);
                labelNameVector.push_back(std::make_pair(ownerLabel, name));
            }
            return;
        } Catch (SqlConnection::Exception::InvalidColumn) {
            LogError("Select statement invalid column error");
        } Catch (SqlConnection::Exception::SyntaxError) {
            LogError("Couldn't prepare select statement");
        } Catch (SqlConnection::Exception::InternalError) {
            LogError("Couldn't execute select statement");
        }
        ThrowMsg(Crypto::Exception::InternalError,
                "Couldn't list names of type <" <<
                static_cast<int>(typeRangeStart) << "," <<
                static_cast<int>(typeRangeStop)  << ">" <<
                " accessible to client label " << smackLabel);
    }



    void Crypto::saveKey(
            const Label& label,
            const RawBuffer &key)
    {
        Try {
            SqlConnection::DataCommandUniquePtr insertCommand =
                    m_connection->PrepareDataCommand(DB_CMD_KEY_INSERT);
            insertCommand->BindString(1, label.c_str());
            insertCommand->BindBlob(2, key);
            insertCommand->Step();
            return;
        } Catch (SqlConnection::Exception::SyntaxError) {
            LogError("Couldn't prepare insert key statement");
        } Catch (SqlConnection::Exception::InternalError) {
            LogError("Couldn't execute insert statement");
        }
        ThrowMsg(Crypto::Exception::InternalError,
                "Couldn't save key for label " << label);
    }

    Crypto::RawBufferOptional Crypto::getKey(const Label& label)
    {
        Try {
            SqlConnection::DataCommandUniquePtr selectCommand =
                    m_connection->PrepareDataCommand(DB_CMD_KEY_SELECT);
            selectCommand->BindString(1, label.c_str());

            if (selectCommand->Step()) {
                return RawBufferOptional(
                        selectCommand->GetColumnBlob(0));
            } else {
                return RawBufferOptional();
            }

        } Catch (SqlConnection::Exception::InvalidColumn) {
            LogError("Select statement invalid column error");
        } Catch (SqlConnection::Exception::SyntaxError) {
            LogError("Couldn't prepare insert key statement");
        } Catch (SqlConnection::Exception::InternalError) {
            LogError("Couldn't execute insert statement");
        }
        ThrowMsg(Crypto::Exception::InternalError,
                "Couldn't get key for label " << label);
    }

    void Crypto::deleteKey(const Label& label) {
        Try {
            Transaction transaction(this);

            SqlConnection::DataCommandUniquePtr deleteCommand =
                    m_connection->PrepareDataCommand(DB_CMD_KEY_DELETE);
            deleteCommand->BindString(1, label.c_str());
            deleteCommand->Step();

            NameTable nameTable(this->m_connection);
            nameTable.deleteAllRows(label);

            transaction.commit();
            return;
        } Catch (SqlConnection::Exception::SyntaxError) {
            LogError("Couldn't prepare insert key statement");
        } Catch (SqlConnection::Exception::InternalError) {
            LogError("Couldn't execute insert statement");
        }
        ThrowMsg(Crypto::Exception::InternalError,
                "Couldn't delete key for label " << label);
    }

    void Crypto::setPermission(
            const Name &name,
            const Label& ownerLabel,
            const Label& accessorLabel,
            const PermissionMask permissionMask)
    {
        Try {
            PermissionTable permissionTable(this->m_connection);
            permissionTable.setPermission(name, ownerLabel, accessorLabel, permissionMask);
            return;
        } Catch (SqlConnection::Exception::SyntaxError) {
            LogError("Couldn't prepare set statement");
        } Catch (SqlConnection::Exception::InternalError) {
            LogError("Couldn't execute set statement");
        }
        ThrowMsg(Crypto::Exception::InternalError,
                "Couldn't set permissions for name " << name );
    }


    void Crypto::SchemaInfo::setVersionInfo() {
        SqlConnection::DataCommandUniquePtr insertContextCommand =
                m_db->m_connection->PrepareDataCommand(DB_CMD_SCHEMA_SET);
        insertContextCommand->BindString(101, DB_SCHEMA_VERSION_FIELD);
        insertContextCommand->BindString(103, std::to_string(DB_VERSION_CURRENT).c_str());
        insertContextCommand->Step();
    }

    bool Crypto::SchemaInfo::getVersionInfo(int & version) const
    {
        // Try..Catch mandatory here - we don't need to escalate the error
        // if it happens - we just won't return the version, allowing CKM to work
        Try {
            SqlConnection::DataCommandUniquePtr selectCommand =
                    m_db->m_connection->PrepareDataCommand(DB_CMD_SCHEMA_GET);
            selectCommand->BindString(101, DB_SCHEMA_VERSION_FIELD);

            if(selectCommand->Step()) {
                version = static_cast<int>(atoi(selectCommand->GetColumnString(1).c_str()));
                return true;
            }
        } Catch (SqlConnection::Exception::InvalidColumn) {
            LogError("Select statement invalid column error");
        } Catch (SqlConnection::Exception::SyntaxError) {
            LogError("Couldn't prepare select statement");
        } Catch (SqlConnection::Exception::InternalError) {
            LogError("Couldn't execute select statement");
        }
        return false;
    }

    void Crypto::PermissionTable::setPermission(
            const Name &name,
            const Label& ownerLabel,
            const Label& accessorLabel,
            const PermissionMask permissionMask)
    {
        if(permissionMask == Permission::NONE)
        {
            // clear permissions
            SqlConnection::DataCommandUniquePtr deletePermissionCommand =
                m_connection->PrepareDataCommand(DB_CMD_PERMISSION_DELETE);
            deletePermissionCommand->BindString(104, accessorLabel.c_str());
            deletePermissionCommand->BindString(101, name.c_str());
            deletePermissionCommand->BindString(102, ownerLabel.c_str());
            deletePermissionCommand->Step();
        }
        else
        {
            // add new permissions
            SqlConnection::DataCommandUniquePtr setPermissionCommand =
                m_connection->PrepareDataCommand(DB_CMD_PERMISSION_SET);
            setPermissionCommand->BindString(104, accessorLabel.c_str());
            setPermissionCommand->BindInteger(105, static_cast<int>(permissionMask));
            setPermissionCommand->BindString(101, name.c_str());
            setPermissionCommand->BindString(102, ownerLabel.c_str());
            setPermissionCommand->Step();
        }
    }

    PermissionMaskOptional Crypto::PermissionTable::getPermissionRow(
            const Name &name,
            const Label &ownerLabel,
            const Label &accessorLabel) const
    {
        SqlConnection::DataCommandUniquePtr selectCommand =
                m_connection->PrepareDataCommand(DB_CMD_PERMISSION_SELECT);
        selectCommand->BindString(104, accessorLabel.c_str());

        // name table reference
        selectCommand->BindString(101, name.c_str());
        selectCommand->BindString(102, ownerLabel.c_str());

        if(selectCommand->Step())
        {
            // there is entry for the <name, ownerLabel> pair
            return PermissionMaskOptional(PermissionMask(selectCommand->GetColumnInteger(0)));
        }
        return PermissionMaskOptional();
    }

    void Crypto::NameTable::addRow(
            const Name &name,
            const Label &ownerLabel)
    {
        // insert NAMES item
        SqlConnection::DataCommandUniquePtr insertNameCommand =
                m_connection->PrepareDataCommand(DB_CMD_NAME_INSERT);
        insertNameCommand->BindString (101, name.c_str());
        insertNameCommand->BindString (102, ownerLabel.c_str());
        insertNameCommand->Step();
    }

    void Crypto::NameTable::deleteRow(
            const Name &name,
            const Label &ownerLabel)
    {
        SqlConnection::DataCommandUniquePtr deleteCommand =
                m_connection->PrepareDataCommand(DB_CMD_NAME_DELETE);
        deleteCommand->BindString(101, name.c_str());
        deleteCommand->BindString(102, ownerLabel.c_str());

        // Step() result code does not provide information whether
        // anything was removed.
        deleteCommand->Step();
    }

    void Crypto::NameTable::deleteAllRows(const Label &ownerLabel)
    {
        SqlConnection::DataCommandUniquePtr deleteData =
                m_connection->PrepareDataCommand(DB_CMD_NAME_DELETE_BY_LABEL);
        deleteData->BindString(102, ownerLabel.c_str());

        // Step() result code does not provide information whether
        // anything was removed.
        deleteData->Step();
    }

    bool Crypto::NameTable::isPresent(const Name &name, const Label &ownerLabel) const
    {
        SqlConnection::DataCommandUniquePtr checkCmd =
                m_connection->PrepareDataCommand(DB_CMD_NAME_COUNT_ROWS);
        checkCmd->BindString(101, name.c_str());
        checkCmd->BindString(102, ownerLabel.c_str());
        if(checkCmd->Step()) {
            int element_count = checkCmd->GetColumnInteger(0);
            LogDebug("Item name: " << name  << " ownerLabel: " << ownerLabel <<
                     " hit count: " << element_count);
            if(element_count > 0)
                return true;
        }
        return false;
    }

    void Crypto::ObjectTable::addRow(const Row &row)
    {
        SqlConnection::DataCommandUniquePtr insertObjectCommand =
                m_connection->PrepareDataCommand(DB_CMD_OBJECT_INSERT);
        insertObjectCommand->BindInteger(1, row.exportable);
        insertObjectCommand->BindInteger(2, static_cast<int>(row.dataType));
        insertObjectCommand->BindInteger(3, static_cast<int>(row.algorithmType));
        insertObjectCommand->BindInteger(4, row.encryptionScheme);
        insertObjectCommand->BindBlob   (5, row.iv);
        insertObjectCommand->BindInteger(6, row.dataSize);
        insertObjectCommand->BindBlob   (7, row.data);
        insertObjectCommand->BindBlob   (8, row.tag);
        insertObjectCommand->BindInteger(9, static_cast<int>(row.backendId));

        // name table reference
        insertObjectCommand->BindString (101, row.name.c_str());
        insertObjectCommand->BindString (102, row.ownerLabel.c_str());

        insertObjectCommand->Step();
    }
} // namespace DB
} // namespace CKM

#pragma GCC diagnostic pop