Skip to content

Instantly share code, notes, and snippets.

@aleks-mariusz
Last active November 9, 2016 17:33
Show Gist options
  • Save aleks-mariusz/001464e452edcbd9a44aa06ccb2256a3 to your computer and use it in GitHub Desktop.
Save aleks-mariusz/001464e452edcbd9a44aa06ccb2256a3 to your computer and use it in GitHub Desktop.
this script preps the sqlite db used by the web-app graphite after initial install by populating it with a default user, preventing a potential race condition resulting in a deadlock requiring the httpd server to be restarted after the first run
#!/usr/bin/env python
import hashlib
import hmac
import random
import sqlite3
import string
from base64 import b64encode
from itertools import izip, starmap
from operator import xor
from os import urandom
from struct import Struct
path_graphite_sqlite_db = '/var/lib/graphite-web/graphite.db' # rpm install, may be /opt/graphite/storage if you installed from src
iterations = 10000
keylen = 24
salt_length = 12
hash_func = 'sha256'
secret_key = urandom(32)
salt = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(salt_length))
# following is based on https://github.com/mitsuhiko/python-pbkdf2/blob/master/pbkdf2.py
buf = []
mac = hmac.new(secret_key, None, getattr(hashlib, hash_func))
def _pseudorandom(x, mac=mac):
h = mac.copy()
h.update(x)
return map(ord, h.digest())
for block in xrange(1, -(-keylen // mac.digest_size) + 1):
rv = u = _pseudorandom(salt + Struct('>I').pack(block))
for i in xrange(iterations - 1):
u = _pseudorandom(''.join(map(chr, u)))
rv = starmap(xor, izip(rv, u))
buf.extend(rv)
# this is the format that the graphite sqlite db uses to save a random passwd
random_hash = '$'.join(['pbkdf2_'+hash_func, str(iterations), salt, b64encode(''.join(map(chr, buf)))])
# and finally save our new default user
with sqlite3.connect(path_graphite_sqlite_db) as db:
cursor = db.cursor()
cursor.execute('''INSERT INTO auth_user VALUES(1,'default','','','[email protected]',:hash,0,1,0,datetime(),datetime())''', {'hash':random_hash})
cursor.execute('''INSERT INTO account_profile VALUES(1,1,'',0)''')
db.commit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment