# Path: certificate.py
# def generateCertificates(DevicePublicKey):
#     # Generate random 2048-bit private and public keys
#     keyPairGenerator = KeyPairGenerator.getInstance("RSA")
#     keyPairGenerator.initialize(2048)
#     keyPair = keyPairGenerator.genKeyPair()
# 
#     # Make it valid for 10 years
#     calendar = Calendar.getInstance()
#     startDate = calendar.getTime()
#     calendar.add(Calendar.YEAR, 10)
#     expiryDate = calendar.getTime()
# 
#     certGen = X509V1CertificateGenerator()
#     dnName = X500Principal("CN=pyMobileDevice Self-Signed CA Certificate")
# 
#     certGen.setSerialNumber(BigInteger.ONE)
#     certGen.setIssuerDN(dnName)
#     certGen.setNotBefore(startDate)
#     certGen.setNotAfter(expiryDate)
#     certGen.setSubjectDN(dnName)  # subject = issuer
#     certGen.setPublicKey(keyPair.getPublic())
#     certGen.setSignatureAlgorithm("SHA1withRSA")
# 
#     #Load PKCS#1 RSA Public Key
#     spec = X509EncodedKeySpec(convertPKCS1toPKCS8pubKey(DevicePublicKey))
#     pubKey = KeyFactory.getInstance("RSA").generatePublic(spec)
# 
#     hostCertificate = "-----BEGIN CERTIFICATE-----\n" + certGen.generate(keyPair.getPrivate(), "BC").getEncoded().tostring().encode("base64") + "-----END CERTIFICATE-----\n"
# 
#     hostPrivateKey = "-----BEGIN PRIVATE KEY-----\n" + keyPair.getPrivate().getEncoded().tostring().encode("base64") + "-----END PRIVATE KEY-----\n"
# 
#     certGen.setPublicKey(pubKey)
#     dnName = X500Principal("CN=pyMobileDevice Self-Signed Device Certificate")
#     certGen.setSubjectDN(dnName)
# 
#     deviceCertificate = "-----BEGIN CERTIFICATE-----\n" + certGen.generate(keyPair.getPrivate(), "BC").getEncoded().tostring().encode("base64") + "-----END CERTIFICATE-----\n"
# 
#     return hostCertificate, hostPrivateKey, deviceCertificate
# 
# Path: plist_service.py
# class PlistService(object):
#     def __init__(self, port, udid=None):
#         self.port = port
#         self.connect(udid)
# 
#     def connect(self, udid=None):
#         mux = usbmux.USBMux()
#         mux.process(5.0)
#         dev = None
# 
#         while not dev and mux.devices:
#             if udid:
#                 for d in mux.devices:
#                     if d.serial == udid:
#                         dev = d
#                         print "Connecting to device: " + dev.serial
#             else:
#                 dev = mux.devices[0]
#                 print "Connecting to device: " + dev.serial
# 
#         try:
#             self.socket = mux.connect(dev, self.port)
#         except:
#             raise Exception("Connection to device port %d failed" % self.port)
#         return dev.serial
# 
#     def close(self):
#         self.socket.close()
# 
#     def recv(self, len=4096):
#         return self.socket.recv(len)
# 
#     def send(self, data):
#         return self.socket.send(data)
# 
#     def recv_exact(self, l):
#         data = ""
#         while l > 0:
#             d = self.recv(l)
#             if not d or len(d) == 0:
#                 break
#             data += d
#             l -= len(d)
#         return data
# 
#     def recv_raw(self):
#         l = self.recv(4)
#         if not l or len(l) != 4:
#             return
#         l = struct.unpack(">L", l)[0]
#         return self.recv_exact(l)
# 
#     def send_raw(self, data):
#         return self.send(struct.pack(">L", len(data)) + data)
# 
#     def recvPlist(self):
#         payload = self.recv_raw()
#         #print '<<<<<<<<',payload
#         if not payload:
#             return
#         if payload.startswith("bplist00"):
#             return BPlistReader(payload).parse()
#         elif payload.startswith("<?xml"):
#             #HAX lockdown HardwarePlatform with null bytes
#             payload = sub('[^\w<>\/ \-_0-9\"\'\\=\.\?\!\+]+', '', payload.decode('utf-8')).encode('utf-8')
#             return plistlib.readPlistFromString(payload)
#         else:
#             raise Exception("recvPlist invalid data : %s" % payload[:100].encode("hex"))
# 
#     def sendPlist(self, d):
#         payload = plistlib.writePlistToString(d)
#         #print '>>>>',payload
#         l = struct.pack(">L", len(payload))
#         self.send(l + payload)
# 
#     def sendRequest(self, plist):
#         self.sendPlist(plist)
#         return self.recvPlist()
# 
#     def start_ssl(self, keyfile):
#         if os._name == 'nt':
#             self.socket = usbmux.SSLSocket(self.socket.sock._sock._get_jsocket(), keyfile)
#         else:
#             self.socket = usbmux.SSLSocket(self.socket.sock, keyfile)


import platform
import plistlib
import uuid
from usbmux import usbmux
from util import readHomeFile, writeHomeFile
from certificate import generateCertificates
from plist_service import PlistService
                pair_record['EscrowBag'] = Pair['EscrowBag']
            writeHomeFile(HOMEFOLDER, '%s.plist' % self.udid, plistlib.writePlistToString(pair_record))
        else:
            raise PairingError

    def getValue(self, domain=None, key=None):
        request = {'Request': 'GetValue', 'Label': self.label}

        if domain:
            request['Domain'] = domain
        if key:
            request['Key'] = key
        response = self.service.sendRequest(request)
        if response:
            r = response.get('Value')
            if hasattr(r, 'data'):
                return r.data
            return r

    def startService(self, name):
        if not self.paired:
            raise NotPairedError

        StartService = self.service.sendRequest({
            'Request': 'StartService',
            'Service': name
            })

        if not StartService or 'Error' in StartService:
            raise StartServiceError(StartService['Error'])

# Path: certificate.py
# def generateCertificates(DevicePublicKey):
#     # Generate random 2048-bit private and public keys
#     keyPairGenerator = KeyPairGenerator.getInstance("RSA")
#     keyPairGenerator.initialize(2048)
#     keyPair = keyPairGenerator.genKeyPair()
# 
#     # Make it valid for 10 years
#     calendar = Calendar.getInstance()
#     startDate = calendar.getTime()
#     calendar.add(Calendar.YEAR, 10)
#     expiryDate = calendar.getTime()
# 
#     certGen = X509V1CertificateGenerator()
#     dnName = X500Principal("CN=pyMobileDevice Self-Signed CA Certificate")
# 
#     certGen.setSerialNumber(BigInteger.ONE)
#     certGen.setIssuerDN(dnName)
#     certGen.setNotBefore(startDate)
#     certGen.setNotAfter(expiryDate)
#     certGen.setSubjectDN(dnName)  # subject = issuer
#     certGen.setPublicKey(keyPair.getPublic())
#     certGen.setSignatureAlgorithm("SHA1withRSA")
# 
#     #Load PKCS#1 RSA Public Key
#     spec = X509EncodedKeySpec(convertPKCS1toPKCS8pubKey(DevicePublicKey))
#     pubKey = KeyFactory.getInstance("RSA").generatePublic(spec)
# 
#     hostCertificate = "-----BEGIN CERTIFICATE-----\n" + certGen.generate(keyPair.getPrivate(), "BC").getEncoded().tostring().encode("base64") + "-----END CERTIFICATE-----\n"
# 
#     hostPrivateKey = "-----BEGIN PRIVATE KEY-----\n" + keyPair.getPrivate().getEncoded().tostring().encode("base64") + "-----END PRIVATE KEY-----\n"
# 
#     certGen.setPublicKey(pubKey)
#     dnName = X500Principal("CN=pyMobileDevice Self-Signed Device Certificate")
#     certGen.setSubjectDN(dnName)
# 
#     deviceCertificate = "-----BEGIN CERTIFICATE-----\n" + certGen.generate(keyPair.getPrivate(), "BC").getEncoded().tostring().encode("base64") + "-----END CERTIFICATE-----\n"
# 
#     return hostCertificate, hostPrivateKey, deviceCertificate
# 
# Path: plist_service.py
# class PlistService(object):
#     def __init__(self, port, udid=None):
#         self.port = port
#         self.connect(udid)
# 
#     def connect(self, udid=None):
#         mux = usbmux.USBMux()
#         mux.process(5.0)
#         dev = None
# 
#         while not dev and mux.devices:
#             if udid:
#                 for d in mux.devices:
#                     if d.serial == udid:
#                         dev = d
#                         print "Connecting to device: " + dev.serial
#             else:
#                 dev = mux.devices[0]
#                 print "Connecting to device: " + dev.serial
# 
#         try:
#             self.socket = mux.connect(dev, self.port)
#         except:
#             raise Exception("Connection to device port %d failed" % self.port)
#         return dev.serial
# 
#     def close(self):
#         self.socket.close()
# 
#     def recv(self, len=4096):
#         return self.socket.recv(len)
# 
#     def send(self, data):
#         return self.socket.send(data)
# 
#     def recv_exact(self, l):
#         data = ""
#         while l > 0:
#             d = self.recv(l)
#             if not d or len(d) == 0:
#                 break
#             data += d
#             l -= len(d)
#         return data
# 
#     def recv_raw(self):
#         l = self.recv(4)
#         if not l or len(l) != 4:
#             return
#         l = struct.unpack(">L", l)[0]
#         return self.recv_exact(l)
# 
#     def send_raw(self, data):
#         return self.send(struct.pack(">L", len(data)) + data)
# 
#     def recvPlist(self):
#         payload = self.recv_raw()
#         #print '<<<<<<<<',payload
#         if not payload:
#             return
#         if payload.startswith("bplist00"):
#             return BPlistReader(payload).parse()
#         elif payload.startswith("<?xml"):
#             #HAX lockdown HardwarePlatform with null bytes
#             payload = sub('[^\w<>\/ \-_0-9\"\'\\=\.\?\!\+]+', '', payload.decode('utf-8')).encode('utf-8')
#             return plistlib.readPlistFromString(payload)
#         else:
#             raise Exception("recvPlist invalid data : %s" % payload[:100].encode("hex"))
# 
#     def sendPlist(self, d):
#         payload = plistlib.writePlistToString(d)
#         #print '>>>>',payload
#         l = struct.pack(">L", len(payload))
#         self.send(l + payload)
# 
#     def sendRequest(self, plist):
#         self.sendPlist(plist)
#         return self.recvPlist()
# 
#     def start_ssl(self, keyfile):
#         if os._name == 'nt':
#             self.socket = usbmux.SSLSocket(self.socket.sock._sock._get_jsocket(), keyfile)
#         else:
#             self.socket = usbmux.SSLSocket(self.socket.sock, keyfile)


# Path: lockdown.py
import platform
import plistlib
import uuid
from usbmux import usbmux
from util import readHomeFile, writeHomeFile
from certificate import generateCertificates
from plist_service import PlistService

                pair_record['EscrowBag'] = Pair['EscrowBag']
            writeHomeFile(HOMEFOLDER, '%s.plist' % self.udid, plistlib.writePlistToString(pair_record))
        else:
            raise PairingError

    def getValue(self, domain=None, key=None):
        request = {'Request': 'GetValue', 'Label': self.label}

        if domain:
            request['Domain'] = domain
        if key:
            request['Key'] = key
        response = self.service.sendRequest(request)
        if response:
            r = response.get('Value')
            if hasattr(r, 'data'):
                return r.data
            return r

    def startService(self, name):
        if not self.paired:
            raise NotPairedError

        StartService = self.service.sendRequest({
            'Request': 'StartService',
            'Service': name
            })

        if not StartService or 'Error' in StartService:
            raise StartServiceError(StartService['Error'])

        return PlistService(StartService['Port'])