aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/sim-rest-server.py
blob: 62498b45c7221767c84ae6119c02a3d5f765e082 (plain)
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
#!/usr/bin/env python3

# RESTful HTTP service for performing authentication against USIM cards
#
# (C) 2021 by Harald Welte <laforge@osmocom.org>
#
# 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 2 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/>.

import json
import sys
import argparse

from klein import Klein

from pySim.transport import ApduTracer
from pySim.transport.pcsc import PcscSimLink
from pySim.commands import SimCardCommands
from pySim.cards import UsimCard
from pySim.exceptions import *

class ApduPrintTracer(ApduTracer):
    def trace_response(self, cmd, sw, resp):
        #print("CMD: %s -> RSP: %s %s" % (cmd, sw, resp))
        pass

def connect_to_card(slot_nr:int):
    tp = PcscSimLink(slot_nr, apdu_tracer=ApduPrintTracer())
    tp.connect()

    scc = SimCardCommands(tp)
    card = UsimCard(scc)

    # this should be part of UsimCard, but FairewavesSIM breaks with that :/
    scc.cla_byte = "00"
    scc.sel_ctrl = "0004"

    card.read_aids()
    card.select_adf_by_aid(adf='usim')

    return tp, scc, card

class ApiError:
    def __init__(self, msg:str):
        self.msg = msg

    def __str__(self):
        return json.dumps({'error': {'message':self.msg}})


def set_headers(request):
    request.setHeader('Content-Type', 'application/json')

class SimRestServer:
    app = Klein()

    @app.handle_errors(NoCardError)
    def no_card_error(self, request, failure):
        set_headers(request)
        request.setResponseCode(410)
        return str(ApiError("No SIM card inserted in slot"))

    @app.handle_errors(ReaderError)
    def reader_error(self, request, failure):
        set_headers(request)
        request.setResponseCode(404)
        return str(ApiError("Reader Error: Specified SIM Slot doesn't exist"))

    @app.handle_errors(ProtocolError)
    def protocol_error(self, request, failure):
        set_headers(request)
        request.setResponseCode(500)
        return str(ApiError("Protocol Error"))

    @app.handle_errors(SwMatchError)
    def sw_match_error(self, request, failure):
        set_headers(request)
        request.setResponseCode(500)
        return str(ApiError("Card Communication Error %s" % failure))


    @app.route('/sim-auth-api/v1/slot/<int:slot>')
    def auth(self, request, slot):
        """REST API endpoint for performing authentication against a USIM.
           Expects a JSON body containing RAND and AUTN.
           Returns a JSON body containing RES, CK, IK and Kc."""
        try:
            # there are two hex-string JSON parameters in the body: rand and autn
            content = json.loads(request.content.read())
            rand = content['rand']
            autn = content['autn']
        except:
            set_headers(request)
            request.setResponseCode(400)
            return str(ApiError("Malformed Request"))

        tp, scc, card = connect_to_card(slot)

        card.select_adf_by_aid(adf='usim')
        res, sw = scc.authenticate(rand, autn)

        tp.disconnect()

        set_headers(request)
        return json.dumps(res, indent=4)

    @app.route('/sim-info-api/v1/slot/<int:slot>')
    def info(self, request, slot):
        """REST API endpoint for obtaining information about an USIM.
        Expects empty body in request.
        Returns a JSON body containing ICCID, IMSI."""

        tp, scc, card = connect_to_card(slot)

        card.select_adf_by_aid(adf='usim')
        iccid, sw = card.read_iccid()
        imsi, sw = card.read_imsi()
        res = {"imsi": imsi, "iccid": iccid }

        tp.disconnect()

        set_headers(request)
        return json.dumps(res, indent=4)


def main(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument("-H", "--host", help="Host/IP to bind HTTP to", default="localhost")
    parser.add_argument("-p", "--port", help="TCP port to bind HTTP to", default=8000)
    #parser.add_argument("-v", "--verbose", help="increase output verbosity", action='count', default=0)

    args = parser.parse_args()

    srr = SimRestServer()
    srr.app.run(args.host, args.port)

if __name__ == "__main__":
    main(sys.argv)