P1sec / pycrate

A Python library to ease the development of encoders and decoders for various protocols and file formats; contains ASN.1 and CSN.1 compilers.
GNU Lesser General Public License v2.1
381 stars 132 forks source link

Encoding Decoding NAS5g message #125

Closed VineetTambe closed 3 years ago

VineetTambe commented 3 years ago

I am very new to pycrate and am trying to encode and decode a NAS5g message.

I have referred to most of the past encoding related issues and the pycrate-wiki to understand. However, when I try to implement the following code from the pycrate-wiki, it throws an error/ unexpected behavior:

from pycrate_mobile.NAS import *

def decode_nas_5g(nas_pdu):
    for pdu in nas_pdu:
        m, e = parse_NAS5G(pdu)
        assert( e == 0 )
        v = m.get_val()
        show(m)
        m.reautomate()
        assert( m.get_val() == v )
        m.set_val(v)
        assert( m.to_bytes() == pdu )
        if _with_json:
            t = m.to_json()
            m.from_json(t)
            assert( m.get_val() == v )

def test_my_code():
    IEs = {}
    IEs['CKSN']= 4
    IEs['LocUpdateType'] = {'Type': 1}
    IEs['LAI'] = (u'20820', 0x4321)
    IEs['ID'] = {'type': 1, 'ident': u'208209876543210'}
    IEs['AddUpdateParams'] = {'CSMO': 1, 'CSMT': 1}
    msg = MMLocationUpdatingRequest(val=IEs)

    show(msg)

    print("/n/n  encode message  /n/n")
    msg.to_bytes()
    print("/n/n  decode the messages  /n/n")
    decode_nas_5g(msg)

if __name__ == '__main__':
    test_my_code()

when I run the above code show(msg) gives expected output however msg.to_bytes() does not return anything and decode_nas_5g() throws an assertion error:

Traceback (most recent call last):
  File "mytest.py", line 75, in <module>
    test_my_code()
  File "mytest.py", line 69, in test_my_code
    decode_nas_5g(msg)
  File "mytest.py", line 32, in decode_nas_5g
    assert( e == 0 )
AssertionError

the error value I am getting is 111-> unspecified protocol error

I am sure that I am missing something obvious, please do bear with me. Thanks in advance.

VineetTambe commented 3 years ago

Okay, so I think I found out what I was doing wrong -

  1. Had to use FGMMRegistrationRequest() instead of MMLocationUpdatingRequest()
  2. Had to pass a tuple as input to decode_nas_5g()
  3. have to hexlify msg.to_bytes() before passing to tuple(map(unhexlify, (msg),)