コード例 #1
0
def config_set_config_request(security_ctx, ssid, passphrase):
    # Form protobuf request packet for SetConfig command
    cmd = proto.wifi_config_pb2.WiFiConfigPayload()
    cmd.msg = proto.wifi_config_pb2.TypeCmdSetConfig
    cmd.cmd_set_config.ssid = str_to_bytes(ssid)
    cmd.cmd_set_config.passphrase = str_to_bytes(passphrase)
    enc_cmd = security_ctx.encrypt_data(cmd.SerializeToString())
    print_verbose(security_ctx,
                  f'Client -> Device (SetConfig cmd): 0x{enc_cmd.hex()}')
    return enc_cmd.decode('latin-1')
コード例 #2
0
 def update_allocation(self):
     reserve = utils.str_to_bytes(
         self.config.get(self.context, "reserve", "0"))
     size = utils.str_to_bytes(self.config.get(self.context, "size", "0"))
     if reserve:
         stat = os.statvfs(self.path)
         fs_free = stat.f_frsize * stat.f_bavail
         self.logger.debug(
             f"consumed: {self.consumption()/2**30:5.2f}, free: {fs_free/2**30:5.2f}, reserve: {reserve/2**30:5.2f}"
         )
         self.allocation = max(0, self.consumption() + fs_free - reserve)
     elif size:
         self.allocation = size
     assert self.allocation, "Can't start; define 'size' or 'reserve'"
コード例 #3
0
ファイル: security2.py プロジェクト: jkearins/esp-idf
    def setup1_response(self, response_data: bytes) -> Any:
        # Interpret SessionResp1 response packet
        setup_resp = proto.session_pb2.SessionData()
        setup_resp.ParseFromString(str_to_bytes(response_data))
        # Ensure security scheme matches
        if setup_resp.sec_ver == proto.session_pb2.SecScheme2:
            # Read encrypyed device proof string
            device_proof = setup_resp.sec2.sr1.device_proof
            self._print_verbose(f'Device Proof:\t0x{device_proof.hex()}')
            self.srp6a_ctx.verify_session(device_proof)
            if not self.srp6a_ctx.authenticated():
                raise RuntimeError('Failed to verify device proof')
        else:
            raise RuntimeError('Unsupported security protocol')

        # Getting the shared secret
        shared_secret = self.srp6a_ctx.get_session_key()
        self._print_verbose(f'Shared Secret:\t0x{shared_secret.hex()}')

        # Using the first 256 bits of a 512 bit key
        session_key = shared_secret[:AES_KEY_LEN]
        self._print_verbose(f'Session Key:\t0x{session_key.hex()}')

        # 96-bit nonce
        self.nonce = setup_resp.sec2.sr1.device_nonce
        if self.nonce is None:
            raise RuntimeError('Received invalid nonce from device!')
        self._print_verbose(f'Nonce:\t0x{self.nonce.hex()}')

        # Initialize the encryption engine with Shared Key and initialization vector
        self.cipher = AESGCM(session_key)
        if self.cipher is None:
            raise RuntimeError(
                'Failed to initialize AES-GCM cryptographic engine!')
コード例 #4
0
def config_get_status_response(security_ctx, response_data):
    # Interpret protobuf response packet from GetStatus command
    decrypted_message = security_ctx.decrypt_data(str_to_bytes(response_data))
    cmd_resp1 = proto.wifi_config_pb2.WiFiConfigPayload()
    cmd_resp1.ParseFromString(decrypted_message)
    print_verbose(security_ctx, f'CmdGetStatus type: {str(cmd_resp1.msg)}')
    print_verbose(
        security_ctx,
        f'CmdGetStatus status: {str(cmd_resp1.resp_get_status.status)}')

    if cmd_resp1.resp_get_status.sta_state == 0:
        print('==== WiFi state: Connected ====')
        return 'connected'
    elif cmd_resp1.resp_get_status.sta_state == 1:
        print('++++ WiFi state: Connecting... ++++')
        return 'connecting'
    elif cmd_resp1.resp_get_status.sta_state == 2:
        print('---- WiFi state: Disconnected ----')
        return 'disconnected'
    elif cmd_resp1.resp_get_status.sta_state == 3:
        print('---- WiFi state: Connection Failed ----')
        if cmd_resp1.resp_get_status.fail_reason == 0:
            print('---- Failure reason: Incorrect Password ----')
        elif cmd_resp1.resp_get_status.fail_reason == 1:
            print('---- Failure reason: Incorrect SSID ----')
        return 'failed'
    return 'unknown'
コード例 #5
0
 def setup0_response(self, response_data):
     # Interpret protocomm security0 response packet
     setup_resp = proto.session_pb2.SessionData()
     setup_resp.ParseFromString(str_to_bytes(response_data))
     # Check if security scheme matches
     if setup_resp.sec_ver != proto.session_pb2.SecScheme0:
         raise RuntimeError('Incorrect security scheme')
コード例 #6
0
ファイル: server.py プロジェクト: dKosarevsky/geekbrains
def send_messages(messages, w, clients):
    for sock in w:
        for message in messages:
            try:
                sock.send(utils.str_to_bytes(message))
            except:
                sock.close()
                clients.remove(sock)
コード例 #7
0
    def find_cities(self):
        if not self.is_login:
            self.client.sendall(b'Ban phai dang nhap')
            return

        data = self.weatherManager.get_cities()
        data = str_to_bytes(data)
        self.client.sendall(data)
コード例 #8
0
ファイル: wifi_scan.py プロジェクト: jkearins/esp-idf
def scan_start_response(security_ctx, response_data):
    # Interpret protobuf response packet from ScanStart command
    dec_resp = security_ctx.decrypt_data(str_to_bytes(response_data))
    resp = proto.wifi_scan_pb2.WiFiScanPayload()
    resp.ParseFromString(dec_resp)
    print_verbose(security_ctx, f'ScanStart status: 0x{str(resp.status)}')
    if resp.status != 0:
        raise RuntimeError
コード例 #9
0
ファイル: wifi_scan.py プロジェクト: jkearins/esp-idf
def scan_status_response(security_ctx, response_data):
    # Interpret protobuf response packet from ScanStatus command
    dec_resp = security_ctx.decrypt_data(str_to_bytes(response_data))
    resp = proto.wifi_scan_pb2.WiFiScanPayload()
    resp.ParseFromString(dec_resp)
    print_verbose(security_ctx, f'ScanStatus status: 0x{str(resp.status)}')
    if resp.status != 0:
        raise RuntimeError
    return {'finished': resp.resp_scan_status.scan_finished, 'count': resp.resp_scan_status.result_count}
コード例 #10
0
    def register(self):
        username = input('Nhap username: '******'Nhap password: '******'register {} {}'.format(username, password)

        self.client.sendall(str_to_bytes(data))
        data = client.recv(SERVER_DATA_LENGTH)
        data = bytes_to_str(data)
        print(data)
コード例 #11
0
ファイル: transport_console.py プロジェクト: jkearins/esp-idf
 async def send_data(self, path, data, session_id=0):
     print('Client->Device msg :', path, session_id,
           str_to_bytes(data).hex())
     try:
         resp = input('Enter device->client msg : ')
     except Exception as err:
         print('error:', err)
         return None
     return hex_str_to_bytes(resp)
コード例 #12
0
def config_apply_config_response(security_ctx, response_data):
    # Interpret protobuf response packet from ApplyConfig command
    decrypt = security_ctx.decrypt_data(str_to_bytes(response_data))
    cmd_resp5 = proto.wifi_config_pb2.WiFiConfigPayload()
    cmd_resp5.ParseFromString(decrypt)
    print_verbose(
        security_ctx,
        f'ApplyConfig status: 0x{str(cmd_resp5.resp_apply_config.status)}')
    return cmd_resp5.resp_apply_config.status
コード例 #13
0
ファイル: esp_prov.py プロジェクト: mahavirj/esp-bootstrap
def version_match(tp, protover):
    try:
        response = utils.bytes_to_str(
            tp.send_version_data(utils.str_to_bytes(protover)))
        if response != "SUCCESS":
            return False
        return True
    except RuntimeError as e:
        print(e)
        return None
コード例 #14
0
    def find_city(self, data: str):
        if not self.is_login:
            self.client.sendall(b'Ban phai dang nhap')
            return

        items = data.split(' ')
        try:
            city_id = int(items[1])
            data = self.weatherManager.get_city(city_id)
            data = str_to_bytes(data)
            self.client.sendall(data)
        except ValueError:
            self.client.sendall(b'Du lieu khong hop le')
コード例 #15
0
ファイル: security2.py プロジェクト: jkearins/esp-idf
    def setup0_response(self, response_data: bytes) -> None:
        # Interpret SessionResp0 response packet
        setup_resp = proto.session_pb2.SessionData()
        setup_resp.ParseFromString(str_to_bytes(response_data))
        self._print_verbose(f'Security version:\t{str(setup_resp.sec_ver)}')
        if setup_resp.sec_ver != proto.session_pb2.SecScheme2:
            raise RuntimeError('Incorrect security scheme')

        # Device public key, random salt and password verifier
        device_pubkey = setup_resp.sec2.sr0.device_pubkey
        device_salt = setup_resp.sec2.sr0.device_salt

        self._print_verbose(f'Device Public Key:\t0x{device_pubkey.hex()}')
        self.client_pop_key = self.srp6a_ctx.process_challenge(
            device_salt, device_pubkey)
コード例 #16
0
    def login(self):
        username = input('Nhap username: '******'Nhap password: '******'login {} {}'.format(username, password)

        client.sendall(str_to_bytes(data))
        data = client.recv(SERVER_DATA_LENGTH)
        data = bytes_to_str(data)

        if data != SUCCESS:
            print(data)
            return
        elif username == 'admin':
            self.is_admin = True
        self.menu()
コード例 #17
0
ファイル: security2.py プロジェクト: jkearins/esp-idf
    def setup0_request(self) -> Any:
        # Form SessionCmd0 request packet using client public key
        setup_req = proto.session_pb2.SessionData()
        setup_req.sec_ver = proto.session_pb2.SecScheme2
        setup_req.sec2.msg = proto.sec2_pb2.S2Session_Command0

        setup_req.sec2.sc0.client_username = str_to_bytes(self.username)
        self.srp6a_ctx = Srp6a(self.username, self.password)
        if self.srp6a_ctx is None:
            raise RuntimeError('Failed to initialize SRP6a instance!')

        client_pubkey = long_to_bytes(self.srp6a_ctx.A)
        setup_req.sec2.sc0.client_pubkey = client_pubkey

        self._print_verbose(f'Client Public Key:\t0x{client_pubkey.hex()}')
        return setup_req.SerializeToString().decode('latin-1')
コード例 #18
0
 def test_bytes(self):
     self.assertEquals(utils.str_to_bytes("27"), 27)
     self.assertEquals(utils.str_to_bytes("27k"), 27*1024)
     self.assertEquals(utils.str_to_bytes("27T"), 27*2**40)
     self.assertEquals(utils.str_to_bytes("27mbT"), 27*2**20)
     self.assertEquals(utils.str_to_bytes("27gbT"), 27*2**30)
     self.assertEquals(utils.bytes_to_str(27*2**30), "27.000G")
     self.assertEquals(utils.bytes_to_str(27*2**30+11*2**10), "27.000G")
     self.assertEquals(utils.bytes_to_str(27*2**30+11*2**10), "27.000G")
     self.assertEquals(utils.bytes_to_str(27*2**20), "27.000M")
     self.assertEquals(utils.str_to_bytes("1.2k"), 1228)
コード例 #19
0
ファイル: security1.py プロジェクト: jkearins/esp-idf
 def setup1_response(self, response_data):
     # Interpret SessionResp1 response packet
     setup_resp = proto.session_pb2.SessionData()
     setup_resp.ParseFromString(str_to_bytes(response_data))
     # Ensure security scheme matches
     if setup_resp.sec_ver == proto.session_pb2.SecScheme1:
         # Read encrypyed device verify string
         device_verify = setup_resp.sec1.sr1.device_verify_data
         self._print_verbose(f'Device Proof:\t0x{device_verify.hex()}')
         # Decrypt the device verify string
         enc_client_pubkey = self.cipher.update(
             setup_resp.sec1.sr1.device_verify_data)
         # Match decryped string with client public key
         if enc_client_pubkey != self.client_public_key:
             raise RuntimeError('Failed to verify device!')
     else:
         raise RuntimeError('Unsupported security protocol')
コード例 #20
0
    def add_city(self):
        if not self.is_admin:
            print('Ban nhap khong hop le')
            return

        name = input('Nhap ten thanh pho: ').strip()

        if len(name) == 0:
            print('Khong duoc de trong ten')
            return

        data = 'add_city {}'.format(name)
        data = str_to_bytes(data)
        self.client.sendall(data)

        data = self.client.recv(SERVER_DATA_LENGTH)
        data = bytes_to_str(data)
        print(data)
コード例 #21
0
    def sync_native_libs_on_device(self):
        # Push missing native libs on device.
        for build_id in self.host_build_id_map:
            if build_id not in self.device_build_id_map:
                entry = self.host_build_id_map[build_id]
                self.adb.check_run(
                    ['push', entry.path, self.dir_on_device + entry.name])
        # Remove native libs not exist on host.
        for build_id in self.device_build_id_map:
            if build_id not in self.host_build_id_map:
                name = self.device_build_id_map[build_id]
                self.adb.run(['shell', 'rm', self.dir_on_device + name])
        # Push new build_id_list on device.
        with open(self.build_id_list_file, 'wb') as fh:
            for build_id in self.host_build_id_map:
                s = str_to_bytes(
                    '%s=%s\n' %
                    (build_id, self.host_build_id_map[build_id].name))
                fh.write(s)
        self.adb.check_run([
            'push', self.build_id_list_file,
            self.dir_on_device + self.build_id_list_file
        ])
        os.remove(self.build_id_list_file)

        # Push elf files without build id on device.
        for entry in self.no_build_id_file_map.values():
            target = self.dir_on_device + entry.name

            # Skip download if we have a file with the same name and size on device.
            result, output = self.adb.run_and_return_output(
                ['shell', 'ls', '-l', target],
                log_output=False,
                log_stderr=False)
            if result:
                items = output.split()
                if len(items) > 5:
                    try:
                        file_size = int(items[4])
                    except ValueError:
                        file_size = 0
                    if file_size == os.path.getsize(entry.path):
                        continue
            self.adb.check_run(['push', entry.path, target])
コード例 #22
0
 def sync_natives_libs_on_device(self):
     # Push missing native libs on device.
     for build_id in self.host_build_id_map:
         if build_id not in self.device_build_id_map:
             entry = self.host_build_id_map[build_id]
             self.adb.check_run(['push', entry.path, self.dir_on_device + entry.name])
     # Remove native libs not exist on host.
     for build_id in self.device_build_id_map:
         if build_id not in self.host_build_id_map:
             name = self.device_build_id_map[build_id]
             self.adb.run(['shell', 'rm', self.dir_on_device + name])
     # Push new build_id_list on device.
     with open(self.build_id_list_file, 'wb') as fh:
         for build_id in self.host_build_id_map:
             s = str_to_bytes('%s=%s\n' % (build_id, self.host_build_id_map[build_id].name))
             fh.write(s)
     self.adb.check_run(['push', self.build_id_list_file,
                         self.dir_on_device + self.build_id_list_file])
     os.remove(self.build_id_list_file)
コード例 #23
0
 def sync_natives_libs_on_device(self):
     # Push missing native libs on device.
     for build_id in self.host_build_id_map:
         if build_id not in self.device_build_id_map:
             entry = self.host_build_id_map[build_id]
             self.adb.check_run(['push', entry.path, self.dir_on_device + entry.name])
     # Remove native libs not exist on host.
     for build_id in self.device_build_id_map:
         if build_id not in self.host_build_id_map:
             name = self.device_build_id_map[build_id]
             self.adb.run(['shell', 'rm', self.dir_on_device + name])
     # Push new build_id_list on device.
     with open(self.build_id_list_file, 'wb') as fh:
         for build_id in self.host_build_id_map:
             s = str_to_bytes('%s=%s\n' % (build_id, self.host_build_id_map[build_id].name))
             fh.write(s)
     self.adb.check_run(['push', self.build_id_list_file,
                         self.dir_on_device + self.build_id_list_file])
     os.remove(self.build_id_list_file)
コード例 #24
0
    def show_city(self):
        while True:
            text = input('Nhap id thanh pho ban muon xem: ').strip()

            try:
                number = int(text)
            except ValueError:
                print('Ban phai nhap so')
                continue

            data = 'city {}'.format(number)
            data = str_to_bytes(data)
            self.client.sendall(data)

            data = self.client.recv(SERVER_DATA_LENGTH)
            data = bytes_to_str(data)

            print('----------------------------------')
            print('Danh sach thoi tiet cac ngay toi')
            print(data)
            break
コード例 #25
0
ファイル: wifi_scan.py プロジェクト: jkearins/esp-idf
def scan_result_response(security_ctx, response_data):
    # Interpret protobuf response packet from ScanResult command
    dec_resp = security_ctx.decrypt_data(str_to_bytes(response_data))
    resp = proto.wifi_scan_pb2.WiFiScanPayload()
    resp.ParseFromString(dec_resp)
    print_verbose(security_ctx, f'ScanResult status: 0x{str(resp.status)}')
    if resp.status != 0:
        raise RuntimeError
    authmode_str = ['Open', 'WEP', 'WPA_PSK', 'WPA2_PSK', 'WPA_WPA2_PSK',
                    'WPA2_ENTERPRISE', 'WPA3_PSK', 'WPA2_WPA3_PSK']
    results = []
    for entry in resp.resp_scan_result.entries:
        results += [{'ssid': entry.ssid.decode('latin-1').rstrip('\x00'),
                     'bssid': entry.bssid.hex(),
                     'channel': entry.channel,
                     'rssi': entry.rssi,
                     'auth': authmode_str[entry.auth]}]
        print_verbose(security_ctx, f"ScanResult SSID    : {str(results[-1]['ssid'])}")
        print_verbose(security_ctx, f"ScanResult BSSID   : {str(results[-1]['bssid'])}")
        print_verbose(security_ctx, f"ScanResult Channel : {str(results[-1]['channel'])}")
        print_verbose(security_ctx, f"ScanResult RSSI    : {str(results[-1]['rssi'])}")
        print_verbose(security_ctx, f"ScanResult AUTH    : {str(results[-1]['auth'])}")
    return results
コード例 #26
0
ファイル: security1.py プロジェクト: jkearins/esp-idf
    def setup0_response(self, response_data):
        # Interpret SessionResp0 response packet
        setup_resp = proto.session_pb2.SessionData()
        setup_resp.ParseFromString(str_to_bytes(response_data))
        self._print_verbose('Security version:\t' + str(setup_resp.sec_ver))
        if setup_resp.sec_ver != proto.session_pb2.SecScheme1:
            raise RuntimeError('Incorrect security scheme')

        self.device_public_key = setup_resp.sec1.sr0.device_pubkey
        # Device random is the initialization vector
        device_random = setup_resp.sec1.sr0.device_random
        self._print_verbose(
            f'Device Public Key:\t0x{self.device_public_key.hex()}')
        self._print_verbose(f'Device Random:\t0x{device_random.hex()}')

        # Calculate Curve25519 shared key using Client private key and Device public key
        sharedK = self.client_private_key.exchange(
            X25519PublicKey.from_public_bytes(self.device_public_key))
        self._print_verbose(f'Shared Key:\t0x{sharedK.hex()}')

        # If PoP is provided, XOR SHA256 of PoP with the previously
        # calculated Shared Key to form the actual Shared Key
        if len(self.pop) > 0:
            # Calculate SHA256 of PoP
            h = hashes.Hash(hashes.SHA256(), backend=default_backend())
            h.update(self.pop)
            digest = h.finalize()
            # XOR with and update Shared Key
            sharedK = a_xor_b(sharedK, digest)
            self._print_verbose(
                f'Updated Shared Key (Shared key XORed with PoP):\t0x{sharedK.hex()}'
            )
        # Initialize the encryption engine with Shared Key and initialization vector
        cipher = Cipher(algorithms.AES(sharedK),
                        modes.CTR(device_random),
                        backend=default_backend())
        self.cipher = cipher.encryptor()
コード例 #27
0
 def parseSendData(self, data:str, encoding, usrCRLF=False, isHexStr=False, escape=False):
     if not data:
         return b''
     if usrCRLF:
         data = data.replace("\n", "\r\n")
     if isHexStr:
         if usrCRLF:
             data = data.replace("\r\n", " ")
         else:
             data = data.replace("\n", " ")
         data = utils.hex_str_to_bytes(data)
         if data == -1:
             self.hintSignal.emit("error", _("Error"), _("Format error, should be like 00 01 02 03"))
             return b''
     else:
         if not escape:
             data = data.encode(encoding,"ignore")
         else: # '11234abcd\n123你好\r\n\thello\x00\x01\x02'
             try:
                 data = utils.str_to_bytes(data, escape=True, encoding=encoding)
             except Exception as e:
                 self.hintSignal.emit("error", _("Error"), _("Escape is on, but escape error:") + str(e))
                 return b''
     return data
コード例 #28
0
    def update_weather(self):
        if not self.is_admin:
            print('Ban nhap khong hop le')
            return

        self.client.sendall(b'list_city')
        data = client.recv(SERVER_DATA_LENGTH)
        data = bytes_to_str(data)
        print(data)

        dict = {}
        dict['city_id'] = input('City id: ').strip()
        dict['day'] = input('Ngay (yyyy-mm-dd): ').strip()
        dict['status'] = input('Trang thai: ').strip()
        dict['temp_min'] = input('Nhiet do thap nhat: ').strip()
        dict['temp_max'] = input('Nhiet do cao nhat: ').strip()

        data = 'update_weather {}'.format(str(dict))
        data = str_to_bytes(data)
        self.client.sendall(data)

        data = self.client.recv(SERVER_DATA_LENGTH)
        data = bytes_to_str(data)
        print(data)
コード例 #29
0
def store_pprof_profile(filename, profile):
    with open(filename, 'wb') as f:
        f.write(str_to_bytes(profile.SerializeToString()))
コード例 #30
0
def custom_data_response(security_ctx, response_data):
    # Decrypt response packet
    decrypt = security_ctx.decrypt_data(str_to_bytes(response_data))
    print(f'++++ CustomData response: {str(decrypt)}++++')
    return 0
コード例 #31
0
def custom_data_request(security_ctx, data):
    # Encrypt the custom data
    enc_cmd = security_ctx.encrypt_data(str_to_bytes(data))
    print_verbose(security_ctx,
                  f'Client -> Device (CustomData cmd): 0x{enc_cmd.hex()}')
    return enc_cmd.decode('latin-1')
コード例 #32
0
 def update(self, k, v):
     h = utils.sha3(k)
     bytes = utils.str_to_bytes(k)
     self.db.put(h, bytes)
     self.trie.update(h, v)