Example #1
0
    def stringReceived(self, data):
        message = SecureMessage()

        try:
            message.populate(data)
        except PopulationError:
            logger.warning("Received Message discarded due to error")
            return

        if self.decryptOnReceive and message.encrypted:
            myKey = app.keyManager.getMyKey()
            message.decrypt(myKey)

        if self.validateSignatureOnReceive:
            if message.signed:
                if not message.validateSignature():
                    logger.warning("Invalid Signature on received message... %s" % self)
                    # return
            else:
                logger.warning("No signature found on message, discarding...")

        if logger.enabled['network']:
            logger.network("\nReceived Message:\n" + message.dump(indent = 4))
            logger.split()

        # Call messageReceived which is to be implemented by user
        self.messageReceived(message)
Example #2
0
    def _setIndex(self, message):
        try:
            encPair = message['pair']
            cert = message['certificate']
            try:
                sessionKey = self.factory.authNode.sessionKeys[cert]
            except KeyError:
                return self.factory.fail("Requested to set index for an unregistered certificate")
            
            pairString = sessionKey.decrypt(encPair)

            try:
                # logger.special(pairString)
                #pairString = pairString[0:pairString.index('}')+1]
                pair = json.loads(pairString)
            except ValueError as e:
                logger.warning("Invalid JSON as cert/index pair, discarding message...")
                logger.warning(e.message, False)
                return

            if pair['certificate'] != cert:
                logger.warning("Encrypted certificate doesn't match client's certificte, discarding message...")
                return

            logger.info("Index set for client")
            logger.verbose("Index: %s" % pair['index'], False)
            logger.verbose("Session Key: %s" % sessionKey.hex(), False)

            self.factory.authNode.indices[cert] = pair['index']
            logger.split()
        except KeyError as e:
            return self.factory.fail("Get-Session-Key no: '%s' field found in message" % e)
Example #3
0
    def _requestTable(self, message):
        try:
            if message.sender != 'collector':
                return self.factory.fail("Unauthorized request for table by '%s'" % message.sender)
            if not message.signed:
                return self.factory.fail("Table Request message must be signed by collector")
            if not message.validateSignature():
                return self.factory.fail("Invalid signature on Table Request message")

            encKey = message['encrypted-session-key']
            myKey = app.keyManager.getMyKey()

            keyHex = myKey.privateEncrypt(encKey)
            key = SessionKey(int(keyHex, 16))
            logger.debug("Received session key from collector:")
            logger.debug(keyHex, False)

            table = self.factory.authNode.generateTable()
            encTable = key.encrypt(json.dumps(table))

            message = SecureMessage()
            message['encrypted-table'] = encTable
            message.sign()

            logger.split()
            self.sendMessage(message)


        except KeyError as e:
            return self.factory.fail("Get-Session-Key no: '%s' field found in message" % e)
Example #4
0
    def endElections(self):
        host = app.config.get("authority-host")
        port = app.config.get("authority-port")

        factory = AuthorityFactory(self)

        logger.split()
        logger.verbose("Connecting to Authority...")
        reactor.connectTCP(host, port, factory)
Example #5
0
    def sendCertToAuth(self, cert):
        host = app.config.get("authority-host")
        port = app.config.get("authority-port")

        d = Deferred()
        factory = Authority2Factory(cert, d)

        logger.split()
        logger.verbose("Connecting to Authority...")
        reactor.connectTCP(host, port, factory)
        return d
Example #6
0
    def sendVoteToCollector(self):
        logger.split()
        self.vote = vote = raw_input("Please Enter Vote Number: ")
        
        host = app.config.get("collector-host")
        port = app.config.get("collector-port")

        d = Deferred()
        factory = CollectorFactory(self.sessionKey, self.vote, d)

        logger.split()
        logger.verbose("Connecting to Collector...")
        reactor.connectTCP(host, port, factory)
        return d
Example #7
0
File: app.py Project: ha-D/netsec
def initKeys():
    # Initialize KeyManager
    keyManager = app.keyManager
    keyParser  = KeyParser()

    # Read public keys
    keyDir = app.config.get("public-key-directory")
    for f in os.listdir(keyDir):
        path = os.path.join(keyDir, f)
        name = f.replace('.pub', '')
        key = keyParser.readPublicKey(path)
        keyManager.addPublicKey(name, key)
        logger.debug("Public key for '%s' read from %s" % (name, path))

    # Read private key
    keyPath = app.config.get("private-key-file")
    key = keyParser.readPrivateKey(keyPath)
    keyManager.setMyKey(key)
    logger.debug("Private Key read from %s" % keyPath)

    logger.split()
Example #8
0
File: app.py Project: ha-D/netsec
def initConfig(options):
    # Read configurations from file
    configFiles = options.config
    if not configFiles and os.path.isfile('config.json'):
        configFiles = ['config.json']
    if not configFiles:
        logger.warning("Couldn't find any configuration files")
    else:
        for configFile in configFiles:
            logger.info("Reading configurations from '%s'" % configFile)
            configReader = ConfigReader(configFile)
            app.config.populate(configReader.config)

    # Read extra config options
    otherOptions = dict(options._get_kwargs())
    for opt in acceptedOptions:
        uOpt = opt.replace('-', '_')
        if otherOptions[uOpt]:
            app.config[opt] = otherOptions[uOpt]

    logger.split();
Example #9
0
    def _getSessionKey(self, message):
        try:
            certificate = message['certificate']

            # Create Cert

            # This is not working
            #cert = m2c.X509.load_cert_string(certificate)
            # Stupid hack to get it working
            tmp = open('.tmp.cert', 'w')
            tmp.write(certificate)
            tmp.close()
            cert = m2c.X509.load_cert('.tmp.cert')

            if not self.factory.authNode.validateCert(cert):
                logger.info("Invalid Certificate received from %s" % self.transport.getPeer())
                reply = SecureMessage()
                reply['status'] = 'invalid'
            else:
                logger.verbose("Certificate validated")
                reply = SecureMessage()
                reply['status'] = 'ok'

                sessionKey = self.factory.authNode.generateSessionKey(cert)

                logger.verbose("Generated session key '%s'" % sessionKey.hex())
                logger.verbose("Sending session key to client..")

                publicKeyPem = cert.get_pubkey().get_rsa().as_pem()
                keyParser = KeyParser()
                publicKey = keyParser.parsePemPublic(publicKeyPem)
                encSessionKey = publicKey.publicEncrypt(sessionKey.hex())

                reply['encrypted-session-key'] = encSessionKey
            logger.split()
            self.sendMessage(reply.sign())

        except KeyError as e:
            return self.factory.fail("Get-Session-Key no: '%s' field found in message" % e)
Example #10
0
    def messageReceived(self, message):
        logger.debug("Message received from Collector")

        try:
            if message.action == 'set-index':
                index = message['index']

                logger.info("Index received from Collector:")
                logger.verbose(index, False)

                self.factory.receivedIndex(index)

            elif message.action == 'announce-results':
                voteCount = message['vote-count']
                myVote = message['your-vote']

                mVote = None

                logger.split().split()
                logger.info("Election Results:")
                for vote in voteCount:
                    if not mVote or voteCount[vote] > mVote:
                        mVote = voteCount[vote]
                for vote in voteCount:
                    if voteCount[vote] == mVote:
                        logger.extraspecial("%5s: %s (%d)" % (vote, '#'*voteCount[vote], voteCount[vote]), False)
                    else:
                        logger.special("%5s: %s (%d)" % (vote, '#'*voteCount[vote], voteCount[vote]), False)

                logger.split()

                logger.info("Your Vote:")
                logger.special("  Index: %s" % myVote['index'])
                logger.special("   Vote: %s" % myVote['vote'])

                reactor.stop()
        except KeyError as e:
            return self.factory.fail("Malformed message received from Collector. No '%s' field" % e)
Example #11
0
    def countVotes(self, indexTable):
        logger.split()
        logger.verbose("Counting votes")

        logger.split()
        logger.info("Election Results:", False)
        logger.split()

        voteCount = {}
        for index in indexTable:
            # index = int(ind)
            key = SessionKey(int(indexTable[index], 16))
            vote = key.decrypt(self.votes[index])
            logger.special("%7s: %s" % (index, vote), False)
            if vote in voteCount:
                voteCount[vote] += 1
            else:
                voteCount[vote] = 1


        logger.split().split()

        mVote = None
        for vote in voteCount:
            if not mVote or voteCount[vote] > mVote:
                mVote = voteCount[vote]
        for vote in voteCount:
            if voteCount[vote] == mVote:
                logger.extraspecial("%5s: %s (%d)" % (vote, '#'*voteCount[vote], voteCount[vote]), False)
            else:
                logger.special("%5s: %s (%d)" % (vote, '#'*voteCount[vote], voteCount[vote]), False)

        logger.split()
        # Send results to clients
        for client in self.clients:
            client['connection'].sendResults(voteCount=voteCount, index=client['index'], vote=client['vote'])
Example #12
0
 def connectionMade(self):
     logger.split()
     logger.debug("Connection established with client %s" % self.transport.getPeer())
Example #13
0
File: ca.py Project: ha-D/netsec
 def connectionMade(self):
     peer = self.transport.getPeer()
     logger.split()
     logger.debug("<%s:%s> Connection established" % (peer.host, peer.port))