def decrypt( key ,operation):
	if operation==1:
		conn = sqlite.connect( ORIGINAL_FILE )
	else:
		conn = sqlite.connect( DECRYPTED_FILE )
	c = conn.cursor()		
	try:
		if operation==1:
			c.execute( "PRAGMA key = '" + key + "';" )
			c.execute( "PRAGMA cipher_use_hmac = OFF;" )
			c.execute( "PRAGMA cipher_page_size = 1024;" )
			c.execute( "PRAGMA kdf_iter = 4000;" )
			c.execute( "ATTACH DATABASE '"+DECRYPTED_FILE+"' AS wechatdecrypted KEY '';" )
			c.execute( "SELECT sqlcipher_export( 'wechatdecrypted' );" )
			c.execute( "DETACH DATABASE wechatdecrypted;" )
		else:
			c.execute( "ATTACH DATABASE '"+ENCRYPTED_FILE_NEW+"' AS wechatencrypted KEY '"+ key +"';" )
			c.execute( "PRAGMA wechatencrypted.cipher_use_hmac = OFF;" )
			c.execute( "PRAGMA wechatencrypted.cipher_page_size = 1024;" )
			c.execute( "PRAGMA wechatencrypted.kdf_iter = 4000;" )
			c.execute( "SELECT sqlcipher_export( 'wechatencrypted' );" )
			c.execute( "DETACH DATABASE wechatencrypted;" )
		c.close()
		status = 1
	except:
		c.close()
		status = 0
	return status
def decrypt(key, operation):
    if operation == 1:
        conn = sqlite.connect(ORIGINAL_FILE)
    else:
        conn = sqlite.connect(DECRYPTED_FILE)
    c = conn.cursor()
    try:
        if operation == 1:
            c.execute("PRAGMA key = '" + key + "';")
            c.execute("PRAGMA cipher_use_hmac = OFF;")
            c.execute("PRAGMA cipher_page_size = 1024;")
            c.execute("PRAGMA kdf_iter = 4000;")
            c.execute("ATTACH DATABASE '" + DECRYPTED_FILE +
                      "' AS wechatdecrypted KEY '';")
            c.execute("SELECT sqlcipher_export( 'wechatdecrypted' );")
            c.execute("DETACH DATABASE wechatdecrypted;")
        else:
            c.execute("ATTACH DATABASE '" + ENCRYPTED_FILE_NEW +
                      "' AS wechatencrypted KEY '" + key + "';")
            c.execute("PRAGMA wechatencrypted.cipher_use_hmac = OFF;")
            c.execute("PRAGMA wechatencrypted.cipher_page_size = 1024;")
            c.execute("PRAGMA wechatencrypted.kdf_iter = 4000;")
            c.execute("SELECT sqlcipher_export( 'wechatencrypted' );")
            c.execute("DETACH DATABASE wechatencrypted;")
        c.close()
        status = 1
    except:
        c.close()
        status = 0
    return status
Exemple #3
0
    def setUp(self):
        try:
            os.remove(get_db_path())
        except OSError:
            pass

        self.con1 = sqlite.connect(get_db_path(), timeout=0.1)
        self.cur1 = self.con1.cursor()

        self.con2 = sqlite.connect(get_db_path(), timeout=0.1)
        self.cur2 = self.con2.cursor()
def init_db():
    # Initialize in-memory database
    app_db = sqlcipher.connect(':memory:', check_same_thread = False)

    # Connect to disk-based database and use key
    db = sqlcipher.connect(app.config['DB'])
    db.executescript('pragma key = "{}"'.format(app.config['KEY']))

    # Copy database to memory
    app_db.executescript(''.join(line for line in db.iterdump()))

    return app_db
Exemple #5
0
 def CheckFailedOpen(self):
     YOU_CANNOT_OPEN_THIS = "/foo/bar/bla/23534/mydb.db"
     try:
         con = sqlite.connect(YOU_CANNOT_OPEN_THIS)
     except sqlite.OperationalError:
         return
     self.fail("should have raised an OperationalError")
Exemple #6
0
 def CheckAutoCommit(self):
     """
     Verifies that creating a connection in autocommit mode works.
     2.5.3 introduced a regression so that these could no longer
     be created.
     """
     con = sqlite.connect(":memory:", isolation_level=None)
Exemple #7
0
 def CheckSetIsolationLevel(self):
     """
     See issue 3312.
     """
     con = sqlite.connect(":memory:")
     self.assertRaises(UnicodeEncodeError, setattr, con,
                       "isolation_level", u"\xe9")
Exemple #8
0
def encrypt(args):
    print
    print yellow('Generating key...')
    key = _generate_key(args.imei, args.uin)
    print
    print green('=' * 80)
    print green('The key is:')
    print
    print cyan('  %s' % key)
    print
    print yellow('Encrypting, hang on...')
    _delete_file_if_exists(args.output_file)
    conn = sqlite.connect(args.input_file)
    c = conn.cursor()
    try:
        c.execute('PRAGMA cipher_default_use_hmac = OFF;')
        c.execute('ATTACH DATABASE \'%s\' AS encrypted KEY \'%s\';' %
                  (args.output_file, key))
        c.execute('PRAGMA cipher_use_hmac = OFF;')
        c.execute('SELECT sqlcipher_export(\'encrypted\');')
        c.execute('DETACH DATABASE encrypted;')
    except:
        print
        print red('=' * 80)
        print red('An error occurred.')
        sys.exit(1)
    else:
        print
        print green('=' * 80)
        print green('Success!')
    finally:
        c.close()
def db_connect(password):
	db = dbapi2.connect(path(app.config['DB_NAME']))
	# TODO: Use something better than re.escape for this
	# For some reason, normal '?' placeholders don't work for PRAGMA's
	db.execute("PRAGMA key = '%s'" % re.escape(password))
	db.execute("PRAGMA foreign_keys = ON")
	return db
Exemple #10
0
 def setUp(self):
     self.cx = sqlite.connect(":memory:")
     self.cx.execute("create table test(id integer primary key, blob_col blob)")
     self.blob_data = "a" * 100
     self.cx.execute("insert into test(blob_col) values (?)", (self.blob_data, ))
     self.blob = self.cx.blob("test", "blob_col", 1, 1)
     self.second_data = "b" * 100
Exemple #11
0
def main():
    argv = sys.argv
    if len(argv) != 4:
        print 'usage: python desql.py encrypted_file password decrypted_file'
        return
    encrypted_file = argv[1]
    password = argv[2]
    decrypted_file = argv[3]
    conn = sqlite.connect(encrypted_file)
    c = conn.cursor()
    try:
        c.execute("PRAGMA key = '" + password + "';")
        c.execute("PRAGMA cipher_use_hmac = OFF;")
        c.execute("PRAGMA cipher_page_size = 1024;")
        c.execute("PRAGMA kdf_iter = 4000;")
        c.execute("ATTACH DATABASE '" + decrypted_file +
                  "' AS wechatdecrypted KEY '';")
        c.execute("SELECT sqlcipher_export( 'wechatdecrypted' );")
        c.execute("DETACH DATABASE wechatdecrypted;")
        c.close()
        print 'Decrypt Success!'
    except:
        c.close()
        os.remove(decrypted_file)
        print 'Decrypt Error!'
        print 'Exception:'
        print traceback.format_exc()
Exemple #12
0
 def _open_database(cls, sqlite_file, password, document_factory=None,
                    soledad=None):
     if not os.path.isfile(sqlite_file):
         raise errors.DatabaseDoesNotExist()
     tries = 2
     while True:
         # Note: There seems to be a bug in sqlite 3.5.9 (with python2.6)
         #       where without re-opening the database on Windows, it
         #       doesn't see the transaction that was just committed
         db_handle = dbapi2.connect(sqlite_file)
         SQLCipherDatabase.set_pragma_key(db_handle, password)
         c = db_handle.cursor()
         v, err = cls._which_index_storage(c)
         db_handle.close()
         if v is not None:
             break
         # possibly another process is initializing it, wait for it to be
         # done
         if tries == 0:
             raise err  # go for the richest error?
         tries -= 1
         time.sleep(cls.WAIT_FOR_PARALLEL_INIT_HALF_INTERVAL)
     return SQLCipherDatabase._sqlite_registry[v](
         sqlite_file, password, document_factory=document_factory,
         soledad=soledad)
Exemple #13
0
 def CheckFailedOpen(self):
     YOU_CANNOT_OPEN_THIS = "/foo/bar/bla/23534/mydb.db"
     try:
         con = sqlite.connect(YOU_CANNOT_OPEN_THIS)
     except sqlite.OperationalError:
         return
     self.fail("should have raised an OperationalError")
Exemple #14
0
def init_cuppoc_db():
    '''
    Use pysqlcipher to create an encrypted targets.db or
    open the existing one with the correct key.
    '''
    while True:
        print("NOTE:")
        print("[!] Checking to see if \"targets.db\" exists or not.")
        print("[!] If it doesn't, cuppoc will make one.")
        print("[!] cuppoc uses AES256 to encrypt your local database.")
        print("[!] This is due to Personally Identifiable Information (PII)")
        print("[!] which will be stored in the database.\n")
        print("[!] You will be asked to enter a password.")
        print("[!] This password is the key to your database. Don't forget :P")
        print("[!] If you have already done this before,")
        print("[!] Then please use the password you used before.")
        db = sqlite.connect("./targets.db")
        cursor = db.cursor()
        user_key = raw_input("> Please enter the password for database: ")
        cursor.execute("PRAGMA key='%s'" % user_key)
        try:
            cursor.execute("CREATE TABLE IF NOT EXISTS Targets (" +
                           "ID INTEGER PRIMARY KEY," + "First_Name TEXT," +
                           "Last_Name TEXT)")
            print("[+] Done... Starting cuppoc!")
            print_separator()
            sleep(3)
            break
        except PYSQLDBERR:
            print("[-] Database doesn't exist or is encrypted.")
            print("[-] If database exists, enter the correct password.")
            print_separator()
            db.close()
            sys.exit(0)
    return [db, cursor]
Exemple #15
0
 def setUp(self):
     self.cx = sqlite.connect(":memory:")
     self.cu = self.cx.cursor()
     self.cu.execute(
         "create table test(id integer primary key, name text, income number)"
     )
     self.cu.execute("insert into test(name) values (?)", ("foo", ))
Exemple #16
0
 def CheckConnectionExecutemany(self):
     con = sqlite.connect(":memory:")
     con.execute("create table test(foo)")
     con.executemany("insert into test(foo) values (?)", [(3,), (4,)])
     result = con.execute("select foo from test order by foo").fetchall()
     self.assertEqual(result[0][0], 3, "Basic test of Connection.executemany")
     self.assertEqual(result[1][0], 4, "Basic test of Connection.executemany")
Exemple #17
0
 def CheckCreateCollationNotCallable(self):
     con = sqlite.connect(":memory:")
     try:
         con.create_collation("X", 42)
         self.fail("should have raised a TypeError")
     except TypeError, e:
         self.assertEqual(e.args[0], "parameter must be callable")
Exemple #18
0
    def __GET_STATUS(self):
        status = ""
        try:
            conn = sqlite3.connect(
                path_constants.installation + '/stats.db', timeout=10)
        except:
            pass

        try:
            cur = conn.cursor()
            cur.execute("PRAGMA key='f$$pm->>>'")
            status = cur.execute("select error from errors where ptid='%s' and accession='%s' and series='%s'" %
                                 (self.__patient.ID, self.__patient.AccessionNumber, self.__patient.SeriesDescription)).fetchall()[0][0]
            conn.close()
        except IndexError:
            print "Not processed before."
            conn.close()
        except Exception as exc:
            print "Problem reading status: %s" % exc
            conn.close()

        if(status
           and (re.findall("error", status, flags=re.IGNORECASE)
                or re.findall("problem", status, flags=re.IGNORECASE))):
            print "Already processed, but with errors."
            self.__set_state(STATES.FS)
        elif(status and re.findall("Already processed", status, flags=re.IGNORECASE)):
            print "Already processed without errors, but attempted reprocessed before."
            self.__set_state(STATES.FS)
        # Not procssed
        elif(not status):
            self.__set_state(STATES.FS)
        else:
            self.__success = "Already processed."
            self.__set_state(STATES.QUITTING)
Exemple #19
0
 def CheckCreateCollationNotAscii(self):
     con = sqlite.connect(":memory:")
     try:
         con.create_collation("collä", cmp)
         self.fail("should have raised a ProgrammingError")
     except sqlite.ProgrammingError, e:
         pass
Exemple #20
0
    def CheckCollationIsUsed(self):
        if sqlite.version_info < (3, 2,
                                  1):  # old SQLite versions crash on this test
            return

        def mycoll(x, y):
            # reverse order
            return -cmp(x, y)

        con = sqlite.connect(":memory:")
        con.create_collation("mycoll", mycoll)
        sql = """
            select x from (
            select 'a' as x
            union
            select 'b' as x
            union
            select 'c' as x
            ) order by x collate mycoll
            """
        result = con.execute(sql).fetchall()
        if result[0][0] != "c" or result[1][0] != "b" or result[2][0] != "a":
            self.fail("the expected order was not returned")

        con.create_collation("mycoll", None)
        try:
            result = con.execute(sql).fetchall()
            self.fail("should have raised an OperationalError")
        except sqlite.OperationalError, e:
            self.assertEqual(e.args[0].lower(),
                             "no such collation sequence: mycoll")
Exemple #21
0
 def CheckCreateCollationNotCallable(self):
     con = sqlite.connect(":memory:")
     try:
         con.create_collation("X", 42)
         self.fail("should have raised a TypeError")
     except TypeError, e:
         self.assertEqual(e.args[0], "parameter must be callable")
Exemple #22
0
 def CheckCreateCollationNotAscii(self):
     con = sqlite.connect(":memory:")
     try:
         con.create_collation("collä", cmp)
         self.fail("should have raised a ProgrammingError")
     except sqlite.ProgrammingError, e:
         pass
Exemple #23
0
def db_connect(password):
    db = dbapi2.connect(path(app.config['DB_NAME']))
    # TODO: Use something better than re.escape for this
    # For some reason, normal '?' placeholders don't work for PRAGMA's
    db.execute("PRAGMA key = '%s'" % re.escape(password))
    db.execute("PRAGMA foreign_keys = ON")
    return db
Exemple #24
0
    def _connect(self):
        params = dict(self.connect_params)
        passphrase = params.pop('passphrase', '')
        kdf_iter = params.pop('kdf_iter', 64000)

        if len(passphrase) < 8:
            raise ImproperlyConfigured(
                'SqlCipherDatabase passphrase should be at least eight '
                'character long.')

        if kdf_iter and kdf_iter < 10000:
            raise ImproperlyConfigured(
                'SqlCipherDatabase kdf_iter should be at least 10000.')

        conn = sqlcipher.connect(self.database, **params)
        conn.isolation_level = None
        try:
            self._add_conn_hooks(conn)
            conn.execute(
                'PRAGMA key=\'{0}\''.format(passphrase.replace("'", "''")))
            conn.execute('PRAGMA kdf_iter={0:d}'.format(kdf_iter))
        except:
            conn.close()
            raise
        else:
            return conn
Exemple #25
0
def decrypt(key):
    if not key:
        print('key is empty!!!')
        sys.exit(-1)
    print('password is {}!'.format(key))
    for name in os.listdir('.'):
        if os.path.splitext(name)[1] == '.db':
            conn = sqlite.connect(name)
            c = conn.cursor()
            try:
                c.execute("PRAGMA key = '{}';".format(key))
                c.execute("PRAGMA cipher_page_size = 1024;")
                c.execute("PRAGMA kdf_iter = 4000;")
                c.execute("PRAGMA cipher_hmac_algorithm = HMAC_SHA1;")
                c.execute("PRAGMA cipher_kdf_algorithm = PBKDF2_HMAC_SHA1;")
                c.execute("PRAGMA cipher_use_hmac = OFF;")
                c.execute("ATTACH DATABASE '{}' AS plaintext KEY '';".format(
                    'decrypt-' + name))
                c.execute("SELECT sqlcipher_export('plaintext');")
                c.execute("DETACH DATABASE plaintext;")
                conn.commit()
                c.close()
            except Exception as e:
                print(repr(e))
                print('An error occurred!!!')
                print('The possible reason is the wrong password?')
                sys.exit(-1)
            finally:
                c.close()
Exemple #26
0
def encrypt(args):
    print
    print yellow('Generating key...')
    key = _generate_key(args.imei, args.uin)
    print
    print green('=' * 80)
    print green('The key is:')
    print
    print cyan('  %s' % key)
    print
    print yellow('Encrypting, hang on...')
    _delete_file_if_exists(args.output_file)
    conn = sqlite.connect(args.input_file)
    c = conn.cursor()
    try:
        c.execute('PRAGMA cipher_default_use_hmac = OFF;')
        c.execute('ATTACH DATABASE \'%s\' AS encrypted KEY \'%s\';' % (args.output_file, key))
        c.execute('PRAGMA cipher_use_hmac = OFF;')
        c.execute('SELECT sqlcipher_export(\'encrypted\');')
        c.execute('DETACH DATABASE encrypted;')
    except:
        print
        print red('=' * 80)
        print red('An error occurred.')
        sys.exit(1)
    else:
        print
        print green('=' * 80)
        print green('Success!')
    finally:
        c.close()
Exemple #27
0
def getDecryptFile(db, key, fileIn, fileOut ):
    status = False

    if not os.path.isfile(fileOut):
        # 
        # code source: http://articles.forensicfocus.com/2014/10/01/decrypt-wechat-enmicromsgdb-database/
        # 
        conn = sqlite3.connect( u'%s' % fileIn )
        conn.row_factory = sqlite3.Row
        cur = conn.cursor()
        if setDecryptParams(cur, key):		
            try:
                print( u'Decrypting...' )
                cur.execute( 'ATTACH DATABASE "%s" AS wechatdecrypted KEY "";' % fileOut)
                cur.execute( 'SELECT sqlcipher_export( "wechatdecrypted" );' )
                cur.execute( 'DETACH DATABASE wechatdecrypted;' )
                print( u'Detaching database...' )
                cur.close()
                status = True
            except:
                print(u'Decrypting failed!')
                pass
                
        cur.close()
	
    return(status)
Exemple #28
0
def getFuncTemplate(db, decrypted=True, key=None):
    results = []

    # Create query
    query = 'SELECT * FROM friend_ext;'
    
    # Open database, set up cursor to read database   
    conn = sqlite3.connect(db)
    conn.row_factory = sqlite3.Row
    cur = conn.cursor()

    if not decrypted:
        if not setDecryptParams(cur, key):
            cur.close()
            return(result)
        
    # Execute query
    cur.execute(query)
    try:
        for index, row in enumerate(cur):
            pass
    except:
        pass

    cur.close()

    return(results)
Exemple #29
0
 def _open_database(cls,
                    sqlite_file,
                    password,
                    document_factory=None,
                    soledad=None):
     if not os.path.isfile(sqlite_file):
         raise errors.DatabaseDoesNotExist()
     tries = 2
     while True:
         # Note: There seems to be a bug in sqlite 3.5.9 (with python2.6)
         #       where without re-opening the database on Windows, it
         #       doesn't see the transaction that was just committed
         db_handle = dbapi2.connect(sqlite_file)
         SQLCipherDatabase.set_pragma_key(db_handle, password)
         c = db_handle.cursor()
         v, err = cls._which_index_storage(c)
         db_handle.close()
         if v is not None:
             break
         # possibly another process is initializing it, wait for it to be
         # done
         if tries == 0:
             raise err  # go for the richest error?
         tries -= 1
         time.sleep(cls.WAIT_FOR_PARALLEL_INIT_HALF_INTERVAL)
     return SQLCipherDatabase._sqlite_registry[v](
         sqlite_file,
         password,
         document_factory=document_factory,
         soledad=soledad)
Exemple #30
0
    def CheckCollationIsUsed(self):
        if sqlite.version_info < (3, 2, 1):  # old SQLite versions crash on this test
            return
        def mycoll(x, y):
            # reverse order
            return -cmp(x, y)

        con = sqlite.connect(":memory:")
        con.create_collation("mycoll", mycoll)
        sql = """
            select x from (
            select 'a' as x
            union
            select 'b' as x
            union
            select 'c' as x
            ) order by x collate mycoll
            """
        result = con.execute(sql).fetchall()
        if result[0][0] != "c" or result[1][0] != "b" or result[2][0] != "a":
            self.fail("the expected order was not returned")

        con.create_collation("mycoll", None)
        try:
            result = con.execute(sql).fetchall()
            self.fail("should have raised an OperationalError")
        except sqlite.OperationalError, e:
            self.assertEqual(e.args[0].lower(), "no such collation sequence: mycoll")
Exemple #31
0
    def CheckClosed(self):
        con = sqlite.connect(":memory:")
        cur = con.cursor()
        cur.close()

        for method_name in ("execute", "executemany", "executescript",
                            "fetchall", "fetchmany", "fetchone"):
            if method_name in ("execute", "executescript"):
                params = ("select 4 union select 5", )
            elif method_name == "executemany":
                params = ("insert into foo(bar) values (?)", [(3, ), (4, )])
            else:
                params = []

            try:
                method = getattr(cur, method_name)

                method(*params)
                self.fail("Should have raised a ProgrammingError: method " +
                          method_name)
            except sqlite.ProgrammingError:
                pass
            except:
                self.fail("Should have raised a ProgrammingError: " +
                          method_name)
    def test__open_database_during_init(self):
        temp_dir = self.createTempDir(prefix='u1db-test-')
        path = temp_dir + '/initialised.db'
        db = SQLCipherDatabase.__new__(
            SQLCipherDatabase)
        db._db_handle = dbapi2.connect(path)  # db is there but not yet init-ed
        db._syncers = {}
        c = db._db_handle.cursor()
        c.execute('PRAGMA key="%s"' % PASSWORD)
        self.addCleanup(db.close)
        observed = []

        class SQLiteDatabaseTesting(SQLCipherDatabase):
            WAIT_FOR_PARALLEL_INIT_HALF_INTERVAL = 0.1

            @classmethod
            def _which_index_storage(cls, c):
                res = SQLCipherDatabase._which_index_storage(c)
                db._ensure_schema()  # init db
                observed.append(res[0])
                return res

        db2 = SQLiteDatabaseTesting._open_database(path, PASSWORD)
        self.addCleanup(db2.close)
        self.assertIsInstance(db2, SQLCipherDatabase)
        self.assertEqual(
            [None,
             SQLCipherDatabase._index_storage_value],
            observed)
Exemple #33
0
    def _connect(self):
        params = dict(self.connect_params)
        passphrase = params.pop('passphrase', '')
        kdf_iter = params.pop('kdf_iter', 64000)

        if len(passphrase) < 8:
            raise ImproperlyConfigured(
                'SqlCipherDatabase passphrase should be at least eight '
                'character long.')

        if kdf_iter and kdf_iter < 10000:
            raise ImproperlyConfigured(
                'SqlCipherDatabase kdf_iter should be at least 10000.')

        conn = sqlcipher.connect(self.database, **params)
        conn.isolation_level = None
        try:
            conn.execute(
                'PRAGMA key=\'{0}\''.format(passphrase.replace("'", "''")))
            conn.execute('PRAGMA kdf_iter={0:d}'.format(kdf_iter))
            self._add_conn_hooks(conn)
        except:
            conn.close()
            raise
        else:
            return conn
Exemple #34
0
def _decrpyt(src, dst, key, cipher, kdf_iter, cipher_page_size):
	conn = sqlite.connect(src)
	c = conn.cursor()
	c.execute("PRAGMA key='{0}'".format(key))
	if kdf_iter is not None:
		c.execute("PRAGMA kdf_iter={0}".format(kdf_iter))
	if cipher is not None:
		c.execute("PRAGMA cipher='{0}'".format(cipher))
	if cipher_page_size is not None:
		c.execute("PRAGMA cipher_page_size={0}".format(cipher_page_size))
	c.close()
	
	c = conn.cursor()
	try:
		c.execute('SELECT COUNT(*) from sqlite_master')
		count = c.fetchone()[0]
	except sqlite.DatabaseError as ex:
		print('wrong key: {0}'.format(ex))
		sys.exit(1)
	finally:
		c.close()
	
	c = conn.cursor()
	c.execute("ATTACH DATABASE '{0}' AS plaintext KEY ''".format(dst))
	c.execute("SELECT sqlcipher_export('plaintext');")
	c.execute("DETACH DATABASE plaintext")
	c.close()
    def setUp(self):
        self.con = sqlite.connect(":memory:")
        cur = self.con.cursor()
        cur.execute("""
            create table test(
                t text,
                i integer,
                f float,
                n,
                b blob
                )
            """)
        cur.execute("insert into test(t, i, f, n, b) values (?, ?, ?, ?, ?)", (
            "foo",
            5,
            3.14,
            None,
            buffer("blob"),
        ))

        self.con.create_aggregate("nostep", 1, AggrNoStep)
        self.con.create_aggregate("nofinalize", 1, AggrNoFinalize)
        self.con.create_aggregate("excInit", 1, AggrExceptionInInit)
        self.con.create_aggregate("excStep", 1, AggrExceptionInStep)
        self.con.create_aggregate("excFinalize", 1, AggrExceptionInFinalize)
        self.con.create_aggregate("checkType", 2, AggrCheckType)
        self.con.create_aggregate("mysum", 1, AggrSum)
Exemple #36
0
    def __init__(self,
                 sqlite_file,
                 password,
                 document_factory=None,
                 soledad=None):
        """Create a new sqlcipher file."""
        self._check_if_db_is_encrypted(sqlite_file)
        self._db_handle = dbapi2.connect(sqlite_file)
        SQLCipherDatabase.set_pragma_key(self._db_handle, password)
        self._real_replica_uid = None
        self._ensure_schema()
        self._soledad = soledad

        def factory(doc_id=None,
                    rev=None,
                    json='{}',
                    has_conflicts=False,
                    encrypted_json=None,
                    syncable=True):
            return LeapDocument(doc_id=doc_id,
                                rev=rev,
                                json=json,
                                has_conflicts=has_conflicts,
                                encrypted_json=encrypted_json,
                                syncable=syncable,
                                soledad=self._soledad)

        self.set_document_factory(factory)
    def test__open_database_during_init(self):
        temp_dir = self.createTempDir(prefix='u1db-test-')
        path = temp_dir + '/initialised.db'
        db = sqlite_backend.SQLitePartialExpandDatabase.__new__(
            sqlite_backend.SQLitePartialExpandDatabase)
        db._db_handle = dbapi2.connect(path)  # db is there but not yet init-ed
        self.addCleanup(db.close)
        observed = []

        class SQLiteDatabaseTesting(sqlite_backend.SQLiteDatabase):
            WAIT_FOR_PARALLEL_INIT_HALF_INTERVAL = 0.1

            @classmethod
            def _which_index_storage(cls, c):
                res = super(SQLiteDatabaseTesting, cls)._which_index_storage(c)
                db._ensure_schema()  # init db
                observed.append(res[0])
                return res

        db2 = SQLiteDatabaseTesting._open_database(path)
        self.addCleanup(db2.close)
        self.assertIsInstance(db2, sqlite_backend.SQLitePartialExpandDatabase)
        self.assertEqual(
            [None,
             sqlite_backend.SQLitePartialExpandDatabase._index_storage_value],
            observed)
Exemple #38
0
    def test__open_database_during_init(self):
        temp_dir = self.createTempDir(prefix='u1db-test-')
        path = temp_dir + '/initialised.db'
        db = sqlite_backend.SQLitePartialExpandDatabase.__new__(
            sqlite_backend.SQLitePartialExpandDatabase)
        db._db_handle = dbapi2.connect(path)  # db is there but not yet init-ed
        self.addCleanup(db.close)
        observed = []

        class SQLiteDatabaseTesting(sqlite_backend.SQLiteDatabase):
            WAIT_FOR_PARALLEL_INIT_HALF_INTERVAL = 0.1

            @classmethod
            def _which_index_storage(cls, c):
                res = super(SQLiteDatabaseTesting, cls)._which_index_storage(c)
                db._ensure_schema()  # init db
                observed.append(res[0])
                return res

        db2 = SQLiteDatabaseTesting._open_database(path)
        self.addCleanup(db2.close)
        self.assertIsInstance(db2, sqlite_backend.SQLitePartialExpandDatabase)
        self.assertEqual([
            None,
            sqlite_backend.SQLitePartialExpandDatabase._index_storage_value
        ], observed)
Exemple #39
0
 def setUp(self):
     self.con = sqlite.connect(":memory:")
     try:
         del sqlite.adapters[int]
     except:
         pass
     sqlite.register_adapter(int, ObjectAdaptationTests.cast)
     self.cur = self.con.cursor()
Exemple #40
0
 def setUp(self):
     self.con = sqlite.connect(":memory:")
     try:
         del sqlite.adapters[int]
     except:
         pass
     sqlite.register_adapter(int, ObjectAdaptationTests.cast)
     self.cur = self.con.cursor()
Exemple #41
0
def get_all_users(table):
    try:
        db = sqlcipher.connect("users.db")
        db.executescript('pragma key="testing"; pragma kdf_iter=64000;')
        row = db.execute("select * from " + table).fetchall()
        return row
    finally:
        db.close()
Exemple #42
0
 def connect(self, *args, **kwargs):
     if not self._connection:
         self._connection = sqlite.connect(*args, **kwargs)
         #return Status(status=True)
         #return None
         #p("NEW CONNECTION WAS ESTABL. {}, {}".format(inspect.stack()[-18][3], args[0]), c="g")
         return self
     else:
         raise ZASConnectionError, "Connection is already exist!"
def have_usleep():
    fname = tempfile.mktemp()
    db = dbapi2.connect(fname)
    cursor = db.cursor()
    cursor.execute('PRAGMA compile_options;')
    options = map(lambda t: t[0], cursor.fetchall())
    db.close()
    os.unlink(fname)
    return u'HAVE_USLEEP' in options
Exemple #44
0
def queryCDR(id):
    db = sqlcipher.connect(app.config['db'])

    id = tuple([id])
    db.executescript('pragma key = "%s" ' % app.config['key'])
    results = db.execute('select * from terms where id like ?', id).fetchall()
    db.close()

    return results
Exemple #45
0
 def CheckScriptErrorNormal(self):
     con = sqlite.connect(":memory:")
     cur = con.cursor()
     raised = False
     try:
         cur.executescript("create table test(sadfsadfdsa); select foo from hurz;")
     except sqlite.OperationalError:
         raised = True
     self.assertEqual(raised, True, "should have raised an exception")
Exemple #46
0
def get_random_user(table):
    try:
        db = sqlcipher.connect("users.db")
        db.executescript('pragma key="testing"; pragma kdf_iter=64000;')
        row = db.execute('SELECT * FROM ' + table +
                         ' ORDER BY RANDOM() LIMIT 1;').fetchall()
        return row[0]
    finally:
        db.close()
Exemple #47
0
def get_selected_user(table, user):
    try:
        db = sqlcipher.connect("users.db")
        db.executescript('pragma key="testing"; pragma kdf_iter=64000;')
        row = db.execute("select * from " + table + " where usr like '" +
                         user + "' LIMIT 1").fetchall()
        return row[0]
    finally:
        db.close()
Exemple #48
0
def getEntries(db, password):
    """Get everything in the database. Used a lot in testing stuff after insertions and deletions."""
    conn = sqlite.connect(db)
    c = conn.cursor()
    c.execute("PRAGMA key='{}'".format(password))
    entries = c.execute("SELECT * FROM entries").fetchall()
    c.close()
    conn.close()
    return entries
Exemple #49
0
    def setUp(self):
        self.con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES)
        self.cur = self.con.cursor()
        self.cur.execute("create table test(x foo)")

        sqlite.converters["FOO"] = lambda x: "[%s]" % x
        sqlite.converters["BAR"] = lambda x: "<%s>" % x
        sqlite.converters["EXC"] = lambda x: 5 // 0
        sqlite.converters["B1B1"] = lambda x: "MARKER"
Exemple #50
0
 def CheckPragmaSchemaVersion(self):
     # This still crashed pysqlite <= 2.2.1
     con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES)
     try:
         cur = self.con.cursor()
         cur.execute("pragma schema_version")
     finally:
         cur.close()
         con.close()
Exemple #51
0
 def CheckScriptSyntaxError(self):
     con = sqlite.connect(":memory:")
     cur = con.cursor()
     raised = False
     try:
         cur.executescript("create table test(x); asdf; create table test2(x)")
     except sqlite.OperationalError:
         raised = True
     self.assertEqual(raised, True, "should have raised an exception")
Exemple #52
0
 def CheckConnectionExecutemany(self):
     con = sqlite.connect(":memory:")
     con.execute("create table test(foo)")
     con.executemany("insert into test(foo) values (?)", [(3, ), (4, )])
     result = con.execute("select foo from test order by foo").fetchall()
     self.assertEqual(result[0][0], 3,
                      "Basic test of Connection.executemany")
     self.assertEqual(result[1][0], 4,
                      "Basic test of Connection.executemany")
 def openDBFile(self):
     fileExists = os.path.isfile(self.filename)
     self.connection = dbapi2.connect(self.filename)
     self.cursor = self.connection.cursor()
     self.cursor.execute("PRAGMA KEY = '" + self.key + "';")
     if not fileExists:
         self.cursor.execute("CREATE TABLE testvalid(nothing);")
         self.cursor.execute("CREATE TABLE log(name NOT NULL, personType NOT NULL, direction NOT NULL, time INTEGER NOT NULL, room integer);")
         self.cursor.execute("CREATE TABLE status(name NOT NULL, personType NOT NULL, isHere NOT NULL DEFAULT 'f', currentRoom integer, enterTime INTEGER, exitTime INTEGER);")
 def open(self):
     fileExists = os.path.isfile(self.file)
     self.connection = sqlite.connect(self.file)
     self.cursor = self.connection.cursor()
     self.cursor.execute("PRAGMA KEY = '" + self.key + "';")
     self.cursor.execute("PRAGMA case_sensitive_like=ON;")
     if not fileExists:
         self.cursor.execute("CREATE TABLE testvalid(nothing);")
         self.cursor.execute("CREATE TABLE log(name NOT NULL, role NOT NULL, direction NOT NULL, room_id integer, time integer NOT NULL);")
         self.cursor.execute("CREATE TABLE status(name NOT NULL, role NOT NULL, is_here NOT NULL DEFAULT 0, cur_room integer, enter_time integer, accumulated_time NOT NULL DEFAULT 0);")
Exemple #55
0
def emptyEntries(db, password):
    """Empty the entries table. Clean table required for each test."""
    conn = sqlite.connect(db)
    c = conn.cursor()
    c.execute("PRAGMA key='{}'".format(password))
    c.execute("""DELETE FROM entries""")
    conn.commit()
    c.close()
    conn.close()
    return