def validate_auth(self, _key, _data): _payload = self.strip_hash(_data) _hash = _data[-10:] _chk_hash = bhex((hmac_new(_key, _payload, sha1)).hexdigest()[:20]) if _chk_hash == _hash: return True else: return False
def validate_auth(self, _key, _data): _payload = self.strip_hash(_data) _hash = _data[-10:] _chk_hash = bhex((hmac_new(_key,_payload,sha1)).hexdigest()[:20]) if _chk_hash == _hash: return True else: return False
def send_to_ipsc(self, _packet): if self._local['AUTH_ENABLED']: _hash = bhex((hmac_new(self._local['AUTH_KEY'],_packet,sha1)).hexdigest()[:20]) _packet = _packet + _hash # Send to the Master if self._master['STATUS']['CONNECTED']: self.transport.write(_packet, (self._master['IP'], self._master['PORT'])) # Send to each connected Peer for peer in self._peers.keys(): if self._peers[peer]['STATUS']['CONNECTED']: self.transport.write(_packet, (self._peers[peer]['IP'], self._peers[peer]['PORT']))
def send_to_ipsc(self, _packet): if self._local['AUTH_ENABLED']: _hash = bhex((hmac_new(self._local['AUTH_KEY'], _packet, sha1)).hexdigest()[:20]) _packet = _packet + _hash # Send to the Master if self._master['STATUS']['CONNECTED']: self.transport.write(_packet, (self._master['IP'], self._master['PORT'])) # Send to each connected Peer for peer in self._peers.keys(): if self._peers[peer]['STATUS']['CONNECTED']: self.transport.write( _packet, (self._peers[peer]['IP'], self._peers[peer]['PORT']))
def dmrd_received(self, _peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data): if (_frame_type == HBPF_DATA_SYNC) and (_dtype_vseq == HBPF_SLT_VTERM) and ( _stream_id != self.last_stream): print(int_id(_stream_id), int_id(self.last_stream)) self.last_stream = _stream_id print('start speech') speech = pkt_gen(bytes_3(3120101), bytes_3(2), bytes_4(3120119), 0, [words['all_circuits'], words['all_circuits']]) sleep(1) while True: try: pkt = next(speech) except StopIteration: break sleep(.058) self.send_system(pkt) print(bhex(pkt)) print('end speech')
class HBSYSTEM(DatagramProtocol): def __init__(self, _name, _config, _logger): # Define a few shortcuts to make the rest of the class more readable self._CONFIG = _config self._system = _name self._logger = _logger self._config = self._CONFIG['SYSTEMS'][self._system] # Define shortcuts and generic function names based on the type of system we are if self._config['MODE'] == 'MASTER': self._clients = self._CONFIG['SYSTEMS'][self._system]['CLIENTS'] self.send_system = self.send_clients self.maintenance_loop = self.master_maintenance_loop self.datagramReceived = self.master_datagramReceived self.dereg = self.master_dereg elif self._config['MODE'] == 'CLIENT': self._stats = self._config['STATS'] self.send_system = self.send_master self.maintenance_loop = self.client_maintenance_loop self.datagramReceived = self.client_datagramReceived self.dereg = self.client_dereg # Configure for AMBE audio export if enabled if self._config['EXPORT_AMBE']: self._ambe = AMBE() def startProtocol(self): # Set up periodic loop for tracking pings from clients. Run every 'PING_TIME' seconds self._system_maintenance = task.LoopingCall(self.maintenance_loop) self._system_maintenance_loop = self._system_maintenance.start(self._CONFIG['GLOBAL']['PING_TIME']) # Aliased in __init__ to maintenance_loop if system is a master def master_maintenance_loop(self): self._logger.debug('(%s) Master maintenance loop started', self._system) for client in self._clients: _this_client = self._clients[client] # Check to see if any of the clients have been quiet (no ping) longer than allowed if _this_client['LAST_PING']+self._CONFIG['GLOBAL']['PING_TIME']*self._CONFIG['GLOBAL']['MAX_MISSED'] < time(): self._logger.info('(%s) Client %s (%s) has timed out', self._system, _this_client['CALLSIGN'], _this_client['RADIO_ID']) # Remove any timed out clients from the configuration del self._CONFIG['SYSTEMS'][self._system]['CLIENTS'][client] # Aliased in __init__ to maintenance_loop if system is a client def client_maintenance_loop(self): self._logger.debug('(%s) Client maintenance loop started', self._system) # If we're not connected, zero out the stats and send a login request RPTL if self._stats['CONNECTION'] == 'NO' or self._stats['CONNECTION'] == 'RTPL_SENT': self._stats['PINGS_SENT'] = 0 self._stats['PINGS_ACKD'] = 0 self._stats['CONNECTION'] = 'RTPL_SENT' self.send_master('RPTL'+self._config['RADIO_ID']) self._logger.info('(%s) Sending login request to master %s:%s', self._system, self._config['MASTER_IP'], self._config['MASTER_PORT']) # If we are connected, sent a ping to the master and increment the counter if self._stats['CONNECTION'] == 'YES': self.send_master('RPTPING'+self._config['RADIO_ID']) self._stats['PINGS_SENT'] += 1 self._logger.debug('(%s) RPTPING Sent to Master. Pings Since Connected: %s', self._system, self._stats['PINGS_SENT']) def send_clients(self, _packet): for _client in self._clients: self.send_client(_client, _packet) #self._logger.debug('(%s) Packet sent to client %s', self._system, self._clients[_client]['RADIO_ID']) def send_client(self, _client, _packet): _ip = self._clients[_client]['IP'] _port = self._clients[_client]['PORT'] self.transport.write(_packet, (_ip, _port)) # KEEP THE FOLLOWING COMMENTED OUT UNLESS YOU'RE DEBUGGING DEEPLY!!!! #self._logger.debug('(%s) TX Packet to %s on port %s: %s', self._clients[_client]['RADIO_ID'], self._clients[_client]['IP'], self._clients[_client]['PORT'], ahex(_packet)) def send_master(self, _packet): self.transport.write(_packet, (self._config['MASTER_IP'], self._config['MASTER_PORT'])) # KEEP THE FOLLOWING COMMENTED OUT UNLESS YOU'RE DEBUGGING DEEPLY!!!! #self._logger.debug('(%s) TX Packet to %s:%s -- %s', self._system, self._config['MASTER_IP'], self._config['MASTER_PORT'], ahex(_packet)) def dmrd_received(self, _radio_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data): pass def master_dereg(self): for _client in self._clients: self.send_client(_client, 'MSTCL'+_client) self._logger.info('(%s) De-Registration sent to Client: %s (%s)', self._system, self._clients[_client]['CALLSIGN'], self._clients[_client]['RADIO_ID']) def client_dereg(self): self.send_master('RPTCL'+self._config['RADIO_ID']) self._logger.info('(%s) De-Registeration sent to Master: %s:%s', self._system, self._config['MASTER_IP'], self._config['MASTER_PORT']) # Aliased in __init__ to datagramReceived if system is a master def master_datagramReceived(self, _data, (_host, _port)): # Keep This Line Commented Unless HEAVILY Debugging! #self._logger.debug('(%s) RX packet from %s:%s -- %s', self._system, _host, _port, ahex(_data)) # Extract the command, which is various length, all but one 4 significant characters -- RPTCL _command = _data[:4] if _command == 'DMRD': # DMRData -- encapsulated DMR data frame _radio_id = _data[11:15] if _radio_id in self._clients \ and self._clients[_radio_id]['CONNECTION'] == 'YES' \ and self._clients[_radio_id]['IP'] == _host \ and self._clients[_radio_id]['PORT'] == _port: _seq = _data[4] _rf_src = _data[5:8] _dst_id = _data[8:11] _bits = int_id(_data[15]) _slot = 2 if (_bits & 0x80) else 1 _call_type = 'unit' if (_bits & 0x40) else 'group' _frame_type = (_bits & 0x30) >> 4 _dtype_vseq = (_bits & 0xF) # data, 1=voice header, 2=voice terminator; voice, 0=burst A ... 5=burst F _stream_id = _data[16:20] #self._logger.debug('(%s) DMRD - Seqence: %s, RF Source: %s, Destination ID: %s', self._system, int_id(_seq), int_id(_rf_src), int_id(_dst_id)) # If AMBE audio exporting is configured... if self._config['EXPORT_AMBE']: self._ambe.parseAMBE(self._system, _data) # The basic purpose of a master is to repeat to the clients if self._config['REPEAT'] == True: for _client in self._clients: if _client != _radio_id: self.send_client(_client, _data) self._logger.debug('(%s) Packet on TS%s from %s (%s) for destination ID %s repeated to client: %s (%s) [Stream ID: %s]', self._system, _slot, self._clients[_radio_id]['CALLSIGN'], int_id(_radio_id), int_id(_dst_id), self._clients[_client]['CALLSIGN'], int_id(_client), int_id(_stream_id)) # Userland actions -- typically this is the function you subclass for an application self.dmrd_received(_radio_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data) elif _command == 'RPTL': # RPTLogin -- a repeater wants to login _radio_id = _data[4:8] if _radio_id: # Future check here for valid Radio ID self._clients.update({_radio_id: { # Build the configuration data strcuture for the client 'CONNECTION': 'RPTL-RECEIVED', 'PINGS_RECEIVED': 0, 'LAST_PING': time(), 'IP': _host, 'PORT': _port, 'SALT': randint(0,0xFFFFFFFF), 'RADIO_ID': str(int(ahex(_radio_id), 16)), 'CALLSIGN': '', 'RX_FREQ': '', 'TX_FREQ': '', 'TX_POWER': '', 'COLORCODE': '', 'LATITUDE': '', 'LONGITUDE': '', 'HEIGHT': '', 'LOCATION': '', 'DESCRIPTION': '', 'SLOTS': '', 'URL': '', 'SOFTWARE_ID': '', 'PACKAGE_ID': '', }}) self._logger.info('(%s) Repeater Logging in with Radio ID: %s, %s:%s', self._system, int_id(_radio_id), _host, _port) _salt_str = hex_str_4(self._clients[_radio_id]['SALT']) self.send_client(_radio_id, 'RPTACK'+_salt_str) self._clients[_radio_id]['CONNECTION'] = 'CHALLENGE_SENT' self._logger.info('(%s) Sent Challenge Response to %s for login: %s', self._system, int_id(_radio_id), self._clients[_radio_id]['SALT']) else: self.transport.write('MSTNAK'+_radio_id, (_host, _port)) self._logger.warning('(%s) Invalid Login from Radio ID: %s', self._system, int_id(_radio_id)) elif _command == 'RPTK': # Repeater has answered our login challenge _radio_id = _data[4:8] if _radio_id in self._clients \ and self._clients[_radio_id]['CONNECTION'] == 'CHALLENGE_SENT' \ and self._clients[_radio_id]['IP'] == _host \ and self._clients[_radio_id]['PORT'] == _port: _this_client = self._clients[_radio_id] _this_client['LAST_PING'] = time() _sent_hash = _data[8:] _salt_str = hex_str_4(_this_client['SALT']) _calc_hash = bhex(sha256(_salt_str+self._config['PASSPHRASE']).hexdigest()) if _sent_hash == _calc_hash: _this_client['CONNECTION'] = 'WAITING_CONFIG' self.send_client(_radio_id, 'RPTACK'+_radio_id) self._logger.info('(%s) Client %s has completed the login exchange successfully', self._system, _this_client['RADIO_ID']) else: self._logger.info('(%s) Client %s has FAILED the login exchange successfully', self._system, _this_client['RADIO_ID']) self.transport.write('MSTNAK'+_radio_id, (_host, _port)) del self._clients[_radio_id] else: self.transport.write('MSTNAK'+_radio_id, (_host, _port)) self._logger.warning('(%s) Login challenge from Radio ID that has not logged in: %s', self._system, int_id(_radio_id)) elif _command == 'RPTC': # Repeater is sending it's configuraiton OR disconnecting if _data[:5] == 'RPTCL': # Disconnect command _radio_id = _data[5:9] if _radio_id in self._clients \ and self._clients[_radio_id]['CONNECTION'] == 'YES' \ and self._clients[_radio_id]['IP'] == _host \ and self._clients[_radio_id]['PORT'] == _port: self._logger.info('(%s) Client is closing down: %s (%s)', self._system, self._clients[_radio_id]['CALLSIGN'], int_id(_radio_id)) self.transport.write('MSTNAK'+_radio_id, (_host, _port)) del self._clients[_radio_id] else: _radio_id = _data[4:8] # Configure Command if _radio_id in self._clients \ and self._clients[_radio_id]['CONNECTION'] == 'WAITING_CONFIG' \ and self._clients[_radio_id]['IP'] == _host \ and self._clients[_radio_id]['PORT'] == _port: _this_client = self._clients[_radio_id] _this_client['CONNECTION'] = 'YES' _this_client['LAST_PING'] = time() _this_client['CALLSIGN'] = _data[8:16] _this_client['RX_FREQ'] = _data[16:25] _this_client['TX_FREQ'] = _data[25:34] _this_client['TX_POWER'] = _data[34:36] _this_client['COLORCODE'] = _data[36:38] _this_client['LATITUDE'] = _data[38:46] _this_client['LONGITUDE'] = _data[46:55] _this_client['HEIGHT'] = _data[55:58] _this_client['LOCATION'] = _data[58:78] _this_client['DESCRIPTION'] = _data[78:97] _this_client['SLOTS'] = _data[97:98] _this_client['URL'] = _data[98:222] _this_client['SOFTWARE_ID'] = _data[222:262] _this_client['PACKAGE_ID'] = _data[262:302] self.send_client(_radio_id, 'RPTACK'+_radio_id) self._logger.info('(%s) Client %s (%s) has sent repeater configuration', self._system, _this_client['CALLSIGN'], _this_client['RADIO_ID']) else: self.transport.write('MSTNAK'+_radio_id, (_host, _port)) self._logger.warning('(%s) Client info from Radio ID that has not logged in: %s', self._system, int_id(_radio_id)) elif _command == 'RPTP': # RPTPing -- client is pinging us _radio_id = _data[7:11] if _radio_id in self._clients \ and self._clients[_radio_id]['CONNECTION'] == "YES" \ and self._clients[_radio_id]['IP'] == _host \ and self._clients[_radio_id]['PORT'] == _port: self._clients[_radio_id]['LAST_PING'] = time() self.send_client(_radio_id, 'MSTPONG'+_radio_id) self._logger.debug('(%s) Received and answered RPTPING from client %s (%s)', self._system, self._clients[_radio_id]['CALLSIGN'], int_id(_radio_id)) else: self.transport.write('MSTNAK'+_radio_id, (_host, _port)) self._logger.warning('(%s) Client info from Radio ID that has not logged in: %s', self._system, int_id(_radio_id)) else: self._logger.error('(%s) Unrecognized command from: %s. Packet: %s', self._system, int_id(_radio_id), ahex(_data))
# Userland actions -- typically this is the function you subclass for an application self.dmrd_received(_radio_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data) elif _command == 'MSTN': # Actually MSTNAK -- a NACK from the master _radio_id = _data[4:8] if _radio_id == self._config['RADIO_ID']: # Validate the source and intended target self._logger.warning('(%s) MSTNAK Received', self._system) self._stats['CONNECTION'] = 'NO' # Disconnect ourselves and re-register elif _command == 'RPTA': # Actually RPTACK -- an ACK from the master # Depending on the state, an RPTACK means different things, in each clause, we check and/or set the state if self._stats['CONNECTION'] == 'RTPL_SENT': # If we've sent a login request... _login_int32 = _data[6:10] self._logger.info('(%s) Repeater Login ACK Received with 32bit ID: %s', self._system, int_id(_login_int32)) _pass_hash = sha256(_login_int32+self._config['PASSPHRASE']).hexdigest() _pass_hash = bhex(_pass_hash) self.send_master('RPTK'+self._config['RADIO_ID']+_pass_hash) self._stats['CONNECTION'] = 'AUTHENTICATED' elif self._stats['CONNECTION'] == 'AUTHENTICATED': # If we've sent the login challenge... if _data[6:10] == self._config['RADIO_ID']: self._logger.info('(%s) Repeater Authentication Accepted', self._system) _config_packet = self._config['RADIO_ID']+\ self._config['CALLSIGN']+\ self._config['RX_FREQ']+\ self._config['TX_FREQ']+\ self._config['TX_POWER']+\ self._config['COLORCODE']+\ self._config['LATITUDE']+\ self._config['LONGITUDE']+\ self._config['HEIGHT']+\
def peer_datagramReceived(self, _data, _sockaddr): # Keep This Line Commented Unless HEAVILY Debugging! # self._logger.debug('(%s) RX packet from %s -- %s', self._system, _sockaddr, ahex(_data)) # Validate that we receveived this packet from the master - security check! if self._config['MASTER_SOCKADDR'] == _sockaddr: # Extract the command, which is various length, but only 4 significant characters _command = _data[:4] if _command == 'DMRD': # DMRData -- encapsulated DMR data frame _peer_id = _data[11:15] if self._config['LOOSE'] or _peer_id == self._config[ 'RADIO_ID']: # Validate the Radio_ID unless using loose validation _seq = _data[4:5] _rf_src = _data[5:8] _dst_id = _data[8:11] _bits = int_id(_data[15]) _slot = 2 if (_bits & 0x80) else 1 _call_type = 'unit' if (_bits & 0x40) else 'group' _frame_type = (_bits & 0x30) >> 4 _dtype_vseq = ( _bits & 0xF ) # data, 1=voice header, 2=voice terminator; voice, 0=burst A ... 5=burst F _stream_id = _data[16:20] self._logger.debug( '(%s) DMRD - Sequence: %s, RF Source: %s, Destination ID: %s', self._system, int_id(_seq), int_id(_rf_src), int_id(_dst_id)) # If AMBE audio exporting is configured... if self._config['EXPORT_AMBE']: self._ambe.parseAMBE(self._system, _data) # Userland actions -- typically this is the function you subclass for an application self.dmrd_received(_peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data) elif _command == 'MSTN': # Actually MSTNAK -- a NACK from the master _peer_id = _data[6:10] if self._config['LOOSE'] or _peer_id == self._config[ 'RADIO_ID']: # Validate the Radio_ID unless using loose validation self._logger.warning( '(%s) MSTNAK Received. Resetting connection to the Master.', self._system) self._stats[ 'CONNECTION'] = 'NO' # Disconnect ourselves and re-register elif _command == 'RPTA': # Actually RPTACK -- an ACK from the master # Depending on the state, an RPTACK means different things, in each clause, we check and/or set the state if self._stats[ 'CONNECTION'] == 'RPTL_SENT': # If we've sent a login request... _login_int32 = _data[6:10] self._logger.info( '(%s) Repeater Login ACK Received with 32bit ID: %s', self._system, int_id(_login_int32)) _pass_hash = sha256( _login_int32 + self._config['PASSPHRASE']).hexdigest() _pass_hash = bhex(_pass_hash) self.send_master('RPTK' + self._config['RADIO_ID'] + _pass_hash) self._stats['CONNECTION'] = 'AUTHENTICATED' elif self._stats[ 'CONNECTION'] == 'AUTHENTICATED': # If we've sent the login challenge... _peer_id = _data[6:10] if self._config['LOOSE'] or _peer_id == self._config[ 'RADIO_ID']: # Validate the Radio_ID unless using loose validation self._logger.info( '(%s) Repeater Authentication Accepted', self._system) _config_packet = self._config['RADIO_ID']+\ self._config['CALLSIGN']+\ self._config['RX_FREQ']+\ self._config['TX_FREQ']+\ self._config['TX_POWER']+\ self._config['COLORCODE']+\ self._config['LATITUDE']+\ self._config['LONGITUDE']+\ self._config['HEIGHT']+\ self._config['LOCATION']+\ self._config['DESCRIPTION']+\ self._config['SLOTS']+\ self._config['URL']+\ self._config['SOFTWARE_ID']+\ self._config['PACKAGE_ID'] self.send_master('RPTC' + _config_packet) self._stats['CONNECTION'] = 'CONFIG-SENT' self._logger.info('(%s) Repeater Configuration Sent', self._system) else: self._stats['CONNECTION'] = 'NO' self._logger.error( '(%s) Master ACK Contained wrong ID - Connection Reset', self._system) elif self._stats[ 'CONNECTION'] == 'CONFIG-SENT': # If we've sent out configuration to the master _peer_id = _data[6:10] if self._config['LOOSE'] or _peer_id == self._config[ 'RADIO_ID']: # Validate the Radio_ID unless using loose validation self._logger.info( '(%s) Repeater Configuration Accepted', self._system) if self._config['OPTIONS']: self.send_master('RPTO' + self._config['RADIO_ID'] + self._config['OPTIONS']) self._stats['CONNECTION'] = 'OPTIONS-SENT' self._logger.info('(%s) Sent options: (%s)', self._system, self._config['OPTIONS']) else: self._stats['CONNECTION'] = 'YES' self._logger.info( '(%s) Connection to Master Completed', self._system) else: self._stats['CONNECTION'] = 'NO' self._logger.error( '(%s) Master ACK Contained wrong ID - Connection Reset', self._system) elif self._stats[ 'CONNECTION'] == 'OPTIONS-SENT': # If we've sent out options to the master _peer_id = _data[6:10] if self._config['LOOSE'] or _peer_id == self._config[ 'RADIO_ID']: # Validate the Radio_ID unless using loose validation self._logger.info('(%s) Repeater Options Accepted', self._system) self._stats['CONNECTION'] = 'YES' self._logger.info( '(%s) Connection to Master Completed with options', self._system) else: self._stats['CONNECTION'] = 'NO' self._logger.error( '(%s) Master ACK Contained wrong ID - Connection Reset', self._system) elif _command == 'MSTP': # Actually MSTPONG -- a reply to RPTPING (send by peer) _peer_id = _data[7:11] if self._config['LOOSE'] or _peer_id == self._config[ 'RADIO_ID']: # Validate the Radio_ID unless using loose validation self._stats['PING_OUTSTANDING'] = False self._stats['NUM_OUTSTANDING'] = 0 self._stats['PINGS_ACKD'] += 1 self._logger.debug( '(%s) MSTPONG Received. Pongs Since Connected: %s', self._system, self._stats['PINGS_ACKD']) elif _command == 'MSTC': # Actually MSTCL -- notify us the master is closing down _peer_id = _data[5:9] if self._config['LOOSE'] or _peer_id == self._config[ 'RADIO_ID']: # Validate the Radio_ID unless using loose validation self._stats['CONNECTION'] = 'NO' self._logger.info('(%s) MSTCL Recieved', self._system) else: self._logger.error( '(%s) Received an invalid command in packet: %s', self._system, ahex(_data))
def master_datagramReceived(self, _data, _sockaddr): # Keep This Line Commented Unless HEAVILY Debugging! # self._logger.debug('(%s) RX packet from %s -- %s', self._system, _sockaddr, ahex(_data)) # Extract the command, which is various length, all but one 4 significant characters -- RPTCL _command = _data[:4] if _command == 'DMRD': # DMRData -- encapsulated DMR data frame _peer_id = _data[11:15] if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == 'YES' \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: _seq = _data[4] _rf_src = _data[5:8] _dst_id = _data[8:11] _bits = int_id(_data[15]) _slot = 2 if (_bits & 0x80) else 1 _call_type = 'unit' if (_bits & 0x40) else 'group' _frame_type = (_bits & 0x30) >> 4 _dtype_vseq = ( _bits & 0xF ) # data, 1=voice header, 2=voice terminator; voice, 0=burst A ... 5=burst F _stream_id = _data[16:20] #self._logger.debug('(%s) DMRD - Seqence: %s, RF Source: %s, Destination ID: %s', self._system, int_id(_seq), int_id(_rf_src), int_id(_dst_id)) # If AMBE audio exporting is configured... if self._config['EXPORT_AMBE']: self._ambe.parseAMBE(self._system, _data) # The basic purpose of a master is to repeat to the peers if self._config['REPEAT'] == True: for _peer in self._peers: if _peer != _peer_id: #self.send_peer(_peer, _data) self.send_peer(_peer, _data[:11] + _peer + _data[15:]) #self.send_peer(_peer, _data[:11] + self._config['RADIO_ID'] + _data[15:]) #self._logger.debug('(%s) Packet on TS%s from %s (%s) for destination ID %s repeated to peer: %s (%s) [Stream ID: %s]', self._system, _slot, self._peers[_peer_id]['CALLSIGN'], int_id(_peer_id), int_id(_dst_id), self._peers[_peer]['CALLSIGN'], int_id(_peer), int_id(_stream_id)) # Userland actions -- typically this is the function you subclass for an application self.dmrd_received(_peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data) elif _command == 'RPTL': # RPTLogin -- a repeater wants to login _peer_id = _data[4:8] if allow_reg(_peer_id): # Check for valid Radio ID self._peers.update({_peer_id: { # Build the configuration data strcuture for the peer 'CONNECTION': 'RPTL-RECEIVED', 'PINGS_RECEIVED': 0, 'LAST_PING': time(), 'SOCKADDR': _sockaddr, 'IP': _sockaddr[0], 'PORT': _sockaddr[1], 'SALT': randint(0,0xFFFFFFFF), 'RADIO_ID': str(int(ahex(_peer_id), 16)), 'CALLSIGN': '', 'RX_FREQ': '', 'TX_FREQ': '', 'TX_POWER': '', 'COLORCODE': '', 'LATITUDE': '', 'LONGITUDE': '', 'HEIGHT': '', 'LOCATION': '', 'DESCRIPTION': '', 'SLOTS': '', 'URL': '', 'SOFTWARE_ID': '', 'PACKAGE_ID': '', }}) self._logger.info( '(%s) Repeater Logging in with Radio ID: %s, %s:%s', self._system, int_id(_peer_id), _sockaddr[0], _sockaddr[1]) _salt_str = hex_str_4(self._peers[_peer_id]['SALT']) self.send_peer(_peer_id, 'RPTACK' + _salt_str) self._peers[_peer_id]['CONNECTION'] = 'CHALLENGE_SENT' self._logger.info( '(%s) Sent Challenge Response to %s for login: %s', self._system, int_id(_peer_id), self._peers[_peer_id]['SALT']) else: self.transport.write('MSTNAK' + _peer_id, _sockaddr) self._logger.warning( '(%s) Invalid Login from Radio ID: %s Denied by Registation ACL', self._system, int_id(_peer_id)) elif _command == 'RPTK': # Repeater has answered our login challenge _peer_id = _data[4:8] if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == 'CHALLENGE_SENT' \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: _this_peer = self._peers[_peer_id] _this_peer['LAST_PING'] = time() _sent_hash = _data[8:] _salt_str = hex_str_4(_this_peer['SALT']) _calc_hash = bhex( sha256(_salt_str + self._config['PASSPHRASE']).hexdigest()) if _sent_hash == _calc_hash: _this_peer['CONNECTION'] = 'WAITING_CONFIG' self.send_peer(_peer_id, 'RPTACK' + _peer_id) self._logger.info( '(%s) Peer %s has completed the login exchange successfully', self._system, _this_peer['RADIO_ID']) else: self._logger.info( '(%s) Peer %s has FAILED the login exchange successfully', self._system, _this_peer['RADIO_ID']) self.transport.write('MSTNAK' + _peer_id, _sockaddr) del self._peers[_peer_id] else: self.transport.write('MSTNAK' + _peer_id, _sockaddr) self._logger.warning( '(%s) Login challenge from Radio ID that has not logged in: %s', self._system, int_id(_peer_id)) elif _command == 'RPTC': # Repeater is sending it's configuraiton OR disconnecting if _data[:5] == 'RPTCL': # Disconnect command _peer_id = _data[5:9] if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == 'YES' \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: self._logger.info('(%s) Peer is closing down: %s (%s)', self._system, self._peers[_peer_id]['CALLSIGN'], int_id(_peer_id)) self.transport.write('MSTNAK' + _peer_id, _sockaddr) del self._peers[_peer_id] else: _peer_id = _data[4:8] # Configure Command if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == 'WAITING_CONFIG' \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: _this_peer = self._peers[_peer_id] _this_peer['CONNECTION'] = 'YES' _this_peer['LAST_PING'] = time() _this_peer['CALLSIGN'] = _data[8:16] _this_peer['RX_FREQ'] = _data[16:25] _this_peer['TX_FREQ'] = _data[25:34] _this_peer['TX_POWER'] = _data[34:36] _this_peer['COLORCODE'] = _data[36:38] _this_peer['LATITUDE'] = _data[38:46] _this_peer['LONGITUDE'] = _data[46:55] _this_peer['HEIGHT'] = _data[55:58] _this_peer['LOCATION'] = _data[58:78] _this_peer['DESCRIPTION'] = _data[78:97] _this_peer['SLOTS'] = _data[97:98] _this_peer['URL'] = _data[98:222] _this_peer['SOFTWARE_ID'] = _data[222:262] _this_peer['PACKAGE_ID'] = _data[262:302] self.send_peer(_peer_id, 'RPTACK' + _peer_id) self._logger.info( '(%s) Peer %s (%s) has sent repeater configuration', self._system, _this_peer['CALLSIGN'], _this_peer['RADIO_ID']) else: self.transport.write('MSTNAK' + _peer_id, _sockaddr) self._logger.warning( '(%s) Peer info from Radio ID that has not logged in: %s', self._system, int_id(_peer_id)) elif _command == 'RPTP': # RPTPing -- peer is pinging us _peer_id = _data[7:11] if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == "YES" \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: self._peers[_peer_id]['PINGS_RECEIVED'] += 1 self._peers[_peer_id]['LAST_PING'] = time() self.send_peer(_peer_id, 'MSTPONG' + _peer_id) self._logger.debug( '(%s) Received and answered RPTPING from peer %s (%s)', self._system, self._peers[_peer_id]['CALLSIGN'], int_id(_peer_id)) else: self.transport.write('MSTNAK' + _peer_id, _sockaddr) self._logger.warning( '(%s) Peer info from Radio ID that has not logged in: %s', self._system, int_id(_peer_id)) else: self._logger.error('(%s) Unrecognized command. Raw HBP PDU: %s', self._system, ahex(_data))
def hashed_packet(self, _key, _data): _hash = bhex((hmac_new(_key,_data,sha1)).hexdigest()[:20]) return _data + _hash
def peer_datagramReceived(self, _data, _sockaddr): # Keep This Line Commented Unless HEAVILY Debugging! # logger.debug('(%s) RX packet from %s -- %s', self._system, _sockaddr, ahex(_data)) # Validate that we receveived this packet from the master - security check! if self._config['MASTER_SOCKADDR'] == _sockaddr: # Extract the command, which is various length, but only 4 significant characters _command = _data[:4] if _command == 'DMRD': # DMRData -- encapsulated DMR data frame _peer_id = _data[11:15] if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation _seq = _data[4:5] _rf_src = _data[5:8] _dst_id = _data[8:11] _bits = int_id(_data[15]) _slot = 2 if (_bits & 0x80) else 1 #_call_type = 'unit' if (_bits & 0x40) else 'group' if _bits & 0x40: _call_type = 'unit' elif (_bits & 0x23) == 0x23: _call_type = 'vcsbk' else: _call_type = 'group' _frame_type = (_bits & 0x30) >> 4 _dtype_vseq = (_bits & 0xF) # data, 1=voice header, 2=voice terminator; voice, 0=burst A ... 5=burst F _stream_id = _data[16:20] #logger.debug('(%s) DMRD - Sequence: %s, RF Source: %s, Destination ID: %s', self._system, int_id(_seq), int_id(_rf_src), int_id(_dst_id)) # ACL Processing if self._CONFIG['GLOBAL']['USE_ACL']: if not acl_check(_rf_src, self._CONFIG['GLOBAL']['SUB_ACL']): if self._laststrid != _stream_id: logger.debug('(%s) CALL DROPPED WITH STREAM ID %s FROM SUBSCRIBER %s BY GLOBAL ACL', self._system, int_id(_stream_id), int_id(_rf_src)) if _slot == 1: self._laststrid1 = _stream_id else: self._laststrid2 = _stream_id return if _slot == 1 and not acl_check(_dst_id, self._CONFIG['GLOBAL']['TG1_ACL']): if self._laststrid1 != _stream_id: logger.debug('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY GLOBAL TS1 ACL', self._system, int_id(_stream_id), int_id(_dst_id)) self._laststrid1 = _stream_id return if _slot == 2 and not acl_check(_dst_id, self._CONFIG['GLOBAL']['TG2_ACL']): if self._laststrid2 != _stream_id: logger.debug('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY GLOBAL TS2 ACL', self._system, int_id(_stream_id), int_id(_dst_id)) self._laststrid2 = _stream_id return if self._config['USE_ACL']: if not acl_check(_rf_src, self._config['SUB_ACL']): if self._laststrid != _stream_id: logger.debug('(%s) CALL DROPPED WITH STREAM ID %s FROM SUBSCRIBER %s BY SYSTEM ACL', self._system, int_id(_stream_id), int_id(_rf_src)) if _slot == 1: self._laststrid1 = _stream_id else: self._laststrid2 = _stream_id return if _slot == 1 and not acl_check(_dst_id, self._config['TG1_ACL']): if self._laststrid1 != _stream_id: logger.debug('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY SYSTEM TS1 ACL', self._system, int_id(_stream_id), int_id(_dst_id)) self._laststrid1 = _stream_id return if _slot == 2 and not acl_check(_dst_id, self._config['TG2_ACL']): if self._laststrid2 != _stream_id: logger.debug('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY SYSTEM TS2 ACL', self._system, int_id(_stream_id), int_id(_dst_id)) self._laststrid2 = _stream_id return # Userland actions -- typically this is the function you subclass for an application self.dmrd_received(_peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data) elif _command == 'MSTN': # Actually MSTNAK -- a NACK from the master _peer_id = _data[6:10] if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation logger.warning('(%s) MSTNAK Received. Resetting connection to the Master.', self._system) self._stats['CONNECTION'] = 'NO' # Disconnect ourselves and re-register self._stats['CONNECTED'] = time() elif _command == 'RPTA': # Actually RPTACK -- an ACK from the master # Depending on the state, an RPTACK means different things, in each clause, we check and/or set the state if self._stats['CONNECTION'] == 'RPTL_SENT': # If we've sent a login request... _login_int32 = _data[6:10] logger.info('(%s) Repeater Login ACK Received with 32bit ID: %s', self._system, int_id(_login_int32)) _pass_hash = sha256(_login_int32+self._config['PASSPHRASE']).hexdigest() _pass_hash = bhex(_pass_hash) self.send_master('RPTK'+self._config['RADIO_ID']+_pass_hash) self._stats['CONNECTION'] = 'AUTHENTICATED' elif self._stats['CONNECTION'] == 'AUTHENTICATED': # If we've sent the login challenge... _peer_id = _data[6:10] if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation logger.info('(%s) Repeater Authentication Accepted', self._system) _config_packet = self._config['RADIO_ID']+\ self._config['CALLSIGN']+\ self._config['RX_FREQ']+\ self._config['TX_FREQ']+\ self._config['TX_POWER']+\ self._config['COLORCODE']+\ self._config['LATITUDE']+\ self._config['LONGITUDE']+\ self._config['HEIGHT']+\ self._config['LOCATION']+\ self._config['DESCRIPTION']+\ self._config['SLOTS']+\ self._config['URL']+\ self._config['SOFTWARE_ID']+\ self._config['PACKAGE_ID'] self.send_master('RPTC'+_config_packet) self._stats['CONNECTION'] = 'CONFIG-SENT' logger.info('(%s) Repeater Configuration Sent', self._system) else: self._stats['CONNECTION'] = 'NO' logger.error('(%s) Master ACK Contained wrong ID - Connection Reset', self._system) elif self._stats['CONNECTION'] == 'CONFIG-SENT': # If we've sent out configuration to the master _peer_id = _data[6:10] if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation logger.info('(%s) Repeater Configuration Accepted', self._system) if self._config['OPTIONS']: self.send_master('RPTO'+self._config['RADIO_ID']+self._config['OPTIONS']) self._stats['CONNECTION'] = 'OPTIONS-SENT' logger.info('(%s) Sent options: (%s)', self._system, self._config['OPTIONS']) else: self._stats['CONNECTION'] = 'YES' self._stats['CONNECTED'] = time() logger.info('(%s) Connection to Master Completed', self._system) else: self._stats['CONNECTION'] = 'NO' logger.error('(%s) Master ACK Contained wrong ID - Connection Reset', self._system) elif self._stats['CONNECTION'] == 'OPTIONS-SENT': # If we've sent out options to the master _peer_id = _data[6:10] if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation logger.info('(%s) Repeater Options Accepted', self._system) self._stats['CONNECTION'] = 'YES' self._stats['CONNECTED'] = time() logger.info('(%s) Connection to Master Completed with options', self._system) else: self._stats['CONNECTION'] = 'NO' logger.error('(%s) Master ACK Contained wrong ID - Connection Reset', self._system) elif _command == 'MSTP': # Actually MSTPONG -- a reply to RPTPING (send by peer) _peer_id = _data[7:11] if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation self._stats['PING_OUTSTANDING'] = False self._stats['NUM_OUTSTANDING'] = 0 self._stats['PINGS_ACKD'] += 1 logger.debug('(%s) MSTPONG Received. Pongs Since Connected: %s', self._system, self._stats['PINGS_ACKD']) elif _command == 'MSTC': # Actually MSTCL -- notify us the master is closing down _peer_id = _data[5:9] if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation self._stats['CONNECTION'] = 'NO' logger.info('(%s) MSTCL Recieved', self._system) else: logger.error('(%s) Received an invalid command in packet: %s', self._system, ahex(_data))
def process(pkt): # we need to save ambe payload from MMDVM as global var global ambe_payload_mmdvm # we need to save the last packet Seq from Hytera IPSC UDP packet for later processing as global var global last_seq_HYT # get payload from packet is landed in netqueue - the payload is including(!) the IP header - the payload we use starts at p[28:] data = IP(pkt.get_payload()) # process only UDP packets longer than 80, shorter packets will be pass-thru without any modification if len(data) > 80: # hexdump(data) # print("Length:", len(data),"\n\r") # extract payload from UDP packet mod_data = raw(data) # convert to bytearray p = bytearray(mod_data) # print(p[28:]) # is the packet a MMDVM DMRD packet ? if p[28:32] == b"DMRD": # if p[28] == 68 and p[29] == 77 and p[30] == 82 and p[31] == 68 : print("------ packet processing MMDVM ------") p1 = bytearray(p[48:82]) p1 = ahex(p1) print(p1, ":from DMRGateway(payload) Seq.Nr:", hex(p[32]), "Byte15-Flags:", format(p[43], '08b'), check_FrameType_MMDVM(p[43]), "SrcId:", int_id(p[33:36]), "T:", int_id(p[36:39])) # swap the ambe mmdvm payload HiByte<>LowByte needed for use in Hytera ambe payload p2 = byte_swap(p1) # save swapped ambe payload in ambe_paylaod_mmdvm for later insert in Hytera ambe payload ambe_payload_mmdvm = p2 print(p2, ":modify MMDVM(Byte_swapping) Seq.Nr:", hex(p[32]), "Byte15-Flags:", format(p[43], '08b')) # print(ahex(p[48:82])) # print(ahex(p[48:82]),":MMDVM Seq.Nr: ",hex(p[32]),"Status: ",format(p[43],'08b')) # is it a Hytera packet ? elif p[28:32] == b"ZZZZ" or p[28:32] == bytearray.fromhex( 'ee ee 11 11'): print("------ packet processing IPSC HYTERA ------") # print(ambe_payload_mmdvm,":saved") # get the SrcId from Hytera payload SrcId = p[96:99] # get the destination Id from Hytera paylaod _DestId = bytearray(p[92:95]) _DestId = ahex(_DestId) # change byteorder for correct calculating destination Id DestId = swap_DestId(_DestId) # print(ahex(p[44:46])) # get slot number from Hytera payload _slot = bytearray(p[44:46]) _slot = ahex(_slot) Slot = check_Slot_HYT(_slot) print(ahex(p[28:32]), ":first 4 Bytes from HytGW Seq.Nr:", hex(p[32]), "FrameType:", hex(p[36]), "Frametype:", check_FrameType_HYT(p[36])) print(ahex(p[54:88]), ":from HytGW unpatched SrcId:", int.from_bytes(SrcId, byteorder='little'), " T:", int.from_bytes(bhex(DestId), byteorder='big'), "(", check_CallType_HYT(p[90]), ") TS:", Slot) # delete the UDP checksum and fill with 00 00 as No_CheckSum p[26:28] = bytearray.fromhex('00 00') if p[28:32] == b"ZZZZ": # if p[28] == 90 and p[29] == 90 and p[30] == 90 and p[31] == 90: # save the last HYT SeqNr (0x00 to 0xFF) of UDP payload for later use (format uint8) last_seq_HYT = p[32] # print(hex(last_seq_HYT)) # replace the Offset_0-3 ZZZZ with 00 00 00 00 (not sure - stamped packet as packet from base station/master) p[28:32] = bytearray.fromhex('00 00 00 00') # check if the Hytera packet is START_OF_TRANSMISSION SeqNr.0x0/Offset_4 and 0x2/Offset_8 if p[36] == 2 and p[32] == 0: print( "CALL_START_PAYLOAD possible not correct => need MODIFY...processing packet..." ) # insert the MMDVM payload VOICE_START p[54:88] = bhex(ambe_payload_mmdvm) print(ahex(p[54:88]), ":to RD985 replace with MMDVM(swapped) SrcId:", int.from_bytes(SrcId, byteorder='little'), " T:", int.from_bytes(bhex(DestId), byteorder='big'), "(", check_CallType_HYT(p[90]), ") TS:", Slot) print("CALL_START => now OK") # check if the Hytera packet is END_OF_TRANSMISSION 0x2222/Offset_18-19 and 0x3/Offset_8 if p[46:48] == bytearray.fromhex('22 22') and p[36] == 3: # if p[46] == 34 and p[47] == 34 and p[36]) == 3: print( "CALL_END_WITHOUT_PAYLOAD => need MODIFY...processing packet..." ) # p[28:32] = bytearray.fromhex('00 00 00 00') # correct some bytes in Hytera payload p[48:50] = bytearray.fromhex('11 11') p[51:53] = bytearray.fromhex('00 10') # insert the MMDVM payload VOICE_TERMINATOR_WITH_LC because the Hytera_GW do it NOT and fill all with 00 ! try: p[54:88] = bhex(ambe_payload_mmdvm) except NameError: print("No codec yet") print(ahex(p[54:88]), ":to RD985 replace with MMDVM(swapped) SrcId:", int.from_bytes(SrcId, byteorder='little'), " T:", int.from_bytes(bhex(DestId), byteorder='big'), "(", check_CallType_HYT(p[90]), ") TS:", Slot) print("CALL_END_WITH_Voiceterminator_LC => now OK") # write all changes to packet in netqueue p = modify_packet(p) pkt.set_payload(bytes(p)) # we accept now the packet in netqueue with all changes and transmit it pkt.accept()
def hashed_packet(self, _key, _data): _hash = bhex((hmac_new(_key, _data, sha1)).hexdigest()[:20]) return _data + _hash
class IPSC(DatagramProtocol): def __init__(self, _name, _config, _logger): # Housekeeping: create references to the configuration and status data for this IPSC instance. # Some configuration objects that are used frequently and have lengthy names are shortened # such as (self._master_sock) expands to (self._config['MASTER']['IP'], self._config['MASTER']['PORT']). # Note that many of them reference each other... this is the Pythonic way. # self._system = _name self._CONFIG = _config self._logger = _logger self._config = self._CONFIG['SYSTEMS'][self._system] # self._local = self._config['LOCAL'] self._local_id = self._local['RADIO_ID'] # self._master = self._config['MASTER'] self._master_stat = self._master['STATUS'] self._master_sock = self._master['IP'], self._master['PORT'] # self._peers = self._config['PEERS'] # # This is a regular list to store peers for the IPSC. At times, parsing a simple list is much less # Spendy than iterating a list of dictionaries... Maybe I'll find a better way in the future. Also # We have to know when we have a new peer list, so a variable to indicate we do (or don't) # args = () # Packet 'constructors' - builds the necessary control packets for this IPSC instance. # This isn't really necessary for anything other than readability (reduction of code golf) # # General Items self.TS_FLAGS = (self._local['MODE'] + self._local['FLAGS']) # # Peer Link Maintenance Packets self.MASTER_REG_REQ_PKT = (MASTER_REG_REQ + self._local_id + self.TS_FLAGS + IPSC_VER) self.MASTER_ALIVE_PKT = (MASTER_ALIVE_REQ + self._local_id + self.TS_FLAGS + IPSC_VER) self.PEER_LIST_REQ_PKT = (PEER_LIST_REQ + self._local_id) self.PEER_REG_REQ_PKT = (PEER_REG_REQ + self._local_id + IPSC_VER) self.PEER_REG_REPLY_PKT = (PEER_REG_REPLY + self._local_id + IPSC_VER) self.PEER_ALIVE_REQ_PKT = (PEER_ALIVE_REQ + self._local_id + self.TS_FLAGS) self.PEER_ALIVE_REPLY_PKT = (PEER_ALIVE_REPLY + self._local_id + self.TS_FLAGS) # # Master Link Maintenance Packets # self.MASTER_REG_REPLY_PKT is not static and must be generated when it is sent self.MASTER_ALIVE_REPLY_PKT = (MASTER_ALIVE_REPLY + self._local_id + self.TS_FLAGS + IPSC_VER) self.PEER_LIST_REPLY_PKT = (PEER_LIST_REPLY + self._local_id) # # General Link Maintenance Packets self.DE_REG_REQ_PKT = (DE_REG_REQ + self._local_id) self.DE_REG_REPLY_PKT = (DE_REG_REPLY + self._local_id) # self._logger.info('(%s) IPSC Instance Created: %s, %s:%s', self._system, int_id(self._local['RADIO_ID']), self._local['IP'], self._local['PORT']) #****************************************************** # SUPPORT FUNCTIONS FOR HANDLING IPSC OPERATIONS #****************************************************** # Determine if the provided peer ID is valid for the provided network # def valid_peer(self, _peerid): if _peerid in self._peers: return True return False # Determine if the provided master ID is valid for the provided network # def valid_master(self, _peerid): if self._master['RADIO_ID'] == _peerid: return True else: return False # De-register a peer from an IPSC by removing it's information # def de_register_peer(self, _peerid): # Iterate for the peer in our data if _peerid in self._peers.keys(): del self._peers[_peerid] self._logger.info('(%s) Peer De-Registration Requested for: %s', self._system, int_id(_peerid)) return else: self._logger.warning( '(%s) Peer De-Registration Requested for: %s, but we don\'t have a listing for this peer', self._system, int_id(_peerid)) pass # Take a received peer list and the network it belongs to, process and populate the # data structure in my_ipsc_config with the results, and return a simple list of peers. # def process_peer_list(self, _data): # Create a temporary peer list to track who we should have in our list -- used to find old peers we should remove. _temp_peers = [] # Determine the length of the peer list for the parsing iterator _peer_list_length = int(ahex(_data[5:7]), 16) # Record the number of peers in the data structure... we'll use it later (11 bytes per peer entry) self._local['NUM_PEERS'] = _peer_list_length / 11 self._logger.info( '(%s) Peer List Received from Master: %s peers in this IPSC', self._system, self._local['NUM_PEERS']) # Iterate each peer entry in the peer list. Skip the header, then pull the next peer, the next, etc. for i in range(7, _peer_list_length + 7, 11): # Extract various elements from each entry... _hex_radio_id = (_data[i:i + 4]) _hex_address = (_data[i + 4:i + 8]) _ip_address = IPAddr(_hex_address) _hex_port = (_data[i + 8:i + 10]) _port = int(ahex(_hex_port), 16) _hex_mode = (_data[i + 10:i + 11]) # Add this peer to a temporary PeerID list - used to remove any old peers no longer with us _temp_peers.append(_hex_radio_id) # This is done elsewhere for the master too, so we use a separate function _decoded_mode = process_mode_byte(_hex_mode) # If this entry WAS already in our list, update everything except the stats # in case this was a re-registration with a different mode, flags, etc. if _hex_radio_id in self._peers.keys(): self._peers[_hex_radio_id]['IP'] = _ip_address self._peers[_hex_radio_id]['PORT'] = _port self._peers[_hex_radio_id]['MODE'] = _hex_mode self._peers[_hex_radio_id]['MODE_DECODE'] = _decoded_mode self._peers[_hex_radio_id]['FLAGS'] = '' self._peers[_hex_radio_id]['FLAGS_DECODE'] = '' self._logger.debug('(%s) Peer Updated: %s', self._system, self._peers[_hex_radio_id]) # If this entry was NOT already in our list, add it. if _hex_radio_id not in self._peers.keys(): self._peers[_hex_radio_id] = { 'IP': _ip_address, 'PORT': _port, 'MODE': _hex_mode, 'MODE_DECODE': _decoded_mode, 'FLAGS': '', 'FLAGS_DECODE': '', 'STATUS': { 'CONNECTED': False, 'KEEP_ALIVES_SENT': 0, 'KEEP_ALIVES_MISSED': 0, 'KEEP_ALIVES_OUTSTANDING': 0, 'KEEP_ALIVES_RECEIVED': 0, 'KEEP_ALIVE_RX_TIME': 0 } } self._logger.debug('(%s) Peer Added: %s', self._system, self._peers[_hex_radio_id]) # Finally, check to see if there's a peer already in our list that was not in this peer list # and if so, delete it. for peer in self._peers.keys(): if peer not in _temp_peers: self.de_register_peer(peer) self._logger.warning( '(%s) Peer Deleted (not in new peer list): %s', self._system, int_id(peer)) #************************************************ # CALLBACK FUNCTIONS FOR USER PACKET TYPES #************************************************ def call_mon_status(self, _data): self._logger.debug( '(%s) Repeater Call Monitor Origin Packet Received: %s', self._system, ahex(_data)) def call_mon_rpt(self, _data): self._logger.debug( '(%s) Repeater Call Monitor Repeating Packet Received: %s', self._system, ahex(_data)) def call_mon_nack(self, _data): self._logger.debug( '(%s) Repeater Call Monitor NACK Packet Received: %s', self._system, ahex(_data)) def xcmp_xnl(self, _data): self._logger.debug('(%s) XCMP/XNL Packet Received: %s', self._system, ahex(_data)) def repeater_wake_up(self, _data): self._logger.debug('(%s) Repeater Wake-Up Packet Received: %s', self._system, ahex(_data)) def group_voice(self, _src_sub, _dst_sub, _ts, _end, _peerid, _data): self._logger.debug( '(%s) Group Voice Packet Received From: %s, IPSC Peer %s, Destination %s', self._system, int_id(_src_sub), int_id(_peerid), int_id(_dst_sub)) def private_voice(self, _src_sub, _dst_sub, _ts, _end, _peerid, _data): self._logger.debug( '(%s) Private Voice Packet Received From: %s, IPSC Peer %s, Destination %s', self._system, int_id(_src_sub), int_id(_peerid), int_id(_dst_sub)) def group_data(self, _src_sub, _dst_sub, _ts, _end, _peerid, _data): self._logger.debug( '(%s) Group Data Packet Received From: %s, IPSC Peer %s, Destination %s', self._system, int_id(_src_sub), int_id(_peerid), int_id(_dst_sub)) def private_data(self, _src_sub, _dst_sub, _ts, _end, _peerid, _data): self._logger.debug( '(%s) Private Data Packet Received From: %s, IPSC Peer %s, Destination %s', self._system, int_id(_src_sub), int_id(_peerid), int_id(_dst_sub)) def unknown_message(self, _packettype, _peerid, _data): self._logger.error( '(%s) Unknown Message - Type: %s From: %s Packet: %s', ahex(_packettype), self._system, int_id(_peerid), ahex(_data)) #************************************************ # IPSC SPECIFIC MAINTENANCE FUNCTIONS #************************************************ # Simple function to send packets - handy to have it all in one place for debugging # def send_packet(self, _packet, (_host, _port)): if self._local['AUTH_ENABLED']: _hash = bhex((hmac_new(self._local['AUTH_KEY'], _packet, sha1)).hexdigest()[:20]) _packet = _packet + _hash self.transport.write(_packet, (_host, _port))
def master_datagramReceived(self, _data, _sockaddr): # Keep This Line Commented Unless HEAVILY Debugging! # logger.debug('(%s) RX packet from %s -- %s', self._system, _sockaddr, ahex(_data)) # Extract the command, which is various length, all but one 4 significant characters -- RPTCL _command = _data[:4] if _command == DMRD: # DMRData -- encapsulated DMR data frame _peer_id = _data[11:15] if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == 'YES' \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: _seq = _data[4] _rf_src = _data[5:8] _dst_id = _data[8:11] _bits = _data[15] _slot = 2 if (_bits & 0x80) else 1 #_call_type = 'unit' if (_bits & 0x40) else 'group' if _bits & 0x40: _call_type = 'unit' elif (_bits & 0x23) == 0x23: _call_type = 'vcsbk' else: _call_type = 'group' _frame_type = (_bits & 0x30) >> 4 _dtype_vseq = (_bits & 0xF) # data, 1=voice header, 2=voice terminator; voice, 0=burst A ... 5=burst F _stream_id = _data[16:20] #logger.debug('(%s) DMRD - Seqence: %s, RF Source: %s, Destination ID: %s', self._system, _seq, int_id(_rf_src), int_id(_dst_id)) # ACL Processing if self._CONFIG['GLOBAL']['USE_ACL']: if not acl_check(_rf_src, self._CONFIG['GLOBAL']['SUB_ACL']): if self._laststrid[_slot] != _stream_id: logger.info('(%s) CALL DROPPED WITH STREAM ID %s FROM SUBSCRIBER %s BY GLOBAL ACL', self._system, int_id(_stream_id), int_id(_rf_src)) self._laststrid[_slot] = _stream_id return if _slot == 1 and not acl_check(_dst_id, self._CONFIG['GLOBAL']['TG1_ACL']): if self._laststrid[_slot] != _stream_id: logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY GLOBAL TS1 ACL', self._system, int_id(_stream_id), int_id(_dst_id)) self._laststrid[_slot] = _stream_id return if _slot == 2 and not acl_check(_dst_id, self._CONFIG['GLOBAL']['TG2_ACL']): if self._laststrid[_slot] != _stream_id: logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY GLOBAL TS2 ACL', self._system, int_id(_stream_id), int_id(_dst_id)) self._laststrid[_slot] = _stream_id return if self._config['USE_ACL']: if not acl_check(_rf_src, self._config['SUB_ACL']): if self._laststrid[_slot] != _stream_id: logger.info('(%s) CALL DROPPED WITH STREAM ID %s FROM SUBSCRIBER %s BY SYSTEM ACL', self._system, int_id(_stream_id), int_id(_rf_src)) self._laststrid[_slot] = _stream_id return if _slot == 1 and not acl_check(_dst_id, self._config['TG1_ACL']): if self._laststrid[_slot] != _stream_id: logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY SYSTEM TS1 ACL', self._system, int_id(_stream_id), int_id(_dst_id)) self._laststrid[_slot] = _stream_id return if _slot == 2 and not acl_check(_dst_id, self._config['TG2_ACL']): if self._laststrid[_slot]!= _stream_id: logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY SYSTEM TS2 ACL', self._system, int_id(_stream_id), int_id(_dst_id)) self._laststrid[_slot] = _stream_id return # The basic purpose of a master is to repeat to the peers if self._config['REPEAT'] == True: pkt = [_data[:11], '', _data[15:]] for _peer in self._peers: if _peer != _peer_id: pkt[1] = _peer self.transport.write(b''.join(pkt), self._peers[_peer]['SOCKADDR']) #logger.debug('(%s) Packet on TS%s from %s (%s) for destination ID %s repeated to peer: %s (%s) [Stream ID: %s]', self._system, _slot, self._peers[_peer_id]['CALLSIGN'], int_id(_peer_id), int_id(_dst_id), self._peers[_peer]['CALLSIGN'], int_id(_peer), int_id(_stream_id)) # Userland actions -- typically this is the function you subclass for an application self.dmrd_received(_peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data) elif _command == RPTL: # RPTLogin -- a repeater wants to login _peer_id = _data[4:8] # Check to see if we've reached the maximum number of allowed peers if len(self._peers) < self._config['MAX_PEERS']: # Check for valid Radio ID if acl_check(_peer_id, self._CONFIG['GLOBAL']['REG_ACL']) and acl_check(_peer_id, self._config['REG_ACL']): # Build the configuration data strcuture for the peer self._peers.update({_peer_id: { 'CONNECTION': 'RPTL-RECEIVED', 'CONNECTED': time(), 'PINGS_RECEIVED': 0, 'LAST_PING': time(), 'SOCKADDR': _sockaddr, 'IP': _sockaddr[0], 'PORT': _sockaddr[1], 'SALT': randint(0,0xFFFFFFFF), 'RADIO_ID': str(int(ahex(_peer_id), 16)), 'CALLSIGN': '', 'RX_FREQ': '', 'TX_FREQ': '', 'TX_POWER': '', 'COLORCODE': '', 'LATITUDE': '', 'LONGITUDE': '', 'HEIGHT': '', 'LOCATION': '', 'DESCRIPTION': '', 'SLOTS': '', 'URL': '', 'SOFTWARE_ID': '', 'PACKAGE_ID': '', }}) logger.info('(%s) Repeater Logging in with Radio ID: %s, %s:%s', self._system, int_id(_peer_id), _sockaddr[0], _sockaddr[1]) _salt_str = bytes_4(self._peers[_peer_id]['SALT']) self.send_peer(_peer_id, b''.join([RPTACK, _salt_str])) self._peers[_peer_id]['CONNECTION'] = 'CHALLENGE_SENT' logger.info('(%s) Sent Challenge Response to %s for login: %s', self._system, int_id(_peer_id), self._peers[_peer_id]['SALT']) else: self.transport.write(b''.join([MSTNAK, _peer_id]), _sockaddr) logger.warning('(%s) Invalid Login from %s Radio ID: %s Denied by Registation ACL', self._system, _sockaddr[0], int_id(_peer_id)) else: self.transport.write(b''.join([MSTNAK, _peer_id]), _sockaddr) logger.warning('(%s) Registration denied from Radio ID: %s Maximum number of peers exceeded', self._system, int_id(_peer_id)) elif _command == RPTK: # Repeater has answered our login challenge _peer_id = _data[4:8] if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == 'CHALLENGE_SENT' \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: _this_peer = self._peers[_peer_id] _this_peer['LAST_PING'] = time() _sent_hash = _data[8:] _salt_str = bytes_4(_this_peer['SALT']) _calc_hash = bhex(sha256(_salt_str+self._config['PASSPHRASE']).hexdigest()) if _sent_hash == _calc_hash: _this_peer['CONNECTION'] = 'WAITING_CONFIG' self.send_peer(_peer_id, b''.join([RPTACK, _peer_id])) logger.info('(%s) Peer %s has completed the login exchange successfully', self._system, _this_peer['RADIO_ID']) else: logger.info('(%s) Peer %s has FAILED the login exchange successfully', self._system, _this_peer['RADIO_ID']) self.transport.write(b''.join([MSTNAK, _peer_id]), _sockaddr) del self._peers[_peer_id] else: self.transport.write(b''.join([MSTNAK, _peer_id]), _sockaddr) logger.warning('(%s) Login challenge from Radio ID that has not logged in: %s', self._system, int_id(_peer_id)) elif _command == RPTC: # Repeater is sending it's configuraiton OR disconnecting if _data[:5] == RPTCL: # Disconnect command _peer_id = _data[5:9] if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == 'YES' \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: logger.info('(%s) Peer is closing down: %s (%s)', self._system, self._peers[_peer_id]['CALLSIGN'], int_id(_peer_id)) self.transport.write(b''.join([MSTNAK, _peer_id]), _sockaddr) del self._peers[_peer_id] else: _peer_id = _data[4:8] # Configure Command if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == 'WAITING_CONFIG' \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: _this_peer = self._peers[_peer_id] _this_peer['CONNECTION'] = 'YES' _this_peer['CONNECTED'] = time() _this_peer['LAST_PING'] = time() _this_peer['CALLSIGN'] = _data[8:16] _this_peer['RX_FREQ'] = _data[16:25] _this_peer['TX_FREQ'] = _data[25:34] _this_peer['TX_POWER'] = _data[34:36] _this_peer['COLORCODE'] = _data[36:38] _this_peer['LATITUDE'] = _data[38:46] _this_peer['LONGITUDE'] = _data[46:55] _this_peer['HEIGHT'] = _data[55:58] _this_peer['LOCATION'] = _data[58:78] _this_peer['DESCRIPTION'] = _data[78:97] _this_peer['SLOTS'] = _data[97:98] _this_peer['URL'] = _data[98:222] _this_peer['SOFTWARE_ID'] = _data[222:262] _this_peer['PACKAGE_ID'] = _data[262:302] self.send_peer(_peer_id, b''.join([RPTACK, _peer_id])) logger.info('(%s) Peer %s (%s) has sent repeater configuration', self._system, _this_peer['CALLSIGN'], _this_peer['RADIO_ID']) else: self.transport.write(b''.join([MSTNAK, _peer_id]), _sockaddr) logger.warning('(%s) Peer info from Radio ID that has not logged in: %s', self._system, int_id(_peer_id)) elif _command == RPTP: # RPTPing -- peer is pinging us _peer_id = _data[7:11] if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == "YES" \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: self._peers[_peer_id]['PINGS_RECEIVED'] += 1 self._peers[_peer_id]['LAST_PING'] = time() self.send_peer(_peer_id, b''.join([MSTPONG, _peer_id])) logger.debug('(%s) Received and answered RPTPING from peer %s (%s)', self._system, self._peers[_peer_id]['CALLSIGN'], int_id(_peer_id)) else: self.transport.write(b''.join([MSTNAK, _peer_id]), _sockaddr) logger.warning('(%s) Ping from Radio ID that is not logged in: %s', self._system, int_id(_peer_id)) elif _command == RPTO: _peer_id = _data[4:8] if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == 'YES' \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: logger.info('(%s) Peer %s (%s) has send options: %s', self._system, self._peers[_peer_id]['CALLSIGN'], int_id(_peer_id), _data[8:]) self.transport.write(b''.join([RPTACK, _peer_id]), _sockaddr) elif _command == DMRA: _peer_id = _data[4:8] logger.info('(%s) Recieved DMR Talker Alias from peer %s, subscriber %s', self._system, self._peers[_peer_id]['CALLSIGN'], int_id(_rf_src)) else: logger.error('(%s) Unrecognized command. Raw HBP PDU: %s', self._system, ahex(_data))
def peer_datagramReceived(self, _data, _sockaddr): # Keep This Line Commented Unless HEAVILY Debugging! # logger.debug('(%s) RX packet from %s -- %s', self._system, _sockaddr, ahex(_data)) # Validate that we receveived this packet from the master - security check! if self._config['MASTER_SOCKADDR'] == _sockaddr: # Extract the command, which is various length, but only 4 significant characters _command = _data[:4] if _command == DMRD: # DMRData -- encapsulated DMR data frame _peer_id = _data[11:15] if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation _seq = _data[4:5] _rf_src = _data[5:8] _dst_id = _data[8:11] _bits = _data[15] _slot = 2 if (_bits & 0x80) else 1 #_call_type = 'unit' if (_bits & 0x40) else 'group' if _bits & 0x40: _call_type = 'unit' elif (_bits & 0x23) == 0x23: _call_type = 'vcsbk' else: _call_type = 'group' _frame_type = (_bits & 0x30) >> 4 _dtype_vseq = (_bits & 0xF) # data, 1=voice header, 2=voice terminator; voice, 0=burst A ... 5=burst F _stream_id = _data[16:20] #logger.debug('(%s) DMRD - Sequence: %s, RF Source: %s, Destination ID: %s', self._system, int_id(_seq), int_id(_rf_src), int_id(_dst_id)) # ACL Processing if self._CONFIG['GLOBAL']['USE_ACL']: if not acl_check(_rf_src, self._CONFIG['GLOBAL']['SUB_ACL']): if self._laststrid[_slot] != _stream_id: logger.info('(%s) CALL DROPPED WITH STREAM ID %s FROM SUBSCRIBER %s BY GLOBAL ACL', self._system, int_id(_stream_id), int_id(_rf_src)) self._laststrid[_slot] = _stream_id return if _slot == 1 and not acl_check(_dst_id, self._CONFIG['GLOBAL']['TG1_ACL']): if self._laststrid[_slot] != _stream_id: logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY GLOBAL TS1 ACL', self._system, int_id(_stream_id), int_id(_dst_id)) self._laststrid[_slot] = _stream_id return if _slot == 2 and not acl_check(_dst_id, self._CONFIG['GLOBAL']['TG2_ACL']): if self._laststrid[_slot] != _stream_id: logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY GLOBAL TS2 ACL', self._system, int_id(_stream_id), int_id(_dst_id)) self._laststrid[_slot] = _stream_id return if self._config['USE_ACL']: if not acl_check(_rf_src, self._config['SUB_ACL']): if self._laststrid[_slot] != _stream_id: logger.info('(%s) CALL DROPPED WITH STREAM ID %s FROM SUBSCRIBER %s BY SYSTEM ACL', self._system, int_id(_stream_id), int_id(_rf_src)) self._laststrid[_slot] = _stream_id return if _slot == 1 and not acl_check(_dst_id, self._config['TG1_ACL']): if self._laststrid[_slot] != _stream_id: logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY SYSTEM TS1 ACL', self._system, int_id(_stream_id), int_id(_dst_id)) self._laststrid[_slot] = _stream_id return if _slot == 2 and not acl_check(_dst_id, self._config['TG2_ACL']): if self._laststrid[_slot] != _stream_id: logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY SYSTEM TS2 ACL', self._system, int_id(_stream_id), int_id(_dst_id)) self._laststrid[_slot] = _stream_id return # Userland actions -- typically this is the function you subclass for an application self.dmrd_received(_peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data) elif _command == MSTN: # Actually MSTNAK -- a NACK from the master _peer_id = _data[6:10] if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation logger.warning('(%s) MSTNAK Received. Resetting connection to the Master.', self._system) self._stats['CONNECTION'] = 'NO' # Disconnect ourselves and re-register self._stats['CONNECTED'] = time() elif _command == RPTA: # Actually RPTACK -- an ACK from the master # Depending on the state, an RPTACK means different things, in each clause, we check and/or set the state if self._stats['CONNECTION'] == 'RPTL_SENT': # If we've sent a login request... _login_int32 = _data[6:10] logger.info('(%s) Repeater Login ACK Received with 32bit ID: %s', self._system, int_id(_login_int32)) _pass_hash = sha256(b''.join([_login_int32, self._config['PASSPHRASE']])).hexdigest() _pass_hash = bhex(_pass_hash) self.send_master(b''.join([RPTK, self._config['RADIO_ID'], _pass_hash])) self._stats['CONNECTION'] = 'AUTHENTICATED' elif self._stats['CONNECTION'] == 'AUTHENTICATED': # If we've sent the login challenge... _peer_id = _data[6:10] if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation logger.info('(%s) Repeater Authentication Accepted', self._system) _config_packet = b''.join([\ self._config['RADIO_ID'],\ self._config['CALLSIGN'],\ self._config['RX_FREQ'],\ self._config['TX_FREQ'],\ self._config['TX_POWER'],\ self._config['COLORCODE'],\ self._config['LATITUDE'],\ self._config['LONGITUDE'],\ self._config['HEIGHT'],\ self._config['LOCATION'],\ self._config['DESCRIPTION'],\ self._config['SLOTS'],\ self._config['URL'],\ self._config['SOFTWARE_ID'],\ self._config['PACKAGE_ID']\ ]) self.send_master(b''.join([RPTC, _config_packet])) self._stats['CONNECTION'] = 'CONFIG-SENT' logger.info('(%s) Repeater Configuration Sent', self._system) else: self._stats['CONNECTION'] = 'NO' logger.error('(%s) Master ACK Contained wrong ID - Connection Reset', self._system) elif self._stats['CONNECTION'] == 'CONFIG-SENT': # If we've sent out configuration to the master _peer_id = _data[6:10] if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation logger.info('(%s) Repeater Configuration Accepted', self._system) if self._config['OPTIONS']: self.send_master(b''.join([RPTO, self._config['RADIO_ID'], self._config['OPTIONS']])) self._stats['CONNECTION'] = 'OPTIONS-SENT' logger.info('(%s) Sent options: (%s)', self._system, self._config['OPTIONS']) else: self._stats['CONNECTION'] = 'YES' self._stats['CONNECTED'] = time() logger.info('(%s) Connection to Master Completed', self._system) # If we are an XLX, send the XLX module request here. if self._config['MODE'] == 'XLXPEER': self.send_xlxmaster(self._config['RADIO_ID'], int(4000), self._config['MASTER_SOCKADDR']) self.send_xlxmaster(self._config['RADIO_ID'], self._config['XLXMODULE'], self._config['MASTER_SOCKADDR']) logger.info('(%s) Sending XLX Module request', self._system) else: self._stats['CONNECTION'] = 'NO' logger.error('(%s) Master ACK Contained wrong ID - Connection Reset', self._system) elif self._stats['CONNECTION'] == 'OPTIONS-SENT': # If we've sent out options to the master _peer_id = _data[6:10] if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation logger.info('(%s) Repeater Options Accepted', self._system) self._stats['CONNECTION'] = 'YES' self._stats['CONNECTED'] = time() logger.info('(%s) Connection to Master Completed with options', self._system) else: self._stats['CONNECTION'] = 'NO' logger.error('(%s) Master ACK Contained wrong ID - Connection Reset', self._system) elif _command == MSTP: # Actually MSTPONG -- a reply to RPTPING (send by peer) _peer_id = _data[7:11] if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation self._stats['PING_OUTSTANDING'] = False self._stats['NUM_OUTSTANDING'] = 0 self._stats['PINGS_ACKD'] += 1 logger.debug('(%s) MSTPONG Received. Pongs Since Connected: %s', self._system, self._stats['PINGS_ACKD']) elif _command == MSTC: # Actually MSTCL -- notify us the master is closing down _peer_id = _data[5:9] if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation self._stats['CONNECTION'] = 'NO' logger.info('(%s) MSTCL Recieved', self._system) elif _command == RPTS: if _data[:7] == RPTSBKN: logger.info('(%s) Received Site Beacon with Repeater ID: %s', self._system, int_id(_data[7:])) else: logger.error('(%s) Received an invalid command in packet: %s', self._system, ahex(_data))
def master_datagramReceived(self, _data, _sockaddr): # Keep This Line Commented Unless HEAVILY Debugging! # logger.debug('(%s) RX packet from %s -- %s', self._system, _sockaddr, ahex(_data)) # Extract the command, which is various length, all but one 4 significant characters -- RPTCL _command = _data[:4] if _command == 'DMRD': # DMRData -- encapsulated DMR data frame _peer_id = _data[11:15] if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == 'YES' \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: _seq = _data[4] _rf_src = _data[5:8] _dst_id = _data[8:11] _bits = int_id(_data[15]) _slot = 2 if (_bits & 0x80) else 1 #_call_type = 'unit' if (_bits & 0x40) else 'group' if _bits & 0x40: _call_type = 'unit' elif (_bits & 0x23) == 0x23: _call_type = 'vcsbk' else: _call_type = 'group' _frame_type = (_bits & 0x30) >> 4 _dtype_vseq = (_bits & 0xF) # data, 1=voice header, 2=voice terminator; voice, 0=burst A ... 5=burst F _stream_id = _data[16:20] #logger.debug('(%s) DMRD - Seqence: %s, RF Source: %s, Destination ID: %s', self._system, int_id(_seq), int_id(_rf_src), int_id(_dst_id)) # ACL Processing if self._CONFIG['GLOBAL']['USE_ACL']: if not acl_check(_rf_src, self._CONFIG['GLOBAL']['SUB_ACL']): if self._laststrid != _stream_id: logger.info('(%s) CALL DROPPED WITH STREAM ID %s FROM SUBSCRIBER %s BY GLOBAL ACL', self._system, int_id(_stream_id), int_id(_rf_src)) if _slot == 1: self._laststrid1 = _stream_id else: self._laststrid2 = _stream_id return if _slot == 1 and not acl_check(_dst_id, self._CONFIG['GLOBAL']['TG1_ACL']): if self._laststrid1 != _stream_id: logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY GLOBAL TS1 ACL', self._system, int_id(_stream_id), int_id(_dst_id)) self._laststrid1 = _stream_id return if _slot == 2 and not acl_check(_dst_id, self._CONFIG['GLOBAL']['TG2_ACL']): if self._laststrid2 != _stream_id: logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY GLOBAL TS2 ACL', self._system, int_id(_stream_id), int_id(_dst_id)) self._laststrid2 = _stream_id return if self._config['USE_ACL']: if not acl_check(_rf_src, self._config['SUB_ACL']): if self._laststrid != _stream_id: logger.info('(%s) CALL DROPPED WITH STREAM ID %s FROM SUBSCRIBER %s BY SYSTEM ACL', self._system, int_id(_stream_id), int_id(_rf_src)) if _slot == 1: self._laststrid1 = _stream_id else: self._laststrid2 = _stream_id return if _slot == 1 and not acl_check(_dst_id, self._config['TG1_ACL']): if self._laststrid1 != _stream_id: logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY SYSTEM TS1 ACL', self._system, int_id(_stream_id), int_id(_dst_id)) self._laststrid1 = _stream_id return if _slot == 2 and not acl_check(_dst_id, self._config['TG2_ACL']): if self._laststrid2 != _stream_id: logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY SYSTEM TS2 ACL', self._system, int_id(_stream_id), int_id(_dst_id)) self._laststrid2 = _stream_id return # The basic purpose of a master is to repeat to the peers if self._config['REPEAT'] == True: pkt = [_data[:11], '', _data[15:]] for _peer in self._peers: if _peer != _peer_id: pkt[1] = _peer self.transport.write(''.join(pkt), self._peers[_peer]['SOCKADDR']) #logger.debug('(%s) Packet on TS%s from %s (%s) for destination ID %s repeated to peer: %s (%s) [Stream ID: %s]', self._system, _slot, self._peers[_peer_id]['CALLSIGN'], int_id(_peer_id), int_id(_dst_id), self._peers[_peer]['CALLSIGN'], int_id(_peer), int_id(_stream_id)) # Userland actions -- typically this is the function you subclass for an application self.dmrd_received(_peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data) elif _command == 'RPTL': # RPTLogin -- a repeater wants to login _peer_id = _data[4:8] # Check to see if we've reached the maximum number of allowed peers if len(self._peers) < self._config['MAX_PEERS']: # Check for valid Radio ID if acl_check(_peer_id, self._CONFIG['GLOBAL']['REG_ACL']) and acl_check(_peer_id, self._config['REG_ACL']): # Build the configuration data strcuture for the peer self._peers.update({_peer_id: { 'CONNECTION': 'RPTL-RECEIVED', 'CONNECTED': time(), 'PINGS_RECEIVED': 0, 'LAST_PING': time(), 'SOCKADDR': _sockaddr, 'IP': _sockaddr[0], 'PORT': _sockaddr[1], 'SALT': randint(0,0xFFFFFFFF), 'RADIO_ID': str(int(ahex(_peer_id), 16)), 'CALLSIGN': '', 'RX_FREQ': '', 'TX_FREQ': '', 'TX_POWER': '', 'COLORCODE': '', 'LATITUDE': '', 'LONGITUDE': '', 'HEIGHT': '', 'LOCATION': '', 'DESCRIPTION': '', 'SLOTS': '', 'URL': '', 'SOFTWARE_ID': '', 'PACKAGE_ID': '', }}) logger.info('(%s) Repeater Logging in with Radio ID: %s, %s:%s', self._system, int_id(_peer_id), _sockaddr[0], _sockaddr[1]) _salt_str = hex_str_4(self._peers[_peer_id]['SALT']) self.send_peer(_peer_id, 'RPTACK'+_salt_str) self._peers[_peer_id]['CONNECTION'] = 'CHALLENGE_SENT' logger.info('(%s) Sent Challenge Response to %s for login: %s', self._system, int_id(_peer_id), self._peers[_peer_id]['SALT']) else: self.transport.write('MSTNAK'+_peer_id, _sockaddr) logger.warning('(%s) Invalid Login from Radio ID: %s Denied by Registation ACL', self._system, int_id(_peer_id)) else: self.transport.write('MSTNAK'+_peer_id, _sockaddr) logger.warning('(%s) Registration denied from Radio ID: %s Maximum number of peers exceeded', self._system, int_id(_peer_id)) elif _command == 'RPTK': # Repeater has answered our login challenge _peer_id = _data[4:8] if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == 'CHALLENGE_SENT' \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: _this_peer = self._peers[_peer_id] _this_peer['LAST_PING'] = time() _sent_hash = _data[8:] _salt_str = hex_str_4(_this_peer['SALT']) _calc_hash = bhex(sha256(_salt_str+self._config['PASSPHRASE']).hexdigest()) if _sent_hash == _calc_hash: _this_peer['CONNECTION'] = 'WAITING_CONFIG' self.send_peer(_peer_id, 'RPTACK'+_peer_id) logger.info('(%s) Peer %s has completed the login exchange successfully', self._system, _this_peer['RADIO_ID']) else: logger.info('(%s) Peer %s has FAILED the login exchange successfully', self._system, _this_peer['RADIO_ID']) self.transport.write('MSTNAK'+_peer_id, _sockaddr) del self._peers[_peer_id] else: self.transport.write('MSTNAK'+_peer_id, _sockaddr) logger.warning('(%s) Login challenge from Radio ID that has not logged in: %s', self._system, int_id(_peer_id)) elif _command == 'RPTC': # Repeater is sending it's configuraiton OR disconnecting if _data[:5] == 'RPTCL': # Disconnect command _peer_id = _data[5:9] if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == 'YES' \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: logger.info('(%s) Peer is closing down: %s (%s)', self._system, self._peers[_peer_id]['CALLSIGN'], int_id(_peer_id)) self.transport.write('MSTNAK'+_peer_id, _sockaddr) del self._peers[_peer_id] else: _peer_id = _data[4:8] # Configure Command if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == 'WAITING_CONFIG' \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: _this_peer = self._peers[_peer_id] _this_peer['CONNECTION'] = 'YES' _this_peer['CONNECTED'] = time() _this_peer['LAST_PING'] = time() _this_peer['CALLSIGN'] = _data[8:16] _this_peer['RX_FREQ'] = _data[16:25] _this_peer['TX_FREQ'] = _data[25:34] _this_peer['TX_POWER'] = _data[34:36] _this_peer['COLORCODE'] = _data[36:38] _this_peer['LATITUDE'] = _data[38:46] _this_peer['LONGITUDE'] = _data[46:55] _this_peer['HEIGHT'] = _data[55:58] _this_peer['LOCATION'] = _data[58:78] _this_peer['DESCRIPTION'] = _data[78:97] _this_peer['SLOTS'] = _data[97:98] _this_peer['URL'] = _data[98:222] _this_peer['SOFTWARE_ID'] = _data[222:262] _this_peer['PACKAGE_ID'] = _data[262:302] self.send_peer(_peer_id, 'RPTACK'+_peer_id) logger.info('(%s) Peer %s (%s) has sent repeater configuration', self._system, _this_peer['CALLSIGN'], _this_peer['RADIO_ID']) else: self.transport.write('MSTNAK'+_peer_id, _sockaddr) logger.warning('(%s) Peer info from Radio ID that has not logged in: %s', self._system, int_id(_peer_id)) elif _command == 'RPTP': # RPTPing -- peer is pinging us _peer_id = _data[7:11] if _peer_id in self._peers \ and self._peers[_peer_id]['CONNECTION'] == "YES" \ and self._peers[_peer_id]['SOCKADDR'] == _sockaddr: self._peers[_peer_id]['PINGS_RECEIVED'] += 1 self._peers[_peer_id]['LAST_PING'] = time() self.send_peer(_peer_id, 'MSTPONG'+_peer_id) logger.debug('(%s) Received and answered RPTPING from peer %s (%s)', self._system, self._peers[_peer_id]['CALLSIGN'], int_id(_peer_id)) else: self.transport.write('MSTNAK'+_peer_id, _sockaddr) logger.warning('(%s) Ping from Radio ID that is not logged in: %s', self._system, int_id(_peer_id)) else: logger.error('(%s) Unrecognized command. Raw HBP PDU: %s', self._system, ahex(_data))