Blame view

RIOT/dist/tools/sniffer/sniffer.py 5.48 KB
a752c7ab   elopes   add first test an...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
  #!/usr/bin/env python
  # -*- coding: utf-8 -*-
  '''
  (C) 2012, Mariano Alvira <mar@devl.org>
  (C) 2014, Oliver Hahm <oliver.hahm@inria.fr>
  (C) 2015, Hauke Petersen <hauke.petersen@fu-berlin.de>
  (C) 2015, Martine Lenders <mlenders@inf.fu-berlin.de>
  (C) 2015, Cenk Gündoğan <cnkgndgn@gmail.com>
  
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
  are met:
  1. Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
  3. Neither the name of the Institute nor the names of its contributors
     may be used to endorse or promote products derived from this software
     without specific prior written permission.
  
  THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  SUCH DAMAGE.
  '''
  
  from __future__ import print_function
  import sys
  import re
  import socket
  from time import sleep, time
  from struct import pack
  from serial import Serial
  
  # PCAP setup
  MAGIC = 0xa1b2c3d4
  MAJOR = 2
  MINOR = 4
  ZONE = 0
  SIG = 0
  SNAPLEN = 0xffff
  NETWORK = 230       # 802.15.4 no FCS
  
  
  def configure_interface(port, channel):
      line = ""
      iface = 0
      port.write(b'ifconfig\n')
      while True:
          line = port.readline()
          if line == '':
              print("Application has no network interface defined",
                    file=sys.stderr)
              sys.exit(2)
          match = re.search(r'^Iface +(\d+)', line.decode())
          if match is not None:
              iface = int(match.group(1))
              break
  
      # set channel, raw mode, and promiscuous mode
      print('ifconfig %d set chan %d' % (iface, channel), file=sys.stderr)
      print('ifconfig %d raw' % iface, file=sys.stderr)
      print('ifconfig %d promisc' % iface, file=sys.stderr)
      port.write(('ifconfig %d set chan %d\n' % (iface, channel)).encode())
      port.write(('ifconfig %d raw\n' % iface).encode())
      port.write(('ifconfig %d promisc\n' % iface).encode())
  
  
  def generate_pcap(port, out):
      # count incoming packets
      count = 0
      # output overall PCAP header
      out.write(pack('<LHHLLLL', MAGIC, MAJOR, MINOR, ZONE, SIG, SNAPLEN,
                     NETWORK))
      sys.stderr.write("RX: %i\r" % count)
      while True:
          line = port.readline().rstrip()
  
          pkt_header = re.match(r">? *rftest-rx --- len 0x(\w\w).*",
                                line.decode())
          if pkt_header:
              now = time()
              sec = int(now)
              usec = int((now - sec) * 1000000)
              length = int(pkt_header.group(1), 16)
              out.write(pack('<LLLL', sec, usec, length, length))
              out.flush()
              count += 1
              sys.stderr.write("RX: %i\r" % count)
              continue
  
          pkt_data = re.match(r"(0x\w\w )+", line.decode())
          if pkt_data:
              for part in line.decode().split(' '):
                  byte = re.match(r"0x(\w\w)", part)
                  if byte:
                      out.write(pack('<B', int(byte.group(1), 16)))
              out.flush()
  
  
  def connect(argv):
      connType = argv[1]
  
      conn = None
      if connType == "serial":
          # open serial port
          try:
              conn = Serial(argv[2], argv[3], dsrdtr=0, rtscts=0,
                            timeout=1)
          except IOError:
              print("error opening serial port", file=sys.stderr)
              sys.exit(2)
      elif connType == "socket":
          host = argv[2]
          port = int(argv[3])
  
          try:
              sock = socket.socket()
              sock.connect((host, port))
              conn = sock.makefile("r+b", bufsize=0)
          except IOError:
              print("error connecting to %s:%s" % (host, port), file=sys.stderr)
              sys.exit(2)
      else:
          print("error: unsupported connection type. Use \"serial\" or \"socket\"")
          sys.exit(2)
  
      return conn
  
  def main(argv):
      if len(argv) < 5:
          print("Usage: %s serial tty baudrate channel [outfile]\n"
                "       %s socket host port channel [outfile]" % (argv[0], argv[0]),
                file=sys.stderr)
          print("       channel = 11-26", file=sys.stderr)
          sys.exit(2)
  
      conn = connect(argv)
  
      sleep(1)
      configure_interface(conn, int(argv[4]))
      sleep(1)
  
      # figure out where to write
      try:
          sys.stderr.write('trying to open file %s\n' % argv[5])
          outfile = open(argv[5], 'w+b')
      except IndexError:
          if sys.version_info > (3,):
              outfile = sys.stdout.buffer
          else:
              outfile = sys.stdout
  
      try:
          generate_pcap(conn, outfile)
      except KeyboardInterrupt:
          conn.close()
          print()
          sys.exit(2)
  
  
  if __name__ == "__main__":
      main(sys.argv)