Module: Meshtastic::MQTT

Defined in:
lib/meshtastic/mqtt.rb

Class Method Summary collapse

Class Method Details

.authorsObject

Author(s)

0day Inc. <support@0dayinc.com>



370
371
372
373
374
# File 'lib/meshtastic/mqtt.rb', line 370

public_class_method def self.authors
  "AUTHOR(S):
    0day Inc. <support@0dayinc.com>
  "
end

.connect(opts = {}) ⇒ Object

Supported Method Parameters

mqtt_obj = Meshtastic::MQQT.connect(

host: 'optional - mqtt host (default: mqtt.meshtastic.org)',
port: 'optional - mqtt port (defaults: 1883)',
username: 'optional - mqtt username (default: meshdev)',
password: 'optional - (default: large4cats)'

)



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/meshtastic/mqtt.rb', line 25

public_class_method def self.connect(opts = {})
  # Publicly available MQTT server / credentials by default
  host = opts[:host] ||= 'mqtt.meshtastic.org'
  port = opts[:port] ||= 1883
  username = opts[:username] ||= 'meshdev'
  password = opts[:password] ||= 'large4cats'

  mqtt_obj = MQTTClient.connect(
    host: host,
    port: port,
    username: username,
    password: password
  )

  mqtt_obj.client_id = SecureRandom.random_bytes(8).unpack1('H*')

  mqtt_obj
rescue StandardError => e
  raise e
end

.disconnect(opts = {}) ⇒ Object

Supported Method Parameters

mqtt_obj = Meshtastic.disconnect(

mqtt_obj: 'required - mqtt_obj returned from #connect method'

)



359
360
361
362
363
364
365
366
# File 'lib/meshtastic/mqtt.rb', line 359

public_class_method def self.disconnect(opts = {})
  mqtt_obj = opts[:mqtt_obj]

  mqtt_obj.disconnect if mqtt_obj
  nil
rescue StandardError => e
  raise e
end

.gps_search(opts = {}) ⇒ Object

Supported Method Parameters

mqtt_obj = Meshtastic.gps_search(

lat: 'required - latitude float (e.g. 37.7749)',
lon: 'required - longitude float (e.g. -122.4194)',

)



342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/meshtastic/mqtt.rb', line 342

public_class_method def self.gps_search(opts = {})
  lat = opts[:lat]
  lon = opts[:lon]

  raise 'ERROR: Latitude and Longitude are required' unless lat && lon

  gps_arr = [lat.to_f, lon.to_f]

  Geocoder.search(gps_arr)
rescue StandardError => e
  raise e
end

.helpObject

Display Usage for this Module



378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# File 'lib/meshtastic/mqtt.rb', line 378

public_class_method def self.help
  puts "USAGE:
    mqtt_obj = #{self}.connect(
      host: 'optional - mqtt host (default: mqtt.meshtastic.org)',
      port: 'optional - mqtt port (defaults: 1883)',
      username: 'optional - mqtt username (default: meshdev)',
      password: 'optional - (default: large4cats)'
    )

    #{self}.subscribe(
      mqtt_obj: 'required - mqtt_obj object returned from #connect method',
      root_topic: 'optional - root topic (default: msh)',
      region: 'optional - region e.g. 'US/VA', etc (default: US)',
      channel: 'optional - channel name e.g. '2/stat/#' (default: '2/e/LongFast/#')',
      psks: 'optional - hash of :channel => psk key value pairs (default: { LongFast: 'AQ==' })',
      qos: 'optional - quality of service (default: 0)',
      json: 'optional - JSON output (default: false)',
      filter: 'optional - comma-delimited string(s) to filter on in message (default: nil)',
      gps_metadata: 'optional - include GPS metadata in output (default: false)'
    )

    #{self}.gps_search(
      lat: 'required - latitude float (e.g. 37.7749)',
      lon: 'required - longitude float (e.g. -122.4194)',
    )

    mqtt_obj = #{self}.disconnect(
      mqtt_obj: 'required - mqtt_obj object returned from #connect method'
    )

    #{self}.authors
  "
end

.subscribe(opts = {}) ⇒ Object

Supported Method Parameters

Meshtastic::MQQT.subscribe(

mqtt_obj: 'required - mqtt_obj returned from #connect method'
root_topic: 'optional - root topic (default: msh)',
region: 'optional - region e.g. 'US/VA', etc (default: US)',
channel: 'optional - channel name e.g. "2/stat/#" (default: "2/e/LongFast/#")',
psks: 'optional - hash of :channel => psk key value pairs (default: { LongFast: "AQ==" })',
qos: 'optional - quality of service (default: 0)',
filter: 'optional - comma-delimited string(s) to filter on in message (default: nil)',
gps_metadata: 'optional - include GPS metadata in output (default: false)',
include_raw: 'optional - include raw packet data in output (default: false)'

)



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/meshtastic/mqtt.rb', line 198

public_class_method def self.subscribe(opts = {})
  mqtt_obj = opts[:mqtt_obj]
  root_topic = opts[:root_topic] ||= 'msh'
  region = opts[:region] ||= 'US'
  channel = opts[:channel] ||= '2/e/LongFast/#'
  # TODO: Support Array of PSKs and attempt each until decrypted

  public_psk = '1PG7OiApB1nwvP+rz05pAQ=='
  psks = opts[:psks] ||= { LongFast: public_psk }
  raise 'ERROR: psks parameter must be a hash of :channel => psk key value pairs' unless psks.is_a?(Hash)

  psks[:LongFast] = public_psk if psks[:LongFast] == 'AQ=='
  psks = get_cipher_keys(psks: psks)

  qos = opts[:qos] ||= 0
  json = opts[:json] ||= false
  filter = opts[:filter]
   = opts[:gps_metadata] ||= false
  include_raw = opts[:include_raw] ||= false

  # NOTE: Use MQTT Explorer for topic discovery
  full_topic = "#{root_topic}/#{region}/#{channel}"
  puts "Subscribing to: #{full_topic}"
  mqtt_obj.subscribe(full_topic, qos)

  filter_arr = filter.to_s.split(',').map(&:strip)
  mqtt_obj.get_packet do |packet_bytes|
    raw_packet = packet_bytes.to_s.b if include_raw
    raw_topic = packet_bytes.topic ||= ''
    raw_payload = packet_bytes.payload ||= ''

    begin
      disp = false
      decoded_payload_hash = {}
      message = {}
      stdout_message = ''

      if json
        decoded_payload_hash = JSON.parse(raw_payload, symbolize_names: true)
      else
        decoded_payload = Meshtastic::ServiceEnvelope.decode(raw_payload)
        decoded_payload_hash = decoded_payload.to_h
      end

      message = decoded_payload_hash[:packet] if decoded_payload_hash.keys.include?(:packet)
      message[:topic] = raw_topic
      message[:node_id_from] = "!#{message[:from].to_i.to_s(16)}"
      message[:node_id_to] = "!#{message[:to].to_i.to_s(16)}"

      # If encrypted_message is not nil, then decrypt
      # the message prior to decoding.
      encrypted_message = message[:encrypted]
      if encrypted_message.to_s.length.positive?
        packet_id = message[:id]
        packet_from = message[:from]

        nonce_packet_id = [packet_id].pack('V').ljust(8, "\x00")
        nonce_from_node = [packet_from].pack('V').ljust(8, "\x00")
        nonce = "#{nonce_packet_id}#{nonce_from_node}".b

        psk = psks[:LongFast]
        target_chanel = decoded_payload_hash[:channel_id].to_s.to_sym
        psk = psks[target_chanel] if psks.keys.include?(target_chanel)
        dec_psk = Base64.strict_decode64(psk)

        cipher = OpenSSL::Cipher.new('AES-128-CTR')
        cipher = OpenSSL::Cipher.new('AES-256-CTR') if dec_psk.length == 32
        cipher.decrypt
        cipher.key = dec_psk
        cipher.iv = nonce

        decrypted = cipher.update(encrypted_message) + cipher.final
        message[:decoded] = Meshtastic::Data.decode(decrypted).to_h
        message[:encrypted] = :decrypted
      end

      if message[:decoded]
        # payload = Meshtastic::Data.decode(message[:decoded][:payload]).to_h
        payload = message[:decoded][:payload]
        msg_type = message[:decoded][:portnum]
        message[:decoded][:payload] = recursively_decode_payloads(
          object: payload,
          msg_type: msg_type,
          gps_metadata: 
        )
      end

      message[:raw_packet] = raw_packet if include_raw
      decoded_payload_hash[:packet] = message
      unless block_given?
        message[:stdout] = 'pretty'
        stdout_message = JSON.pretty_generate(decoded_payload_hash)
      end
    rescue Google::Protobuf::ParseError,
           JSON::GeneratorError,
           ArgumentError => e

      message[:decrypted] = e.message if e.message.include?('key must be')
      message[:decrypted] = 'unable to decrypt - psk?' if e.message.include?('occurred during parsing')
      decoded_payload_hash[:packet] = message
      unless block_given?
        puts "WARNING: #{e.inspect} - MSG IS >>>"
        # puts e.backtrace
        message[:stdout] = 'inspect'
        stdout_message = decoded_payload_hash.inspect
      end

      next
    ensure
      filter_arr = [message[:id].to_s] if filter.nil?
      flat_message = message.values.join(' ')

      disp = true if filter_arr.first == message[:id] ||
                     filter_arr.all? { |filter| flat_message.include?(filter) }

      if disp
        if block_given?
          yield decoded_payload_hash
        else
          puts "\n"
          puts '-' * 80
          puts 'MSG:'
          puts stdout_message
          puts '-' * 80
          puts "\n\n\n"
        end
      else
        print '.'
      end
    end
  end
rescue Interrupt
  puts "\nCTRL+C detected. Exiting..."
rescue StandardError => e
  raise e
ensure
  mqtt_obj.disconnect if mqtt_obj
end