본문 바로가기

취미

파이썬 scapy로 AP 만들기 - WEP 구현

그냥 끄적여보는것..



IEEE 802.11 wireless LAN manegement frame capabilities information

WEP,WPA 사용시 Cap에 Privacy 플래그 세팅

ex)

packet[Dot11Beacon].cap = packet[Dot11Beacon].cap | 0x1000


Beacon, Probe, Auth를 제외한 프레임의 FCfield 에 Protected flag 세팅

Ex)  FCfield | 0x40



Auth Body Frame

WEP Authentication 방식 지정

Open - Dot11Auth(algo=0,seqnum=0x02, status=0) Challenge 없이  연결.. 데이터는 암호화

shared - Dot11Auth(algo=1, seqnum=0x02,status=0) Challenge Handshake


algo=0 - Open

        1 - shared

seqnum

status 0 - successful



WEP

WEP 인증절차


• WEP = Wired Equivalency Protocol (유선 동등 프라이버시)

• RC4 stream cipher

• Purposes:

– Authentication

– Packet Encryption

Uses single key to authenticate all network users and encrypt all packets


WEP: Authentication

• WEP defines “shared-key authentication” for admission control to WEP-protected networks

• AP sends challenge C, STA WEP-encrypts it and responds with R







WEP에서 RC4암호화 알고리즘 상세기술

WEP는 64비트 암호화 방식과 128비트 암호화 방식인 WEP2가 있다.


WEP: RC4

• WEP-encrypted packets include an additional 4-byte header, and a 4-byte CRC-32

• WEP header includes the 24-bit IV and some flags

• CRC-32(ICV 값 생성) covers only the payload, and is used to determine if a packet has been successfully decrypted

WEP Packet Format

단말과 AP간 암호를 위하여 먼저 동일한 패스워드 문장으로부터 생성되는 4종류의 장기 공유 키를 자동 생성한다(KDF). 이 4개의 고유 키는 2비트의 KeyID로 각각 구분된다. 이후, 4개의 공유 키 중 하나를 선택하여 MAC 프레임에 대한 WEP 암호 시 사용한다.


IV : 3비트의 IV값은 매 프레임마다 임의로 선택되거나 단순 1씩 증가한다.

KeyID : 2bit의 길이를 가지며 송신측이 선택한 4가지의 WEP 비밀 키 중 하나의 KeyID 값을

명시하며, 이 키 ID는 세션 연결 후 변경되지 않는다.

not rekeying option... 802.1x dynamic wep에 WEP rekeying을 통해 중간에 key를 변경할 수 있도록 명시하였다.

key 이용시간은 WEP-rekey period에 명시한다. Default 1800초이고, 30초부터 19일까지 설정할 수 있다.






관련소스


crc32.py

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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
#!/usr/bin/env python
# CRC32 tools by Victor
 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
# References
# Calculating Reverse CRC http://www.danielvik.com/2010/10/calculating-reverse-crc.html
# Finding Reverse CRC Patch with Readable Characters http://www.danielvik.com/2012/01/finding-reverse-crc-patch-with-readable.html
# Rewinding CRC - Calculating CRC backwards
# http://www.danielvik.com/2013/07/rewinding-crc-calculating-crc-backwards.html
 
import argparse
import os
import sys
 
permitted_characters = set(
    map(ord, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_'))  # \w
 
testing = False
 
args = None
 
 
def get_poly():
    poly = parse_dword(args.poly)
    if args.msb:
        poly = reverseBits(poly)
    check32(poly)
    return poly
 
 
def get_input():
    if args.instr:
        return tuple(map(ord, args.instr))
    with args.infile as f:  # pragma: no cover
        return tuple(map(ord, f.read()))
 
 
def out(str):
    if not testing:  # pragma: no cover
        args.outfile.write(str)
        args.outfile.write(os.linesep)
 
table = []
table_reverse = []
 
 
def init_tables(poly, reverse=True):
    global table, table_reverse
    table = []
    # build CRC32 table
    for i in range(256):
        for j in range(8):
            if i & 1:
                i >>= 1
                i ^= poly
            else:
                i >>= 1
        table.append(i)
    assert len(table) == 256"table is wrong size"
    # build reverse table
    if reverse:
        table_reverse = []
        found_none = set()
        found_multiple = set()
        for i in range(256):
            found = []
            for j in range(256):
                if table[j] >> 24 == i:
                    found.append(j)
            table_reverse.append(tuple(found))
            if not found:
                found_none.add(i)
            elif len(found) > 1:
                found_multiple.add(i)
        assert len(table_reverse) == 256"reverse table is wrong size"
        if found_multiple:
            out('WARNING: Multiple table entries have an MSB in {0}'.format(
                rangess(found_multiple)))
        if found_none:
            out('ERROR: no MSB in the table equals bytes in {0}'.format(
                rangess(found_none)))
 
 
def calc(bytes, accum=0):
    accum = ~accum
    for b in bytes:
        accum = table[(accum ^ b) & 0xFF] ^ ((accum >> 8) & 0x00FFFFFF)
    accum = ~accum
    return accum & 0xFFFFFFFF
 
 
def rewind(accum, bytes):
    if not bytes:
        return (accum,)
    stack = [(len(bytes), ~accum)]
    solutions = []
    while stack:
        node = stack.pop()
        prev_offset = node[0- 1
        for i in table_reverse[(node[1>> 24) & 0xFF]:
            prevCRC = (((node[1] ^ table[i]) << 8|
                       (i ^ bytes[prev_offset])) & 0xFFFFFFFF
            if prev_offset:
                stack.append((prev_offset, prevCRC))
            else:
                solutions.append((~prevCRC) & 0xFFFFFFFF)
    return set(solutions)  # eliminate duplicates
 
 
def findReverse(desired, accum):
    solutions = []
    accum = ~accum
    stack = [(~desired,)]
    while stack:
        node = stack.pop()
        for j in table_reverse[(node[0>> 24) & 0xFF]:
            if len(node) == 4:
                a = accum
                bytes = []
                node = node[1:] + (j,)
                for i in range(3-1-1):
                    bytes.append((a ^ node[i]) & 0xFF)
                    a >>= 8
                    a ^= table[node[i]]
                solutions.append(tuple(bytes))
            else:
                stack.append(((node[0] ^ table[j]) << 8,) + node[1:] + (j,))
    return set(solutions)
 
# Tools
 
 
def parse_dword(x):
    return int(x, 0) & 0xFFFFFFFF
 
 
def reverseBits(x):
    # http://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
    # http://stackoverflow.com/a/20918545
    x = ((x & 0x55555555<< 1| ((x & 0xAAAAAAAA>> 1)
    x = ((x & 0x33333333<< 2| ((x & 0xCCCCCCCC>> 2)
    x = ((x & 0x0F0F0F0F<< 4| ((x & 0xF0F0F0F0>> 4)
    x = ((x & 0x00FF00FF<< 8| ((x & 0xFF00FF00>> 8)
    x = ((x & 0x0000FFFF<< 16| ((x & 0xFFFF0000>> 16)
    return x & 0xFFFFFFFF
 
# Compatibility with Python 2.6 and earlier.
if hasattr(int"bit_length"):
    def bit_length(num):
        return num.bit_length()
else:
    import math
 
    def bit_length(n):
        if n == 0:
            return 0
        bits = -32
        m = 0
        while n:
            m = n
            n >>= 32
            bits += 32
        while m:
            m >>= 1
            bits += 1
        return bits
 
 
def check32(poly):
    if poly & 0x80000000 == 0:
        out('WARNING: polynomial degree ({0}) != 32'.format(bit_length(poly)))
        out('         instead, try')
        out('         0x{0:08x} (reversed/lsbit-first)'.format(poly | 0x80000000))
        out('         0x{0:08x} (normal/msbit-first)'.format(reverseBits(poly | 0x80000000)))
 
 
def reciprocal(poly):
    ''' Return the reversed reciprocal (Koopman notatation) polynomial of a
        reversed (lsbit-first) polynomial '''
    return reverseBits((poly << 1| 1)
 
 
def print_num(num):
    ''' Write a numeric result in various forms '''
    out('hex: 0x{0:08x}'.format(num))
    out('dec:   {0:d}'.format(num))
    out('oct: 0o{0:011o}'.format(num))
    out('bin: 0b{0:032b}'.format(num))
 
import itertools
 
 
def ranges(i):
    for a, b in itertools.groupby(enumerate(i), lambda x: x[1- x[0]):
        b = list(b)
        yield b[0][1], b[-1][1]
 
 
def rangess(i):
    return ', '.join(map(lambda x: '[{0},{1}]'.format(*x), ranges(i)))
 
# Parsers
 
 
def get_parser():
    ''' Return the command-line parser '''
    parser = argparse.ArgumentParser(
        description="Reverse, undo, and calculate CRC32 checksums")
    subparsers = parser.add_subparsers(metavar='action')
 
    poly_flip_parser = argparse.ArgumentParser(add_help=False)
    subparser_group = poly_flip_parser.add_mutually_exclusive_group()
    subparser_group.add_argument(
        '-m''--msbit', dest="msb", action='store_true',
        help='treat the polynomial as normal (msbit-first)')
    subparser_group.add_argument('-l''--lsbit', action='store_false',
                                 help='treat the polynomial as reversed (lsbit-first) [default]')
 
    desired_poly_parser = argparse.ArgumentParser(add_help=False)
    desired_poly_parser.add_argument(
        'desired', type=str, help='[int] desired checksum')
 
    default_poly_parser = argparse.ArgumentParser(add_help=False)
    default_poly_parser.add_argument(
        'poly', default='0xEDB88320', type=str, nargs='?',
        help='[int] polynomial [default: 0xEDB88320]')
 
    accum_parser = argparse.ArgumentParser(add_help=False)
    accum_parser.add_argument(
        'accum', type=str, help='[int] accumulator (final checksum)')
 
    default_accum_parser = argparse.ArgumentParser(add_help=False)
    default_accum_parser.add_argument(
        'accum', default='0', type=str, nargs='?',
        help='[int] starting accumulator [default: 0]')
 
    outfile_parser = argparse.ArgumentParser(add_help=False)
    outfile_parser.add_argument('-o''--outfile',
                                metavar="f",
                                type=argparse.FileType('w'),
                                default=sys.stdout,
                                help="Output to a file instead of stdout")
 
    infile_parser = argparse.ArgumentParser(add_help=False)
    subparser_group = infile_parser.add_mutually_exclusive_group()
    subparser_group.add_argument('-i''--infile',
                                 metavar="f",
                                 type=argparse.FileType('rb'),
                                 default=sys.stdin,
                                 help="Input from a file instead of stdin")
    subparser_group.add_argument('-s''--str',
                                 metavar="s",
                                 type=str,
                                 default='',
                                 dest='instr',
                                 help="Use a string as input")
 
    subparser = subparsers.add_parser('flip', parents=[outfile_parser],
                                      help="flip the bits to convert normal(msbit-first) polynomials to reversed (lsbit-first) and vice versa")
    subparser.add_argument('poly', type=str, help='[int] polynomial')
    subparser.set_defaults(
        func=lambda: print_num(reverseBits(parse_dword(args.poly))))
 
    subparser = subparsers.add_parser('reciprocal', parents=[outfile_parser],
                                      help="find the reciprocal (Koopman notation) of a reversed (lsbit-first) polynomial and vice versa")
    subparser.add_argument('poly', type=str, help='[int] polynomial')
    subparser.set_defaults(func=reciprocal_callback)
 
    subparser = subparsers.add_parser('table', parents=[outfile_parser,
                                                        poly_flip_parser,
                                                        default_poly_parser],
                                      help="generate a lookup table for a polynomial")
    subparser.set_defaults(func=table_callback)
 
    subparser = subparsers.add_parser('reverse', parents=[
        outfile_parser,
        poly_flip_parser,
        desired_poly_parser,
        default_accum_parser,
        default_poly_parser],
        help="find a patch that causes the CRC32 checksum to become a desired value")
    subparser.set_defaults(func=reverse_callback)
 
    subparser = subparsers.add_parser('undo', parents=[
        outfile_parser,
        poly_flip_parser,
        accum_parser,
        default_poly_parser,
        infile_parser],
        help="rewind a CRC32 checksum")
    subparser.add_argument('-n''--len', metavar='l', type=str,
                           default='0', help='[int] number of bytes to rewind [default: 0]')
    subparser.set_defaults(func=undo_callback)
 
    subparser = subparsers.add_parser('calc', parents=[
        outfile_parser,
        poly_flip_parser,
        default_accum_parser,
        default_poly_parser,
        infile_parser],
        help="calculate the CRC32 checksum")
    subparser.set_defaults(func=calc_callback)
 
    return parser
 
 
def reciprocal_callback():
    poly = parse_dword(args.poly)
    check32(poly)
    print_num(reciprocal(poly))
 
 
def table_callback():
    # initialize tables
    init_tables(get_poly(), False)
    # print table
    out('[{0}]'.format(', '.join(map('0x{0:08x}'.format, table))))
 
 
def reverse_callback():
    # initialize tables
    init_tables(get_poly())
    # find reverse bytes
    desired = parse_dword(args.desired)
    accum = parse_dword(args.accum)
    # 4-byte patch
    patches = findReverse(desired, accum)
    for patch in patches:
        out('4 bytes: {{0x{0:02x}, 0x{1:02x}, 0x{2:02x}, 0x{3:02x}}}'.format(*patch))
        checksum = calc(patch, accum)
        out('verification checksum: 0x{0:08x} ({1})'.format(
            checksum, 'OK' if checksum == desired else 'ERROR'))
    # 6-byte alphanumeric patches
    for i in permitted_characters:
        for j in permitted_characters:
            bytes = [i, j]
            patches = findReverse(desired, calc(bytes, accum))
            for patch in patches:
                if all(p in permitted_characters for p in patch):
                    bytes.extend(patch)
                    out('alternative: {1}{2}{3}{4}{5}{6} ({0})'.format(
                        'OK' if calc(bytes, accum) == desired else 'ERROR'*map(chr, bytes)))
 
 
def undo_callback():
    # initialize tables
    init_tables(get_poly())
    # calculate checksum
    accum = parse_dword(args.accum)
    maxlen = int(args.len0)
    data = get_input()
    if not 0 < maxlen <= len(data):
        maxlen = len(data)
    out('rewinded {0}/{1} ({2:.2f}%)'.format(maxlen, len(data),
        maxlen * 100.0 / len(data) if len(data) else 100))
    for solution in rewind(accum, data[-maxlen:]):
        out('')
        print_num(solution)
 
 
def calc_callback():
    # initialize tables
    init_tables(get_poly(), False)
    # calculate checksum
    accum = parse_dword(args.accum)
    data = get_input()
    out('data len: {0}'.format(len(data)))
    out('')
    print_num(calc(data, accum))
 
 
def main(argv=None):
    ''' Runs the program and handles command line options '''
    parser = get_parser()
 
    # Parse arguments and run the function
    global args
    args = parser.parse_args(argv)
    args.func()
 
if __name__ == '__main__':
    main()  # pragma: no cover
 
cs



KDF.py

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
 
def wepkey64(val):
    pseed = [0000]
    randNumber = 0
    k64 = [""""""""]
    i = 0
    j = 0
    tmp = 0
    while i < len(val):
        pseed[i % 4] ^= ord(val[i])
        i += 1
 
    randNumber = pseed[0| (pseed[1<< 8| (pseed[2<< 16| (pseed[3<< 32)
 
    i = 0
    while i < 4:
        j = 0
        while j < 5:
            randNumber = (randNumber * 0x343fd + 0x269ec3) & 0xffffffff
            tmp = (randNumber >> 16) & 0xff
            s = str(hex(tmp)[2:])  # Remove the \0x: 5d
            s = s.zfill(2)
            k64[i] += s.upper()
            j += 1
        i += 1
 
    return k64
cs



rc4.py

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
# Please be aware that while functional, this script is intended for educational
# use as a visual aid, and is not designed for further implementation.
 
 
import string
import binascii
 
 
def KSA(key):
    table = []
    j = 0
 
    for i in range(256):  # Initialize a sorted table from numbers 0 to 255
        table.append(i)
    # Mess up the sorted table, based on the secret key
    for i in range(256):
        j = (j + table[i] + ord(key[i % len(key)])) % 256
        table[i], table[j] = table[j], table[i]
    return table
 
 
def PRGA(table):
    i = 0
    j = 0
    while True:
        i = (i + 1) % 256
        j = (j + table[i]) % 256
        table[i], table[j] = table[j], table[i]
        yield table[(table[i] + table[j]) % 256]
 
 
def encode(key, text):
    newtext = []
    randomized = KSA(key)
    keystream = PRGA(randomized)
    encrypted = ''
 
    for c in text:
        unic = ord(c)  # Get an int value
        h = hex(unic ^ next(keystream)) # Get a hex value: \0x5d
        s = str(h[2:])  # Remove the \0x: 5d
        s = s.zfill(2)  # Ensure there are always two digits, nothing like '6'
        newtext.append(s)
    for i in newtext:
        encrypted += str(i)
    print(encrypted)
 
 
def decode(key, text):
    h = binascii.unhexlify(text)
    randomized = KSA(key)
    keystream = PRGA(randomized)
    decrypted = ''
    for i in h:
        n = int(i)  # Get the numerical value for the hex character
        a = n ^ next(keystream)  # Get the unencrypted numerical value from table
        c = chr(a)  # Get the ASCII value for that number
        decrypted += c
    print(decrypted)
 
 
def RC4(key, text):
    if all(c in string.hexdigits for c in text):
        decode(key, text)
    else:
        encode(key, text)
cs


'취미' 카테고리의 다른 글

AWS DynamoDB, Lambda를 이용한 auto scaling #2  (2) 2017.02.20
JWT(JSON Web Token)  (0) 2017.02.20
AWS DynamoDB, Lambda를 이용한 auto scaling #1  (0) 2017.02.19
아이폰 MAC address 랜덤화  (3) 2016.04.09
802.11 Management Frame Format  (0) 2016.02.15