#!/usr/bin/python
#
# This script extracts the Bluetooth link keys
# from BlueZ's link key file /etc/bluetooth/link_key
# and creates a Windows .inf-file in the current
# directory. This inf-file will install the link keys
# under windows (right click -> install).
#
# By sharing the keys between the MS-Stack and BlueZ
# you avoid the problem that devices have to be pair
# every time you switch the OS while using the same
# Bluetooth dongle.
#
# Copyright 2004 by Fred Schaettgen <bluez.sch@ttgen.net>

import sys

outFileName = "bluez_keys.inf"
keyFileName = "/etc/bluetooth/link_key"

def printError(msg):
    print "ERROR: "+msg
    sys.exit(1)

def toRevHexStr(s, separator):
    ret = ""
    sep = ""
    for c in s:
        ret = hex(int(ord(c))+0x100)[3:6] + sep + ret
        sep = separator
    return ret

def toDosStr(s):
    ret = ""
    for c in s:
        if c=="\n":
            ret = ret + "\r\n"
        else:
            ret = ret + c
    return ret

def writeOut(s):
    global outFile
    outFile.write(toDosStr(s))

keyFile = open(keyFileName, "r")
keyRecordsRaw = []

outFile = open(outFileName, "w")

recordSize = 36
record = keyFile.read(recordSize)
while len(record) == recordSize:
    keyRecordsRaw.append(record)
    record = keyFile.read(recordSize)
if len(record) != 0:
    printError("Unexpected end of link key file!")

keyList = []
for record in keyRecordsRaw:
    d = dict()
    d["if"] = toRevHexStr(record[0:6], "")
    d["dev"] = toRevHexStr(record[6:12], "")
    d["key"] = toRevHexStr(record[12:28], ",")
    keyList.append(d)


writeOut("""\
[Version]
Signature=\"$CHICAGO$\"
AdvancedINF=2.5

; This file will install Bluetooth link keys for
; the Microsoft Bluetooth stack.
;
; Edit this file to suit your needs, then save it,
; right-click the file icon and select \"Install\".
;
; The following lines specify for which device/adapter pair
; a link key is installed.
; Simply remove the lines of the link keys that you don't
; want to import.

[DefaultInstall.NT]
AddReg=BaseKeyTree

""")

for inf in keyList:
    writeOut("AddReg=DEV-"+inf["dev"]+"-"+inf["if"]+"\n")

writeOut("""\

; ----------- End of user modifiable section -------------


[BaseKeyTree]
HKLM,%bthport%\Keys,,,,

[BaseKeyTree.security]
"D:AR(A;CI;GRGW;;;PU)(A;CI;GRGW;;;LS)"

[Strings]
bthport="SYSTEM\CurrentControlSet\Services\BTHPORT\Parameters"

""")

for inf in keyList:
    writeOut("[DEV-" + inf["dev"] + "-" + inf["if"] + "]\n")
    writeOut("HKLM,%bthport%\\Keys\\" + inf["if"])
    writeOut(",\"" + inf["dev"] + "\",0x00000001," + inf["key"] + "\n\n")

outFile.close()
print "BlueZ link keys exported to "+outFileName

