aboutsummaryrefslogtreecommitdiffstats
path: root/src/simos_server.rb
blob: 3c7a52a28f7552c7509765ef758a35a4a4e63377 (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
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
#!/usr/bin/env ruby
# encoding: UTF-8
=begin
This file is part of softSIM.

softSIM 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.

softSIM 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 sofSIM.  If not, see <http://www.gnu.org/licenses/>.

Copyright (C) 2011 Kevin "tsaitgaist" Redon kevredon@mail.tsaitgaist.info
=end
require_relative 'sap/server'
require_relative 'lib/apdu'
require 'socket'
require 'xml'

# SAP server using a SIM backup file
class SIMServer < Server

  def initialize(io,path="sim.xml")
    super(io)
    @xml_path = path
  end

#====================
#== main functions ==
#====================

  # read file
  def connect

    begin
      xml = IO.read(@xml_path)
      doc = XML::Parser.string(xml)
      @card = doc.parse
    rescue
      log("connect","can't read #{@xml_path}",3)
      status = create_message("STATUS_IND",[[0x08,[0x02]]])
      send(status)
      sleep 1
      retry
    end
    
    # select MF
    select([0x3f,0x00])
    
    # card ready
    return true
  end
  
  def disconnect
    @card.save(@xml_path)
    log("disconnect","save SIM in #{@xml_path}",3)
  end

  # get ATR
  def atr
    raise "connect to card to get ATR" unless @card
    return @card.find_first("/sim")["atr"].hex2arr
  end

  # send APDU and get response
  def apdu(request)
    raise "connect to card to send APDU" unless @card
    # check the size
    return [0x6f,0x00] unless request.length>=5
    # I can only handle SIM APDU (class A0)
    return [0x6e,0x00] unless request[0]==0xa0
    # default
    data = []
    sw = [0x6f,0x00]
    # the instruction
    case request[1]
    when 0xa4 # SELECT
      # remove the last response
      @response = nil
      # verify the apdu
      if request[2,2]!=[0x00,0x00] then
        # incorrect parameter P1 or P2
        sw = [0x6b,0x00]
      elsif request[4]!=0x02 then
        # incorrect parameter P3
        sw = [0x67,0x02]
      else
        # is the file ID present ?
        if request.length==7 then
		  # check if the directory can be selected
		  file_id = request[5,2]
		  node = select(file_id)
		  if node then
		    # file selected, response awaiting
		    @response = node.find_first("./header").content.hex2arr
		    sw = [0x9f,@response.length]
        log("APDU select","file selected : #{file_id.to_hex_disp}",3)
		  else
		    # out of range (invalid address)
		    sw = [0x94,0x02]
        log("APDU select","file not found/accessible : #{file_id.to_hex_disp}",3)
		  end
		else
		  # out of range (invalid address)
		  sw = [0x94,0x02]
          log("APDU select","file not found/accessible : #{file_id.to_hex_disp}",3)
		end
      end
    when 0xc0 # GET RESPONSE
      # verify the apdu
      if request[2,2]!=[0x00,0x00] then
        # incorrect parameter P1 or P2
        sw = [0x6b,0x00]
      elsif !@response then
        # technical problem with no diagnostic given
        sw = [0x6f,0x00]
      elsif request[4]!=@response.length then
        # incorrect parameter P3
        sw = [0x67,@response.length]
      else
        # return the response
        data = @response
        sw = [0x90,0x00]
      end
    when 0xf2 # STATUS
      # get current directory
      status = @pwd.find_first("./header").content.hex2arr
      # verify the apdu
      if request[2,2]!=[0x00,0x00] then
        # incorrect parameter P1 or P2
        sw = [0x6b,0x00]
      elsif request[4]!=status.length then
        # incorrect parameter P3
        sw = [0x67,status.length]
      else
        # return the status
        data = status
        sw = [0x90,0x00]
      end
    when 0xb0 # READ BINARY
      # is an ef selected ?
      type = file_info
      if type[:type]!="EF" then
        # no EF selected
        sw = [0x94,0x00]
      elsif type[:structure]!="transparent" then
        # file is inconsitent with the command
        sw = [0x94,0x08]
      else
        body = @selected.find_first("./body").content.hex2arr
        offset = (request[2]<<8)+request[3]
        length = request[4]
        if offset>=body.length or offset+length>body.length then
          # out of range (invalid address)
          sw = [0x94,0x02]
        else
          # return the data
          data = body[offset,length]
          sw = [0x90,0x00]
        end
      end
    when 0xd6 # UPDATE BINARY
      # is an transparent ef selected ?
      type = file_info
      if type[:type]!="EF" then
        # no EF selected
        sw = [0x94,0x00]
      elsif type[:structure]!="transparent" then
        # file is inconsitent with the command
        sw = [0x94,0x08]
      else
        body = @selected.find_first("./body").content.hex2arr
        offset = (request[2]<<8)+request[3]
        length = request[4]
        if offset>=body.length or offset+length>body.length then
          # out of range (invalid address)
          sw = [0x94,0x02]
        else
          # write the data
          body[offset,length] = request[5,length]
          sw = [0x90,0x00]
        end
      end
    when 0x88 # RUN GSM ALGORITHM
      # verify the apdu
      if request[2,2]!=[0x00,0x00] then
        # incorrect parameter P1 or P2
        sw = [0x6b,0x00]
      elsif request[4]!=0x10 then
        # incorrect parameter P3
        sw = [0x67,0x00]
      elsif ![file_info(@pwd)[:id],file_info(@pwd.find_first(".."))[:id]].include? [0x7F,0x20] then
        # not under DF_GSM, file is inconsistent with the command
        sw = [0x94,0x08]
      else
        # return the SRES/Kc
        # do I have it ?
        tuple = @card.find_first("/sim/a38/tuple[@rand='#{request[5,16].to_hex}']")
        if tuple then
          @response = tuple["sres"].hex2arr+tuple["kc"].hex2arr
          sw = [0x9f,@response.length]
        else
          # memory problem
          sw = [0x92,0x40]
        end
      end
    
    else # unknown instruction byte
      sw = [0x6d,0x00]
    end
    return data+sw
  end

#===================
#== SIM functions ==
#===================

  # select file using the file ID
  # node representing the file is returned
  # nil is return if file does not exist or is unaccessible
  def select(id)

    # find file
    if id==[0x3f,0x00] then
      # the MF is always selectable
      response = @card.find_first("/sim/file[@id='#{id.to_hex}']")
    elsif result=@pwd.find_first("./file[@id='#{id.to_hex}']") then
      # any file which is an immediate child of the current directory
      response = result
    elsif file_info(@pwd)[:type]=="DF" and result=@pwd.find_first("../file[@id='#{id.to_hex}']") then
      # any DF which is an immediate child of the parent of the current DF
      response = result
    elsif result=@pwd.find_first("..") and file_info(result)[:id]==id then
      # the parent of the current directory
      response = result
    elsif file_info(@pwd)[:id]==id then
      # the current DF
      response = @pwd
    else
      # file not found
      response = nil
    end
    
    # remember new selected file
    @selected = response if response
    # get current directory
    if ["MF","DF"].include? file_info(@selected)[:type] then
      # selected of a DF
      @pwd = @selected
    else
      # selected is an ED, DF is parent
      @pwd = @selected.find_first("..")
    end
    
    return response
  end
  
  # get type of selected file, and structure if EF
  def file_info(file=@selected)
    
    to_return = {}
    header = @selected.find_first("./header").content.hex2arr
    
    # file id
    to_return[:id] = [header[4],header[5]]
    
    # file type
    type = case header[6]
    when 0
      "RFU"
    when 1
      "MF"
    when 2
      "DF"
    when 4
      "EF"
    else
      "unknown"
    end
    to_return[:type] = type

    # EF struture
    if type=="EF" then
      # structure
      structure = case header[13]
      when 0
        "transparent"
      when 1
        "linear fixed"
      when 3
        "cyclic"
      else
        "unknown"
      end
      to_return[:structure] = structure
    end
    
    return to_return
  end

end