Coder Social home page Coder Social logo

go-sqlcipher's People

Contributors

frankbraun avatar klingtnet avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

go-sqlcipher's Issues

Question: how to do cross compile?

I've tried:

env GOOS=linux GOARCH=amd64 go build 

but it shows:

go build github.com/mutecomm/go-sqlcipher: no buildable Go source files in /Users/asd/MEGA/go/src/github.com/mutecomm/go-sqlcipher

OS: Mac OSX latest
Arch: amd64

but it works fine if not using mutecomm/go-sqlcipher

"warning: 'OSAtomicCompareAndSwapPtrBarrier' is deprecated"

Installing github.com/gobuffalo/buffalo/buffalo and I got this warning.

# github.com/mutecomm/go-sqlcipher
../../go/src/github.com/mutecomm/go-sqlcipher/sqlite3.c:20897:17: warning: 'OSAtomicCompareAndSwapPtrBarrier' is deprecated: first deprecated in macOS 10.12 - Use atomic_compare_exchange_strong() from <stdatomic.h> instead [-Wdeprecated-declarations]
/usr/include/libkern/OSAtomicDeprecated.h:547:6: note: 'OSAtomicCompareAndSwapPtrBarrier' has been explicitly marked deprecated here

Upgrade SQLCipher

Hi, @frankbraun , thanks for your awesome library!

A newer version of SQLite and SQLCipher has been released. Could you upgrade it to latest version?

multiple definition error

I'm leveraging golang-migrate to do database schema init & update.
Aligned with go-sqlcipher, it always pops up the following error:

# command-line-arguments c:\go\pkg\tool\windows_amd64\link.exe: running gcc failed: exit status 1 C:/TDM-GCC-64/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\ADMINI~1\AppData\Local\Temp\go-link-302618435\000053.o: in function sqlite3_status64':
C:\Users\Administrator\go\pkg\mod\github.com\mattn\[email protected]/sqlite3-binding.c:20370: multiple definition of sqlite3_status64'; C:\Users\ADMINI~1\AppData\Local\Temp\go-link-302618435\000033.o:C:\Users\Administrator\go\pkg\mod\github.com\mutecomm\go-sqlcipher\[email protected]/sqlite3.c:26352: first defined here C:/TDM-GCC-64/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\ADMINI~1\AppData\Local\Temp\go-link-302618435\000053.o: in function sqlite3_status':
C:\Users\Administrator\go\pkg\mod\github.com\mattn\[email protected]/sqlite3-binding.c:20390: multiple definition of sqlite3_status'; C:\Users\ADMINI~1\AppData\Local\Temp\go-link-302618435\000033.o:C:\Users\Administrator\go\pkg\mod\github.com\mutecomm\go-sqlcipher\[email protected]/sqlite3.c:26372: first defined here C...

Concurrency

Hi, thanks for this nice module, I had trouble using other sqlite encryption modules, this simply works.

One question: Is the package safe to be used by multiple goroutines? i. e.: I use the sqlite file as the database for a small webservice that could potentially handle many requests at once. Therefore I have to assume that database writes may happen concurrently.

Thanks in advance

Unable to open encrypted database file with sqlcipher CLI

I am unable to open an encrypted database file that was created using this library with sqlcipher's CLI.

This is my example Go program that creates a database and inserts a record in a table:

package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"os"
	"time"

	_ "github.com/mutecomm/go-sqlcipher/v4"
)

func wrapErr(err, deferErr error) error {
	if err == nil {
		return deferErr
	}
	if deferErr == nil {
		return err
	}
	return fmt.Errorf("%s: %w", err.Error(), deferErr)
}

func run(ctx context.Context) (err error) {
	if len(os.Args) != 2 {
		err = fmt.Errorf("Usage: %s <password>", os.Args[0])
		return
	}
	password := os.Args[1]
	// https://www.zetetic.net/sqlcipher/sqlcipher-api/#PRAGMA_key
	urn := fmt.Sprintf("file:%s?_pragma_key='%s'&_pragma_cipher_page_size=4096", "example.sqlite3", password)
	db, err := sql.Open("sqlite3", urn)
	if err != nil {
		return
	}
	defer func() {
		err = wrapErr(err, db.Close())
	}()
	_, err = db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS example_table (id INTEGER PRIMARY KEY, foo TEXT NOT NULL)`)
	if err != nil {
		return
	}
	res, err := db.ExecContext(ctx, `INSERT INTO example_table (foo) VALUES (?)`, fmt.Sprintf("some record inserted at %s", time.Now()))
	if err != nil {
		return
	}
	id, err := res.LastInsertId()
	if err != nil {
		return
	}
	log.Println("inserted record with ID:", id)
	return
}

func main() {
	err := run(context.TODO())
	if err != nil {
		log.Fatal(err)
	}
}

And here's how to reproduce the issue:

$ go version
go version go1.15 linux/amd64
$ go run main.go thisismypassword
2020/08/21 17:19:35 inserted record with ID: 1
$ sqlcipher -version
3.31.0 2020-01-22 18:38:59 f6affdd41608946fcfcea914ece149038a8b25a62bbe719ed2561c649b86alt1 (SQLCipher 4.4.0 community)
$ sqlcipher 
> PRAGMA key='thisismypassword';
> PRAGMA cipher_page_size=4096;
> .open 'example.sqlite3';
> SELECT * FROM example_table;
Error: file is not a database

v4.4.2 pragma support only key and cipher_page_size ?

I hpoe support multy pragam just like add code bellow:

pragmaMap := map[string]string{}
pragmaKey := ""
pragmaCipherPageSize := -1

pos := strings.IndexRune(dsn, '?')
if pos >= 1 {
        params, err := url.ParseQuery(dsn[pos+1:])
        if err != nil {
	        return nil, err
        }
        
        // support multi pragma
        for key, strArr := range params {
	        if strings.Contains(key, "_pragma_") {
		        pragmaMap[key[8:]] = strArr[0]
	        }
        }
        .....
}

// _pragma_key
if pragmaKey != "" {
        query := fmt.Sprintf("PRAGMA key = \"%s\";", pragmaKey)
        if err := exec(query); err != nil {
	        C.sqlite3_close_v2(db)
	        return nil, err
        }
}

// _pragma_cipher_page_size
if pragmaCipherPageSize != -1 {
        query := fmt.Sprintf("PRAGMA cipher_page_size = %d;",
	        pragmaCipherPageSize)
        if err := exec(query); err != nil {
	        C.sqlite3_close_v2(db)
	        return nil, err
        }
}

// support multi pragma
for key, val := range pragmaMap {
		if val != "" && key != "key" && key != "cipher_page_size" {
			query := fmt.Sprintf("PRAGMA %s = %s;", key, val)
			if err := exec(query); err != nil {
				C.sqlite3_close_v2(db)
				return nil, err
			}
		}
	}

build error on windows with mingw

go get github.com/mutecomm/go-sqlcipher
report many errors about pthread, you can just modify sqlite3_windows.go

cgo LDFLAGS: -lmingwex -lmingw32 add -lpthread at this line

such as:
crypt_cipher_is_valid.c:25: undefined reference to _imp__pthread_mutex_lock' crypt_cipher_is_valid.c:30: undefined reference to_imp__pthread_mutex_unlock'
crypt_cipher_is_valid.c:27: undefined reference to _imp__pthread_mutex_unlock' crypt_find_cipher.o: In functionfind_cipher':
crypt_find_cipher.c:27: undefined reference to _imp__pthread_mutex_lock' crypt_find_cipher.c:30: undefined reference to_imp__pthread_mutex_unlock'
crypt_find_cipher.c:34: undefined reference to _imp__pthread_mutex_unlock' crypt_find_hash.o: In functionfind_hash':
crypt_find_hash.c:27: undefined reference to _imp__pthread_mutex_lock' crypt_find_hash.c:30: undefined reference to_imp__pthread_mutex_unlock'
crypt_find_hash.c:34: undefined reference to _imp__pthread_mutex_unlock' crypt_hash_is_valid.o: In functionhash_is_valid':
crypt_hash_is_valid.c:25: undefined reference to _imp__pthread_mutex_lock' crypt_hash_is_valid.c:30: undefined reference to_imp__pthread_mutex_unlock'
crypt_hash_is_valid.c:27: undefined reference to _imp__pthread_mutex_unlock' crypt_register_cipher.o: In functionregister_cipher':
crypt_register_cipher.c:30: undefined reference to _imp__pthread_mutex_lock' crypt_register_cipher.c:42: undefined reference to_imp__pthread_mutex_unlock'
crypt_register_cipher.c:48: undefined reference to _imp__pthread_mutex_unlock' crypt_register_hash.o: In functionregister_hash':
crypt_register_hash.c:30: undefined reference to _imp__pthread_mutex_lock' crypt_register_hash.c:42: undefined reference to_imp__pthread_mutex_unlock'
crypt_register_hash.c:48: undefined reference to _imp__pthread_mutex_unlock' crypt_register_prng.o: In functionregister_prng':
crypt_register_prng.c:30: undefined reference to `_imp__pthread_mutex_lock'

Update sqlite version to 3.39.2 to fix vulnerability CVE-2022-35737

Hi @frankbraun @klingtnet @nkbai @JonathanLogan

go-sqlite3 affected by vulnerability CVE-2022-35737. Can we please update sqlite3 code to latest 3.39.2?

Go sqlite3 driver: https://github.com/mattn/go-sqlite3
Seems above package code is we are using here. They updated the sqlite3 code to latest to fix the vulnerability CVE-2022-35737.
Below is the commit details they did:
mattn/go-sqlite3@d8e192b

Please update our sqlite source code also to latest.

Thanks,
Durgababu

File is not a database on query

Hi,

I am trying to write a commandline client for Enpass 6.x password vaults.
These are stored on regular sqlite databases as attached. enpassvault.zip

However, every query will return file is not a database while the Python version seems to work fine.
Any idea?

https://github.com/hazcod/enpass-cli-test

% go run main.go 
2020/12/07 09:55:14 printing tables
2020/12/07 09:55:15 could not retrieve crypto parameters: could not query crypto parameters: file is not a database
exit status 1

Can not open encrypted db file generated by C++

I compile sqlcipher in Windows and generated an encrypted db file like this:

#include <iostream>
#include <string.h>
#include "sqlite3.h"

using namespace std;


static int callback(void* notUsed, int argc, char** argv, char** azColName)
{
    for (int i = 0; i < argc; i++)
        cout << azColName[i] << ":" << (argv[i] ? argv[i] : "NULL") << "\t";
    cout << endl;
    return 0;
}

void dbTest()
{
#pragma region 打开或创建数据库

    /*打开或创建的数据库实例句柄*/
    sqlite3* db = NULL;

    /*数据库文件的路径及文件名*/
    const char* path = "./sqlcipher.db";
    /*根据文件路径打开数据库连接。如果数据库不存在,则创建。数据库文件的路径必须以C字符串传入*/
    int result = sqlite3_open_v2(path, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_SHAREDCACHE, NULL);

    if (result == SQLITE_OK)
        cout << "打开或创建数据库成功" << endl;
    else
        cout << "打开或创建数据库失败" << endl;

    sqlite3_close(db);

#pragma endregion

#pragma region 指定数据库密码

    const char* pwd = "abcdefg";
    result = sqlite3_open_v2(path, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_CREATE, NULL);

    if (result == SQLITE_OK)
        cout << "打开数据库成功" << endl;
    else
        cout << "打开数据库失败" << endl;

    result = sqlite3_key(db, pwd, strnlen(pwd, 1000));
    cout << "指定数据库密码是否成功:" << result << endl;

    char* errmsg;
    //sqlite3_exec(db, "PRAGMA key = \"'abcdefg'\";", NULL, NULL, &errmsg);
    //if (result == SQLITE_OK)
    //{
    //    cout << "SQL 语句执行成功" << endl;
    //}
    //else
    //{
    //    cout << "SQL 语句执行时发生错误:" << sqlite3_errmsg(db) << endl;
    //}

#pragma endregion

#pragma region 执行SQL语句
    
    result = sqlite3_exec(db, "CREATE TABLE [t1](id integer PRIMARY KEY AUTOINCREMENT UNIQUE, name varchar);", NULL, NULL, &errmsg);
    if (result == SQLITE_OK)
    {
        cout << "SQL 语句执行成功" << endl;
    }
    else
    {
        cout << "SQL 语句执行时发生错误:" << sqlite3_errmsg(db) << endl;
    }

    result = sqlite3_exec(db, "INSERT INTO t1(name) VALUES('张三');", NULL, NULL, &errmsg);
    if (result == SQLITE_OK)
    {
        cout << "SQL 语句执行成功" << endl;
    }
    else
    {
        cout << "SQL 语句执行时发生错误:" << sqlite3_errmsg(db) << endl;
    }

    result = sqlite3_exec(db, "SELECT * FROM t1;", callback, NULL, &errmsg);
    if (result == SQLITE_OK)
    {
        cout << "SQL 语句执行成功" << endl;
    }
    else
    {
        cout << "SQL 语句执行时发生错误:" << sqlite3_errmsg(db) << endl;
    }

#pragma endregion

    sqlite3_close(db);
}

int main()
{
    std::cout << "Hello World!\n";

    dbTest();

    char sz[] = "End !";
    cout << sz << endl;
    return 0;
}

then I want to use it in Go project, code like this:

import (
	"database/sql"
	"fmt"
	"log"
	"os"
	_ "github.com/mutecomm/go-sqlcipher/v4"
)
func main() {
key := "abcdefg"
	dbname := fmt.Sprintf("sqlcipher.db?_pragma_key=x'%s'", key)

	db, err := sql.Open("sqlite3", dbname)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	rows, err := db.Exec("SELECT * FROM t1;")
	if err != nil {
		return
	}
	fmt.Println(rows)
}

when execute:

rows, err := db.Exec("SELECT * FROM t1;")

throw an error: file is not a database.

Any hints?

Upgrade sqlite version

Upgrading the version by cloning the code and running the script make the database not encrypted.

The version of go module is not correct

The tag is v3.4.2, but the go module name is github.com/mutecomm/go-sqlcipher, which is not right. Should be changed to github.com/mutecomm/go-sqlcipher/v3

How can I specify the key and other options, ie:`cipher_compatibility`

I have a password (hex, 64 len). And I have some other options. For now, I don't know how to specify those option. I have tried three ways. But none of those works, the error is file is not a database.

Tried 1:

param_str := "_pragma_cipher_page_size=4096&_cipher_compatibility=3&_cipher_page_size=4096&_synchronous=NORMAL&_count_changes=OFF&_auto_vacuum=0&_journal_mode=WAL"
dbname := fmt.Sprintf("%s?_pragma_key=x'%s'&%s", dbPath, dbPwd, param_str)
db, err := sql.Open("sqlcipher", dbname)

Tried 2:

sql.Register("sqlcipher", &sqlcipher.SQLiteDriver{
			ConnectHook: func(conn *sqlcipher.SQLiteConn) error {
			// 	fmt.Println("sqlcipher PRAGMA called")
				conn.Exec("PRAGMA cipher_compatibility = 3", nil)
				conn.Exec("PRAGMA cipher_page_size = 4096", nil)
				conn.Exec("PRAGMA synchronous=NORMAL", nil)
				conn.Exec("PRAGMA count_changes=OFF", nil)
				conn.Exec("PRAGMA auto_vacuum=0", nil)
				conn.Exec("PRAGMA journal_mode = WAL", nil)
				return nil
			},
		})
db, err := sql.Open("sqlcipher", dbname)

Tried 3:

db, err := sql.Open("sqlcipher", dbname)

if err != nil {
    log.Panic(err.Error())
}

db.Exec("PRAGMA cipher_compatibility=3")
db.Exec("PRAGMA cipher_page_size=4096")
db.Exec("PRAGMA synchronous=NORMAL")
db.Exec("PRAGMA count_changes=OFF")
db.Exec("PRAGMA auto_vacuum=0")
db.Exec("PRAGMA journal_mode=WAL")

What I want is specify the key and those pragma. What is the right way. Thank you!

Database re-encrypts after a minute or so

Question.

I'm currently doing something like this:

conn, err := sql.Open("sqlite3", dbPath)
if err != nil {
	return nil, err
}
if password != "" {
	p := "pragma key='" + password + "';"
	conn.Exec(p)
}

Immediately following this code I query to check to see if the db decrypted properly and it does. But then a minute or so later I start getting a file is encrypted or is not a database error. I'm not closing the connection. Just making queries on the existing instance.

Am I using this wrong? Is there some kind of timeout that re-encrypts it shortly after decryption? Do I need to re-call pragma key= before each db query?

json_extract

hi, i need to use this package and enable json_extract features, i tried to modify sqlite3.c and try to enable json_extract but it does not work, is there anyway to activate it? since the code is already there. thank you

cannot drop table column

Using 4.4.2 can successfully add table column, but cannot drop table column.
I checked sqlite version-3.38.0 to support drop column.
Could you update the sqlite that go-sqlcipher depends on to support drop column?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.