bnet-authenticator 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 32216dd69cf3a1e7339eefd3874b68857d821ece
4
+ data.tar.gz: 25f2fe14ffd941325155ad4debe42f738d0d5e28
5
+ SHA512:
6
+ metadata.gz: e77c7baba9fc31fe14f8a6c2f727b58eab522185e4f1f106bc63c89eafc2f3c67e7c11f1539cbb095734f712a9089a5eda6b3f783140ad9b3f15f44d39e3a295
7
+ data.tar.gz: a1be870018f6e50de709aae78a5c7d06f9e89fe13c42274d57aeb9b7f439a098e19cf63990c8859b5181c1f2322ce3e833e7355778a32377694689f865b84a2f
data/.yardopts ADDED
@@ -0,0 +1 @@
1
+ --no-private lib/bnet/authenticator.rb - README.md COPYING
data/COPYING ADDED
@@ -0,0 +1,10 @@
1
+ The MIT License
2
+ ===============
3
+
4
+ Copyright 2014 ZHANG Yi <zhangyi.cn@gmail.com>.
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
7
+
8
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
9
+
10
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Gemfile ADDED
@@ -0,0 +1,3 @@
1
+ source "https://rubygems.org"
2
+
3
+ gemspec
data/README.md ADDED
@@ -0,0 +1,43 @@
1
+ Bnet::Authenticator
2
+ ====
3
+ Ruby implementation of the Battle.net Mobile Authenticator.
4
+
5
+ [![Build Status](https://travis-ci.org/dorentus/bnet-authenticator.png?branch=master)](https://travis-ci.org/dorentus/bnet-authenticator)
6
+
7
+ Installation
8
+ ====
9
+ $ [sudo] gem install bnet-authenticator
10
+
11
+ Using the library
12
+ ====
13
+ >> require 'bnet/authenticator'
14
+
15
+ Request a new authenticator
16
+ ----
17
+ >> authenticator = Bnet::Authenticator.new(:region => :US)
18
+ => Serial: US-1402-2552-9200
19
+ Secret: c1307afe865735653d981771dff04ceb79b1a353
20
+ Restoration Code: EQXCPB2YVE
21
+
22
+ Get a token
23
+ ----
24
+ >> authenticator.caculate_token
25
+ => 80185191
26
+
27
+ Restore an authenticator from server
28
+ ----
29
+ >> Bnet::Authenticator.new(:serial => 'CN-1402-1943-1283', :restorecode => '4CKBN08QEB')
30
+ => Serial: CN-1402-1943-1283
31
+ Secret: 4202aa2182640745d8a807e0fe7e34b30c1edb23
32
+ Restoration Code: 4CKBN08QEB
33
+
34
+ Initialize an authenticator with given serial and secret
35
+ ----
36
+ >> Bnet::Authenticator.new(:serial => 'CN-1402-1943-1283', :secret => '4202aa2182640745d8a807e0fe7e34b30c1edb23')
37
+ => Serial: CN-1402-1943-1283
38
+ Secret: 4202aa2182640745d8a807e0fe7e34b30c1edb23
39
+ Restoration Code: 4CKBN08QEB
40
+
41
+ Using the command-line tool
42
+ ====
43
+ Run `bna` and follow instructions.
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ require 'rake/testtask'
2
+
3
+ Rake::TestTask.new do |t|
4
+ t.libs << 'test'
5
+ end
6
+
7
+ desc "Run tests"
8
+ task :default => :test
data/bin/bna ADDED
@@ -0,0 +1,68 @@
1
+ #!/usr/bin/env ruby
2
+ require 'optparse'
3
+ require 'ostruct'
4
+ require 'fileutils'
5
+ require 'bnet/authenticator'
6
+
7
+ module Bnet
8
+
9
+ COMMANDS = {}
10
+ %w(help new token info restore).each do |command|
11
+ require "bnet/commands/#{command}"
12
+ COMMANDS[command.to_sym] = Kernel.const_get('Bnet').const_get('Commands').const_get("#{command.capitalize}Command").new
13
+ end
14
+
15
+ def self.parse_global_options(args)
16
+ parser = OptionParser.new do |opts|
17
+ opts.banner = "Usage: #{File.basename $0} <command> [options] [params]\n\n" +
18
+ "Available commands:\n\n" +
19
+ COMMANDS.values.reduce('') { |m, v| m += "#{v.help}\n" }
20
+ end
21
+
22
+ global_help_message = parser.help
23
+
24
+ parser.order!(args)
25
+
26
+ return args, global_help_message
27
+ end
28
+
29
+ def self.print_error(message)
30
+ prefix = 'Error'
31
+ if $stderr.tty?
32
+ prefix = "\e[4;31m#{prefix}\e[00m"
33
+ end
34
+ $stderr.puts "#{prefix}: #{message}"
35
+ $stderr.puts
36
+ end
37
+
38
+ begin
39
+ # parse global options
40
+ args, global_help_message = parse_global_options(ARGV)
41
+
42
+ # run command
43
+ command = args.shift || :help
44
+
45
+ raise Bnet::InvalidCommandException.new("invalid command #{command.to_s}") unless COMMANDS.has_key?(command.to_sym)
46
+
47
+ COMMANDS[command.to_sym].parse_and_run(args)
48
+ rescue Bnet::InvalidCommandException, OptionParser::InvalidOption => e
49
+ print_error e.message unless e.message.nil?
50
+
51
+ command = e.command
52
+ if COMMANDS.has_key? command
53
+ puts COMMANDS[command].help
54
+ else
55
+ puts global_help_message
56
+ end
57
+
58
+ if e.instance_of?(Bnet::InvalidCommandException) && e.message.nil?
59
+ exit 0
60
+ else
61
+ exit 1
62
+ end
63
+ rescue Errno::EACCES, Errno::ENOENT => e
64
+ print_error e.message
65
+ exit 1
66
+ end
67
+
68
+ end
@@ -0,0 +1,28 @@
1
+ # -*- encoding: utf-8 -*-
2
+ $:.push File.expand_path("../lib", __FILE__)
3
+
4
+ require 'bnet/authenticator/version'
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = 'bnet-authenticator'
8
+ s.version = Bnet::Authenticator::VERSION
9
+ s.platform = Gem::Platform::RUBY
10
+ s.authors = ['ZHANG Yi']
11
+ s.email = ['zhangyi.cn@gmail.com']
12
+ s.homepage = 'https://github.com/dorentus/bnet-authenticator'
13
+ s.summary = %q{Battle.net Mobile Authenticator}
14
+ s.description = %q{Ruby implementation of the Battle.net Mobile Authenticator}
15
+ s.license = 'MIT'
16
+
17
+ s.required_ruby_version = '>= 1.9.3'
18
+
19
+ if s.respond_to?(:add_development_dependency)
20
+ s.add_development_dependency 'rake', '~> 0'
21
+ s.add_development_dependency 'yard', '~> 0'
22
+ end
23
+
24
+ s.files = `git ls-files`.split("\n") - %w(.travis.yml .gitignore)
25
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
26
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
27
+ s.require_paths = ['lib']
28
+ end
@@ -0,0 +1,134 @@
1
+ require 'bnet/authenticator/core'
2
+
3
+ module Bnet
4
+
5
+ # The battlenet authenticator
6
+ class Authenticator
7
+
8
+ # @!attribute [r] serial
9
+ # @return [String] the serial of the authenticator
10
+ attr_reader :serial
11
+
12
+ # @!attribute [r] secret
13
+ # @return [String] hexified secret of the authenticator
14
+ attr_reader :secret
15
+
16
+ # @!attribute [r] restoration code
17
+ # @return [String] the restoration code of the authenticator
18
+ attr_reader :restorecode
19
+
20
+ # @!attribute [r] region
21
+ # @return [Symbol] the region of the authenticator
22
+ attr_reader :region
23
+
24
+ # Get a new authenticator
25
+ #
26
+ # == Example:
27
+ # >> Bnet::Authenticator.new(:serial => 'CN-1402-1943-1283', :secret => '4202aa2182640745d8a807e0fe7e34b30c1edb23')
28
+ # => Serial: CN-1402-1943-1283
29
+ # Secret: 4202aa2182640745d8a807e0fe7e34b30c1edb23
30
+ # Restoration Code: 4CKBN08QEB
31
+ #
32
+ # >> Bnet::Authenticator.new(:region => :US)
33
+ # => Serial: US-1402-2552-9200
34
+ # Secret: c1307afe865735653d981771dff04ceb79b1a353
35
+ # Restoration Code: EQXCPB2YVE
36
+ #
37
+ # >> Bnet::Authenticator.new(:serial => 'CN-1402-1943-1283', :restorecode => '4CKBN08QEB')
38
+ # => Serial: CN-1402-1943-1283
39
+ # Secret: 4202aa2182640745d8a807e0fe7e34b30c1edb23
40
+ # Restoration Code: 4CKBN08QEB
41
+ #
42
+ # == Parameters:
43
+ # options:
44
+ # A `Hash`. Valid key combanations are:
45
+ #
46
+ # - `:serial` & `:secret`
47
+ #
48
+ # Create a new authenticator with given `serial` and `secret`.
49
+ #
50
+ # - `:region`
51
+ #
52
+ # Request for a new authenticator using given `region`
53
+ #
54
+ # - `:serial` & `:restorecode`
55
+ #
56
+ # Reqeust to restore an authenticator using given `serial` and `restorecode`
57
+ #
58
+ def initialize(options = {})
59
+ options = Core.normalize_options(options)
60
+
61
+ if options.has_key?(:serial) && options.has_key?(:secret)
62
+ @serial, @secret = options[:serial], options[:secret]
63
+ elsif options.has_key?(:region)
64
+ @serial, @secret = Core.request_new_serial(options[:region], options[:model])
65
+ elsif options.has_key?(:serial) && options.has_key?(:restorecode)
66
+ @serial, @secret = Core.request_restore(options[:serial], options[:restorecode])
67
+ else
68
+ raise BadInputError.new('invalid options')
69
+ end
70
+ end
71
+
72
+ # Get the restoration code of this authenticator
73
+ # @return [String]
74
+ def restorecode
75
+ return nil if @serial.nil? or @secret.nil?
76
+
77
+ code_bin = Digest::SHA1.digest(normalized_serial + binary_secret).reverse[0, 10].reverse
78
+ Core.encode_restorecode(code_bin)
79
+ end
80
+
81
+ # Get the region of this authenticator
82
+ # @return [Symbol]
83
+ def region
84
+ Core.extract_region(@serial)
85
+ end
86
+
87
+ # Caculate token using this authenticator's `secret` and given `timestamp`
88
+ # (defaults to current time)
89
+ #
90
+ # @param timestamp [Integer] a UNIX timestamp in seconds
91
+ # @return [String] current token
92
+ def caculate_token(timestamp = nil)
93
+ Core.caculate_token(@secret, timestamp)
94
+ end
95
+
96
+ # Caculate token using giving `secret` and given `timestamp`
97
+ # (defaults to current time)
98
+ #
99
+ # @param secret [String] hexified secret string of an authenticator
100
+ # @param timestamp [Integer] a UNIX timestamp in seconds
101
+ # @return [String] current token
102
+ def self.caculate_token(secret, timestamp = nil)
103
+ Core.caculate_token(secret, timestamp)
104
+ end
105
+
106
+ # Request for server timestamp
107
+ #
108
+ # @param region [Symbol]
109
+ # @return [Integer] server timestamp
110
+ def self.request_server_time(region)
111
+ Core.request_server_time(region)
112
+ end
113
+
114
+ # String representation of this authenticator
115
+ # @return [String]
116
+ def to_s
117
+ "Serial: #{serial}\nSecret: #{secret}\nRestoration Code: #{restorecode}"
118
+ end
119
+
120
+ private
121
+
122
+ def normalized_serial
123
+ Core.normalize_serial(@serial)
124
+ end
125
+
126
+ def binary_secret
127
+ return nil if @secret.nil?
128
+
129
+ @secret.as_hex_to_bin
130
+ end
131
+
132
+ end
133
+
134
+ end
@@ -0,0 +1,243 @@
1
+ require 'digest/sha1'
2
+ require 'digest/hmac'
3
+ require 'net/http'
4
+ require 'bnet/support'
5
+
6
+ module Bnet
7
+
8
+ class Authenticator
9
+
10
+ class RequestFailedError < StandardError; end
11
+ class BadInputError < StandardError; end
12
+
13
+ module Core
14
+
15
+ RSA_MOD = 104890018807986556874007710914205443157030159668034197186125678960287470894290830530618284943118405110896322835449099433232093151168250152146023319326491587651685252774820340995950744075665455681760652136576493028733914892166700899109836291180881063097461175643998356321993663868233366705340758102567742483097
16
+ RSA_KEY = 257
17
+ AUTHENTICATOR_HOSTS = {
18
+ :CN => "mobile-service.battlenet.com.cn",
19
+ :EU => "m.eu.mobileservice.blizzard.com",
20
+ :US => "m.us.mobileservice.blizzard.com",
21
+ }
22
+ ENROLLMENT_REQUEST_PATH = '/enrollment/enroll.htm'
23
+ TIME_REQUEST_PATH = '/enrollment/time.htm'
24
+ RESTORE_INIT_REQUEST_PATH = '/enrollment/initiatePaperRestore.htm'
25
+ RESTORE_VALIDATE_REQUEST_PATH = '/enrollment/validatePaperRestore.htm'
26
+
27
+ RESTORECODE_MAP = (0..32).reduce({}) do |memo, c|
28
+ memo[c] = case
29
+ when c < 10 then c + 48
30
+ else
31
+ c += 55
32
+ c += 1 if c > 72 # S
33
+ c += 1 if c > 75 # O
34
+ c += 1 if c > 78 # L
35
+ c += 1 if c > 82 # I
36
+ c
37
+ end
38
+ memo
39
+ end
40
+ RESTORECODE_MAP_INVERSE = RESTORECODE_MAP.invert
41
+
42
+ def self.caculate_token(secret, timestamp = nil)
43
+ secret = normalize_options(:secret => secret)[:secret]
44
+ return nil if secret.nil?
45
+
46
+ timestamp = Time.now.getutc.to_i if timestamp.nil?
47
+
48
+ current = timestamp / 30
49
+ next_timestamp = (current + 1) * 30
50
+
51
+ digest = Digest::HMAC.digest([current].pack('Q>'), secret.as_hex_to_bin, Digest::SHA1)
52
+
53
+ start_position = digest[19].ord & 0xf
54
+
55
+ token = '%08d' % (digest[start_position, 4].as_bin_to_i % 100000000)
56
+
57
+ return token, next_timestamp
58
+ end
59
+
60
+ def self.normalize_serial(serial)
61
+ serial.to_s.gsub(/-/, '').upcase
62
+ end
63
+
64
+ def self.prettify_serial(serial)
65
+ serial = normalize_serial(serial)
66
+ "#{serial[0, 2]}-" + serial[2, 12].scan(/.{4}/).join('-')
67
+ end
68
+
69
+ private
70
+
71
+ def self.normalize_options(options)
72
+ return nil if options.nil?
73
+
74
+ if options.has_key?(:serial)
75
+ normalized_serial = normalize_serial(options[:serial])
76
+ region = extract_region(normalized_serial)
77
+
78
+ if AUTHENTICATOR_HOSTS.has_key?(region) && normalized_serial =~ /\d{12}/
79
+ options[:serial] = prettify_serial(normalized_serial)
80
+ else
81
+ raise BadInputError.new("bad serial #{options[:serial]}")
82
+ end
83
+ end
84
+
85
+ if options.has_key?(:region)
86
+ region = options[:region].to_s.upcase.to_sym
87
+ raise BadInputError.new("unsupported region #{region}") unless AUTHENTICATOR_HOSTS.has_key?(region)
88
+
89
+ options[:region] = region
90
+ end
91
+
92
+ if options.has_key?(:restorecode)
93
+ restorecode = options[:restorecode].upcase
94
+
95
+ raise BadInputError.new("bad restoration code #{restorecode}") unless restorecode =~ /[0-9A-Z]{10}/
96
+
97
+ options[:restorecode] = restorecode
98
+ end
99
+
100
+ if options.has_key?(:secret)
101
+ secret = options[:secret]
102
+ raise BadInputError.new("bad secret #{secret}") unless secret =~ /[0-9a-f]{40}/i
103
+ end
104
+
105
+ options
106
+ end
107
+
108
+ def self.extract_region(serial)
109
+ serial.to_s[0, 2].upcase.to_sym
110
+ end
111
+
112
+ def self.create_one_time_pad(length)
113
+ (0..1.0/0.0).reduce('') do |memo, i|
114
+ break memo if memo.length >= length
115
+ memo << Digest::SHA1.digest(rand().to_s)
116
+ end[0, length]
117
+ end
118
+
119
+ def self.encode_restorecode(bin)
120
+ bin.bytes.map do |v|
121
+ RESTORECODE_MAP[v & 0x1f]
122
+ end.as_bytes_to_bin
123
+ end
124
+
125
+ def self.decode_restorecode(str)
126
+ str.bytes.map do |c|
127
+ RESTORECODE_MAP_INVERSE[c]
128
+ end.as_bytes_to_bin
129
+ end
130
+
131
+ def self.request_new_serial(region, model = nil)
132
+ model ||= 'bn/authenticator'
133
+
134
+ # one-time key of 37 bytes
135
+ k = create_one_time_pad(37)
136
+
137
+ # make byte[56]
138
+ # 00 byte[1] 固定为1
139
+ # 01 byte[37] 37位的随机数据,只使用一次,用来解密服务器返回数据
140
+ # 38 byte[2] 区域码: CN, US, EU, etc.
141
+ # 40 byte[16] 设备模型数据(手机型号字符串,可随意)
142
+ bytes = [1]
143
+ bytes.concat(k.bytes.to_a)
144
+ bytes.concat(region.to_s.bytes.take(2))
145
+ bytes.concat(model.ljust(16, "\0").bytes.take(16))
146
+
147
+ # encrypted using RSA
148
+ e = (bytes.as_bytes_to_i ** RSA_KEY % RSA_MOD).to_bin
149
+
150
+ # request to server
151
+ request = Net::HTTP::Post.new(ENROLLMENT_REQUEST_PATH)
152
+ request.content_type = 'application/octet-stream'
153
+ request.body = e
154
+
155
+ response = Net::HTTP.new(AUTHENTICATOR_HOSTS[region]).start do |http|
156
+ http.request(request)
157
+ end
158
+
159
+ # server error
160
+ # note: server is unhappy with certain `k`s, such as:
161
+ # [206, 166, 17, 196, 68, 160, 142, 111, 216, 196, 170, 19, 49, 239, 101, 93, 114, 241, 57, 223, 150, 80, 219, 114, 95, 20, 42, 142, 193, 115, 79, 71, 189, 147, 242, 111, 27].as_bytes_to_bin
162
+ raise RequestFailedError.new("Error requesting for new serial: #{response.code}") if response.code.to_i(10) != 200
163
+
164
+ # the first 8 bytes be server timestamp in milliseconds
165
+ # server_timestamp_in_ms = response.body[0, 8].as_bin_to_i
166
+
167
+ # the rest 37 bytes, to be XORed with `k`
168
+ decrypted = response.body[8, 37].bytes.zip(k.bytes).reduce('') do |memo, pair|
169
+ memo << (pair[0] ^ pair[1]).chr
170
+ end
171
+
172
+ # now
173
+ # the first 20 bytes be the authenticator secret
174
+ # the rest 17 bytes be the authenticator serial (readable string begins with CN-, US-, EU-, etc.)
175
+ secret = decrypted[0, 20]
176
+ serial = decrypted[20, 17]
177
+
178
+ return serial, secret.as_bin_to_hex
179
+ end
180
+
181
+ def self.request_restore(serial, restorecode)
182
+ serial_normalized = normalize_serial(serial)
183
+ region = extract_region(serial_normalized)
184
+ restorecode_bin = decode_restorecode(restorecode)
185
+
186
+ # stage 1
187
+ request = Net::HTTP::Post.new(RESTORE_INIT_REQUEST_PATH)
188
+ request.content_type = 'application/octet-stream'
189
+ request.body = serial_normalized
190
+
191
+ response = Net::HTTP.new(AUTHENTICATOR_HOSTS[region]).start do |http|
192
+ http.request(request)
193
+ end
194
+
195
+ raise RequestFailedError.new("Error requesting for restore (stage 1): #{response.code}") if response.code.to_i(10) != 200
196
+
197
+ # stage 2
198
+ challenge = response.body
199
+
200
+ key = create_one_time_pad(20)
201
+
202
+ digest = Digest::HMAC.digest(serial_normalized + challenge,
203
+ restorecode_bin,
204
+ Digest::SHA1)
205
+
206
+ payload = serial_normalized
207
+ payload += ((digest+key).as_bin_to_i ** RSA_KEY % RSA_MOD).to_bin
208
+
209
+ request = Net::HTTP::Post.new(RESTORE_VALIDATE_REQUEST_PATH)
210
+ request.content_type = 'application/octet-stream'
211
+ request.body = payload
212
+
213
+ response = Net::HTTP.new(AUTHENTICATOR_HOSTS[region]).start do |http|
214
+ http.request(request)
215
+ end
216
+
217
+ raise RequestFailedError.new("Error requesting for restore (stage 2): #{response.code}") if response.code.to_i(10) != 200
218
+
219
+ secret = response.body.bytes.zip(key.bytes).reduce('') do |memo, pair|
220
+ memo << (pair[0] ^ pair[1]).chr
221
+ end.as_bin_to_hex
222
+
223
+ return prettify_serial(serial), secret
224
+ end
225
+
226
+ def self.request_server_time(region)
227
+ request = Net::HTTP::Get.new(TIME_REQUEST_PATH)
228
+ request.content_type = 'application/octet-stream'
229
+
230
+ response = Net::HTTP.new(AUTHENTICATOR_HOSTS[region]).start do |http|
231
+ http.request(request)
232
+ end
233
+
234
+ raise RequestFailedError.new("Error requesting server time: #{response.code}") if response.code.to_i(10) != 200
235
+
236
+ response.body.as_bin_to_i.to_f / 1000.0
237
+ end
238
+
239
+ end
240
+
241
+ end
242
+
243
+ end
@@ -0,0 +1,5 @@
1
+ module Bnet
2
+ class Authenticator
3
+ VERSION = "0.1.0"
4
+ end
5
+ end
@@ -0,0 +1,82 @@
1
+ module Bnet
2
+
3
+ class InvalidCommandException < Exception
4
+ attr_accessor :command
5
+ attr_accessor :message
6
+
7
+ def initialize(message = nil, command = nil)
8
+ @message = message
9
+ @command = command
10
+ end
11
+
12
+ end
13
+
14
+ class Command
15
+ attr_accessor :options
16
+ attr_accessor :parser
17
+ attr_accessor :args
18
+
19
+ def initialize
20
+ @options = OpenStruct.new
21
+
22
+ @parser = OptionParser.new do |opts|
23
+ opts.banner = <<-END.gsub(/^\s+/, '')
24
+ #{description}\n
25
+ Usage: #{File.basename $0} #{name}#{" " + extra_params unless extra_params.nil?}
26
+ END
27
+
28
+ setup_opts(opts)
29
+ end
30
+ end
31
+
32
+ def parse_and_run(args)
33
+ parse args
34
+
35
+ begin
36
+ run
37
+ rescue Bnet::Authenticator::BadInputError, Bnet::Authenticator::RequestFailedError => e
38
+ raise Bnet::InvalidCommandException.new(e.message, name.to_sym)
39
+ end
40
+ end
41
+
42
+ def help
43
+ "* #{(name + ':').ljust(12)}#{parser.help}"
44
+ end
45
+
46
+ def name
47
+ self.class.name.split('::').last.gsub(/Command$/, '').downcase
48
+ end
49
+
50
+ private
51
+
52
+ def parse(args)
53
+ begin
54
+ parser.parse! args
55
+ rescue OptionParser::InvalidOption => e
56
+ e.class.module_eval { attr_accessor :command } unless e.respond_to? :command
57
+ e.command = name.to_sym
58
+ raise e
59
+ end
60
+ @args = args
61
+ end
62
+
63
+ protected
64
+
65
+ def description
66
+ # description of the command
67
+ end
68
+
69
+ def extra_params
70
+ # extra params of the command
71
+ end
72
+
73
+ def setup_opts(opts)
74
+ # fill @options
75
+ end
76
+
77
+ def run
78
+ # can access @options
79
+ end
80
+ end
81
+
82
+ end
@@ -0,0 +1,27 @@
1
+ require 'bnet/command'
2
+
3
+ module Bnet
4
+
5
+ module Commands
6
+
7
+ class HelpCommand < Command
8
+
9
+ def description
10
+ 'Print help message for this program or a command.'
11
+ end
12
+
13
+ def extra_params
14
+ '[command]'
15
+ end
16
+
17
+ def run
18
+ command = args.shift
19
+ command = command.to_sym unless command.nil?
20
+ raise InvalidCommandException.new(nil, command)
21
+ end
22
+
23
+ end
24
+
25
+ end
26
+
27
+ end
@@ -0,0 +1,29 @@
1
+ require 'bnet/command'
2
+
3
+ module Bnet
4
+
5
+ module Commands
6
+
7
+ class InfoCommand < Command
8
+
9
+ def description
10
+ "Print serial, secret and restoration code of an authenticator."
11
+ end
12
+
13
+ def extra_params
14
+ "<serial> <secret>"
15
+ end
16
+
17
+ def run
18
+ serial = @args.shift
19
+ secret = @args.shift
20
+
21
+ authenticator = Authenticator.new(:serial => serial, :secret => secret)
22
+ puts authenticator.to_s
23
+ end
24
+
25
+ end
26
+
27
+ end
28
+
29
+ end
@@ -0,0 +1,29 @@
1
+ require 'bnet/command'
2
+
3
+ module Bnet
4
+
5
+ module Commands
6
+
7
+ class NewCommand < Command
8
+
9
+ def description
10
+ "Request a new authenticator from server."
11
+ end
12
+
13
+ def extra_params
14
+ "[region (valid regions are: US|EU|CN)]"
15
+ end
16
+
17
+ def run
18
+ region = args.shift || 'US'
19
+ region = region.to_sym
20
+
21
+ authenticator = Authenticator.new(:region => region)
22
+ puts authenticator.to_s
23
+ end
24
+
25
+ end
26
+
27
+ end
28
+
29
+ end
@@ -0,0 +1,32 @@
1
+ require 'bnet/command'
2
+
3
+ module Bnet
4
+
5
+ module Commands
6
+
7
+ class RestoreCommand < Command
8
+
9
+ def description
10
+ "Restore an authenticator from server and save it."
11
+ end
12
+
13
+ def extra_params
14
+ "<serial> <restorecode>"
15
+ end
16
+
17
+ def run
18
+ serial = @args.shift
19
+ restorecode = @args.shift
20
+
21
+ authenticator = Authenticator.new(
22
+ :serial => serial,
23
+ :restorecode => restorecode
24
+ )
25
+ puts authenticator.to_s
26
+ end
27
+
28
+ end
29
+
30
+ end
31
+
32
+ end
@@ -0,0 +1,70 @@
1
+ require 'bnet/command'
2
+
3
+ module Bnet
4
+
5
+ module Commands
6
+
7
+ class TokenCommand < Command
8
+
9
+ def description
10
+ "Print current token for giving secret."
11
+ end
12
+
13
+ def extra_params
14
+ "[-r] [--repeat] <secret>"
15
+ end
16
+
17
+ def setup_opts(opts)
18
+ @options.repeat = false
19
+ opts.on("-r", "--repeat", "Keep printing updated token") do
20
+ @options.repeat = true
21
+ end
22
+ end
23
+
24
+ def run
25
+ secret = @args.shift
26
+
27
+ token, next_timestamp = Authenticator.caculate_token(secret)
28
+
29
+ puts token
30
+ if @options.repeat
31
+ interrupted = false
32
+ trap("INT") { interrupted = true } # traps Ctrl-C
33
+
34
+ until interrupted do
35
+ sleep 1
36
+
37
+ if Time.now.getutc.to_i < next_timestamp
38
+ print_countdown(next_timestamp - Time.now.getutc.to_i)
39
+ next
40
+ end
41
+
42
+ token, next_timestamp = Authenticator.caculate_token(secret)
43
+ puts token
44
+ end
45
+ end
46
+ end
47
+
48
+ private
49
+
50
+ def print_countdown(seconds, output = $stdout)
51
+ return unless output.tty?
52
+
53
+ case
54
+ when seconds > 25 then h, c = 1, 32
55
+ when seconds > 20 then h, c = 0, 32
56
+ when seconds > 15 then h, c = 1, 33
57
+ when seconds > 10 then h, c = 0, 33
58
+ when seconds > 5 then h, c = 0, 31
59
+ else
60
+ h, c = 1, 31
61
+ end
62
+
63
+ output.puts "\e[%d;%dm%02d\e[1A\e[0m" % [h, c, seconds]
64
+ end
65
+
66
+ end
67
+
68
+ end
69
+
70
+ end
@@ -0,0 +1,63 @@
1
+ module Bnet
2
+
3
+ module Support
4
+
5
+ module Array
6
+
7
+ def as_bytes_to_bin
8
+ pack('C*')
9
+ end
10
+
11
+ def as_bytes_to_hex
12
+ '%02x' * length % self
13
+ end
14
+
15
+ def as_bytes_to_i
16
+ as_bytes_to_hex.to_i(16)
17
+ end
18
+
19
+ end
20
+
21
+ module Integer
22
+
23
+ def to_bytes
24
+ to_s(16).scan(/.{2}/).map {|s| s.to_i(16)}
25
+ end
26
+
27
+ def to_bin
28
+ to_bytes.as_bytes_to_bin
29
+ end
30
+
31
+ end
32
+
33
+ module String
34
+
35
+ def as_bin_to_i
36
+ bytes.to_a.as_bytes_to_i
37
+ end
38
+
39
+ def as_bin_to_hex
40
+ bytes.to_a.as_bytes_to_hex
41
+ end
42
+
43
+ def as_hex_to_bin
44
+ to_i(16).to_bytes.as_bytes_to_bin
45
+ end
46
+
47
+ end
48
+
49
+ end
50
+
51
+ end
52
+
53
+ class Array
54
+ include Bnet::Support::Array
55
+ end
56
+
57
+ class Integer
58
+ include Bnet::Support::Integer
59
+ end
60
+
61
+ class String
62
+ include Bnet::Support::String
63
+ end
@@ -0,0 +1,63 @@
1
+ require 'test/unit'
2
+ require 'bnet/authenticator'
3
+
4
+ class Bnet::AuthenticatorTest < Test::Unit::TestCase
5
+ DEFAULT_SERIAL = 'CN-1402-1943-1283'
6
+ DEFAULT_SECRET = '4202aa2182640745d8a807e0fe7e34b30c1edb23'
7
+ DEFAULT_RSCODE = '4CKBN08QEB'
8
+ DEFAULT_REGION = :CN
9
+
10
+ def test_load
11
+ authenticator = Bnet::Authenticator.new(:serial => DEFAULT_SERIAL, :secret => DEFAULT_SECRET)
12
+ is_default_authenticator authenticator
13
+ end
14
+
15
+ def test_argument_error
16
+ assert_raise ::Bnet::BadInputError do
17
+ Bnet::Authenticator.new
18
+ end
19
+
20
+ assert_raise ::Bnet::BadInputError do
21
+ Bnet::Authenticator.new(:serial => 'ABC')
22
+ end
23
+
24
+ assert_raise ::Bnet::BadInputError do
25
+ Bnet::Authenticator.new(:region => 'SG')
26
+ end
27
+
28
+ assert_raise ::Bnet::BadInputError do
29
+ Bnet::Authenticator.new(:restorecode => 'DDDD')
30
+ end
31
+ end
32
+
33
+ def test_request_new_serial
34
+ authenticator = Bnet::Authenticator.new(:region => :US)
35
+ assert_equal :US, authenticator.region
36
+ assert_not_nil authenticator.serial
37
+ assert_not_nil authenticator.secret
38
+ assert_not_nil authenticator.restorecode
39
+ end
40
+
41
+ def test_restore
42
+ authenticator = Bnet::Authenticator.new(:serial => DEFAULT_SERIAL, :restorecode => DEFAULT_RSCODE)
43
+ is_default_authenticator authenticator
44
+ end
45
+
46
+ def test_request_server_time
47
+ assert_nothing_raised do
48
+ Bnet::Authenticator.request_server_time :EU
49
+ end
50
+ end
51
+
52
+ private
53
+
54
+ def is_default_authenticator(authenticator)
55
+ assert_equal DEFAULT_REGION, authenticator.region
56
+ assert_equal DEFAULT_SERIAL, authenticator.serial
57
+ assert_equal DEFAULT_SECRET, authenticator.secret
58
+ assert_equal DEFAULT_RSCODE, authenticator.restorecode
59
+ assert_equal ['61459300', 1347279360], authenticator.caculate_token(1347279358)
60
+ assert_equal ['61459300', 1347279360], authenticator.caculate_token(1347279359)
61
+ assert_equal ['23423634', 1347279390], authenticator.caculate_token(1347279360)
62
+ end
63
+ end
metadata ADDED
@@ -0,0 +1,92 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: bnet-authenticator
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - ZHANG Yi
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2014-02-26 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rake
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: yard
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ description: Ruby implementation of the Battle.net Mobile Authenticator
42
+ email:
43
+ - zhangyi.cn@gmail.com
44
+ executables:
45
+ - bna
46
+ extensions: []
47
+ extra_rdoc_files: []
48
+ files:
49
+ - ".yardopts"
50
+ - COPYING
51
+ - Gemfile
52
+ - README.md
53
+ - Rakefile
54
+ - bin/bna
55
+ - bnet-authenticator.gemspec
56
+ - lib/bnet/authenticator.rb
57
+ - lib/bnet/authenticator/core.rb
58
+ - lib/bnet/authenticator/version.rb
59
+ - lib/bnet/command.rb
60
+ - lib/bnet/commands/help.rb
61
+ - lib/bnet/commands/info.rb
62
+ - lib/bnet/commands/new.rb
63
+ - lib/bnet/commands/restore.rb
64
+ - lib/bnet/commands/token.rb
65
+ - lib/bnet/support.rb
66
+ - test/test_battlenet_authenticator.rb
67
+ homepage: https://github.com/dorentus/bnet-authenticator
68
+ licenses:
69
+ - MIT
70
+ metadata: {}
71
+ post_install_message:
72
+ rdoc_options: []
73
+ require_paths:
74
+ - lib
75
+ required_ruby_version: !ruby/object:Gem::Requirement
76
+ requirements:
77
+ - - ">="
78
+ - !ruby/object:Gem::Version
79
+ version: 1.9.3
80
+ required_rubygems_version: !ruby/object:Gem::Requirement
81
+ requirements:
82
+ - - ">="
83
+ - !ruby/object:Gem::Version
84
+ version: '0'
85
+ requirements: []
86
+ rubyforge_project:
87
+ rubygems_version: 2.2.2
88
+ signing_key:
89
+ specification_version: 4
90
+ summary: Battle.net Mobile Authenticator
91
+ test_files:
92
+ - test/test_battlenet_authenticator.rb