Esempio n. 1
0
    def execute_route(self, meta_data, request_pdu):
        """ Execute configured route based on requests meta data and request
        PDU.

        :param meta_data: A dict with meta data. It must at least contain
            key 'unit_id'.
        :param request_pdu: A bytearray containing request PDU.
        :return: A bytearry containing reponse PDU.
        """
        try:
            function = create_function_from_request_pdu(request_pdu)
            results =\
                function.execute(meta_data['unit_id'], self.server.route_map)

            try:
                # ReadFunction's use results of callbacks to build response
                # PDU...
                return function.create_response_pdu(results)
            except TypeError:
                # ...other functions don't.
                return function.create_response_pdu()
        except ModbusError as e:
            function_code = get_function_code_from_request_pdu(request_pdu)
            return pack_exception_pdu(function_code, e.error_code)
        except Exception as e:
            log.exception('Could not handle request: {0}.'.format(e))
            function_code = get_function_code_from_request_pdu(request_pdu)

            return pack_exception_pdu(function_code,
                                      ServerDeviceFailureError.error_code)
Esempio n. 2
0
    def execute_route(self, meta_data, request_pdu):
        """ Execute configured route based on requests meta data and request
        PDU.

        :param meta_data: A dict with meta data. It must at least contain
            key 'unit_id'.
        :param request_pdu: A bytearray containing request PDU.
        :return: A bytearry containing reponse PDU.
        """
        try:
            function = create_function_from_request_pdu(request_pdu)
            results =\
                function.execute(meta_data['unit_id'], self.route_map)

            try:
                # ReadFunction's use results of callbacks to build response
                # PDU...
                return function.create_response_pdu(results)
            except TypeError:
                # ...other functions don't.
                return function.create_response_pdu()
        except ModbusError as e:
            function_code = get_function_code_from_request_pdu(request_pdu)
            return pack_exception_pdu(function_code, e.error_code)
        except Exception as e:
            log.exception('Could not handle request: {0}.'.format(e))
            function_code = get_function_code_from_request_pdu(request_pdu)

            return pack_exception_pdu(function_code,
                                      ServerDeviceFailureError.error_code)
Esempio n. 3
0
 def handle(self):
     try:
         request_adu = self.request.recv(1024)
         response_adu = self.process(request_adu)
         self.respond(response_adu)
     except:
         import traceback
         log.exception('Error while handling request: {0}.'
                       .format(traceback.print_exc()))
         raise
Esempio n. 4
0
    def handle(self):
        try:
            while True:
                try:
                    mbap_header = recv_exactly(self.request.recv, 7)
                    remaining = self.get_meta_data(mbap_header)['length'] - 1
                    request_pdu = recv_exactly(self.request.recv, remaining)
                except ValueError:
                    return

                response_adu = self.process(mbap_header + request_pdu)
                self.respond(response_adu)
        except:
            log.exception('Error while handling request')
            raise
Esempio n. 5
0
    def handle(self):
        try:
            while True:
                request_adu = self.request.recv(1024)

                # When client terminates connection length of request_adu is 0.
                if len(request_adu) == 0:
                    return

                response_adu = self.process(request_adu)
                self.respond(response_adu)
        except:
            import traceback
            log.exception('Error while handling request: {0}.'
                          .format(traceback.print_exc()))
            raise
Esempio n. 6
0
    def handle(self):
        logging.debug("handle")
        try:
            while True:
                try:
                    mbap_header = recv_exactly(self.request.recv, 7)
                    remaining = self.get_meta_data(mbap_header)['length'] - 1
                    request_pdu = recv_exactly(self.request.recv, remaining)
                except ValueError:
                    return

                response_adu = self.process(mbap_header + request_pdu)
                self.respond(response_adu)
        except:
            import traceback
            log.exception('Error while handling request: {0}.'.format(
                traceback.print_exc()))
            raise
Esempio n. 7
0
    def process(self, request_adu):
        """ Process request ADU and return response.

        :param request_adu: A bytearray containing the ADU request.
        :return: A bytearray containing the response of the ADU request.
        """
        log.debug('Lenght of received ADU is {0}.'.format(len(request_adu)))
        log.info('<-- {0} - {1}.'.format(self.client_address[0],
                 hexlify(request_adu)))
        try:
            transaction_id, protocol_id, _, unit_id = \
                unpack_mbap(request_adu[:7])

            function = function_factory(request_adu[7:])
            results = function.execute(unit_id, self.server.route_map)

            try:
                # ReadFunction's use results of callbacks to build response
                # PDU...
                response_pdu = function.create_response_pdu(results)
            except TypeError:
                # ...other functions don't.
                response_pdu = function.create_response_pdu()
        except ModbusError as e:
            function_code = get_function_code_from_request_pdu(request_adu[7:])
            response_pdu = pack_exception_pdu(function_code, e.error_code)
        except Exception as e:
            log.exception('Could not handle request: {0}.'.format(e))
            function_code = get_function_code_from_request_pdu(request_adu[7:])
            response_pdu = \
                pack_exception_pdu(function_code,
                                   ServerDeviceFailureError.error_code)

        response_mbap = pack_mbap(transaction_id, protocol_id,
                                  len(response_pdu) + 1, unit_id)

        log.debug('Response MBAP {0}'.format(response_mbap))
        log.debug('Response PDU {0}'.format(response_pdu))

        response_adu = response_mbap + response_pdu

        return response_adu
Esempio n. 8
0
    def handle(self):
        try:
            while True:
                try:
                        
                    message=self.request.recv(1024)
                    if not message: break

                    salt_key = b'6ea920bb0e8ad58ebf2dbf5634f14f26'
                    salt_iv = b'4893ed0de93bf86871845c06e2bef676'

                    def readfile ( file ) :
                        with open (file ,'rb') as f:
                            content = f.read ()
                            f.close()
                            return content

                    dh = readfile("umodbus/secrets/my_dh_file")

                    backend = default_backend()

                    hkdf_key = HKDF(
                        algorithm=hashes.SHA256(),
                        length=16,
                        salt=ba.unhexlify(salt_key),
                        info=b"keygen",
                        backend=backend)

                    hkdf_iv = HKDF(
                        algorithm=hashes.SHA256(),
                        length=16,
                        salt=ba.unhexlify(salt_iv),
                        info=b"ivgen",
                        backend=backend)

                    key = hkdf_key.derive(dh)
                    iv = hkdf_iv.derive(dh)

                    aes = algorithms.AES(key)
                    mode = modes.CBC(iv)

                    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)


                    hash_received = message[(len(message)-32):len(message)]
                    message = message[0:(len(message)-32)]
                    



                    decryptor = cipher.decryptor()
                    dec_msg = decryptor.update(message) + decryptor.finalize()

                    unpadder = padding.PKCS7(128).unpadder()
                    dec_msg = unpadder.update(dec_msg)
                    dt = dec_msg + unpadder.finalize()

                    dt = ba.unhexlify(dt)

                    h = hmac.HMAC(key, hashes.SHA256(), backend=backend)
                    h.update(dt)

                    hash_generated = h.finalize()
                    # print("hash rec:", hash_received)
                    # print("hash gen:", hash_generated)

                    if(hash_generated != hash_received):
                        print("hash mismatch! time to abort...")
                        break
                    else:
                        print("hash matched!")


               
                    #At this Point the message from the client has been received and is ready to be processed 
                    mbap_header = dt[0:7]
                    remaining = self.get_meta_data(mbap_header)['length'] - 1
                    request_pdu = dt[7:8+remaining]

                      
                except ValueError:
                    return

                response_adu = self.process(mbap_header + request_pdu)

                #At this point the responce to the message  has been structured and is ready to be send to the client
                self.respond(response_adu)
        except:
            import traceback
            log.exception('Error while handling request: {0}.'
                          .format(traceback.print_exc()))
        raise
Esempio n. 9
0
    def handle(self):
        try:
            helloMsgServer = 'server'
            helloMsgClient = 'client'

            serverkey = RSA.generate(2048)
            serverpbkey = serverkey.publickey().exportKey('PEM').decode(
                'ascii')
            serverprkey = serverkey.exportKey('PEM').decode('ascii')
            print('\nServer Public keys:\n\n', serverpbkey,
                  '\n\n\nRSA server private key:\n\n', serverprkey)
            sign = signData(helloMsgServer.encode(), serverprkey)
            print("\n\nSign:\n\n", sign)
            message = str(serverpbkey) + ";" + str(sign)
            print("\n\nRSA Message:\n\n", message)
            self.request.sendall(message.encode())

            rsaResponse = self.request.recv(3072).strip()
            rsaMsg = rsaResponse.decode()
            clientpbkey = rsaMsg.split(';')[0]
            signRcvd = rsaMsg.split(';')[1]
            verify = verifySign(helloMsgClient.encode(), clientpbkey, signRcvd)
            if verify:
                print("\n\n---------Received Client RSA Public Key---------\n")
            else:
                raise Exception(
                    "\nClient Authentication Failure. RSA public key and sign don't match\n"
                )
            print('\nRSA client pub key\n\n', clientpbkey)

            print(
                "\n\n****************************RSA Exchange Completes and Authentication Done***************************"
            )
            #self.state = 0

            dh_params = load_dh_params()
            srkey = generate_dh_prvkey(dh_params)

            response = dh_params.parameter_bytes(Encoding.PEM,
                                                 ParameterFormat.PKCS3)
            self.request.sendall(response)
            self.data = self.request.recv(3072).strip()
            print(
                "\n\n****************************Received Client's public Key****************************\n"
            )
            if bytearray(self.data)[0:18] == b'Client public key:':
                # now we convert the binary message to bytearray so we can choose the public key
                # part of it and use key serialization method to turn it into an object
                client_pubkey = load_pem_public_key(
                    bytes(bytearray(self.data)[18:]), default_backend())
                # now if the public key is loaded (we might not get to this point otherwise,
                # something for you to check!)
                if client_pubkey:
                    # client key is valid so we generate our own from the parameters
                    server_keypair = srkey

                    # we   will send the public key to the client and we need to convert it to
                    # binary to send over the network
                    response = b'Server public key:' + server_keypair.public_key(
                    ).public_bytes(Encoding.PEM,
                                   PublicFormat.SubjectPublicKeyInfo)

                    session_key = server_keypair.exchange(client_pubkey)
                    #self.state = 0
                    self.request.sendall(response)
                    print(
                        "\n****************************Shared Secret key is generated***************************\n"
                    )
                    print(
                        "\n**********************DH Exchange Completes and Session Established**********************"
                    )
                else:
                    # if we get here the client key is not right
                    response = b'Invalid client public key, hanging up'
                    self.request.sendall(response)
                    return

            iv = 'nvXIK5RtUZpZQdJD'
            while True:
                try:
                    message = self.request.recv(1024)
                    if not message:
                        break
                    #print('\niv',iv)
                    self.iv = iv
                    print('\nCipher + Hash:\t\t-------->\t', (message))
                    obtained_key = hkdf_function(session_key)
                    self.obtained_key = obtained_key
                    plain, digest = aes_decrypt(message, obtained_key, iv)
                    print('\nDerived key:\t\t-------->\t', (obtained_key))
                    localDigest = getHash(plain)
                    verify = verifyHash(digest, localDigest)
                    if verify == False:
                        break
                    print("\nHash is verified.")
                    mbap_header = plain[0:7]
                    remaining = self.get_meta_data(mbap_header)['length'] - 1
                    request_pdu = plain[7:8 + remaining]

                except ValueError:
                    print("issue")
                    return

                response_adu = self.process(mbap_header + request_pdu)
                print("\nResponse ADU:\t\t-------->\t", (response_adu))
                #At this point the responce to the message  has been structured and is ready to be send to the client
                self.respond(response_adu)
        except:
            import traceback
            log.exception('Error while handling request: {0}.'.format(
                traceback.print_exc()))
        raise