Class: WiKID::Auth

Inherits:
Object
  • Object
show all
Defined in:
lib/WiKID.rb,
lib/WiKID_version.rb

Constant Summary collapse

VERSION =
"3.2.3"

Instance Method Summary collapse

Constructor Details

#initialize(host_or_file, port, keyfile, keypass, cafile = @@DEFAULT_CA_FILE) ⇒ Auth

This constructor allows the Auth_WiKID module to be initialized from either a properties file or via explicit arguments.

The contents of the properties file should contain the following key-value pairs:

  • host - The IP address or hostname of the wAuth server

  • port - The SSL listener port for the wAuth daemon on the wAuth server

  • keyfile - The PKCS12 keystore generated for client by the wAuth server

  • pass - The passphrase securing the keys in keyfile

  • cafile - The PEM-encoded certificate file for validating the wAuth server certificate

Parameters:

  • host_or_file (string)

    Either the IP address or hostname of the wAuth server, or the path to a properties file

  • port (int)

    The SSL listener port for the wAuth daemon on the wAuth server

  • keyfile (string)

    The PKCS12 keystore generated for this client by the wAuth server

  • keypass (string)

    The passphrase securing the keys in keyfile

  • cafile (string) (defaults to: @@DEFAULT_CA_FILE)

    The certificate authority store for validating the wAuth server certificate



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
# File 'lib/WiKID.rb', line 110

def initialize(host_or_file, port, keyfile, keypass, cafile = @@DEFAULT_CA_FILE)

  unless SSLEnabled
    raise RuntimeError.new('Ruby/OpenSSL module is required for WiKID authentication.')
  end

  if (File.exist?(host_or_file))
    # props = parse_ini_file(host_or_file)
    props = Hash.new

    @host = props['host']
    @port = props['port']
    @keyfile = props['keyfile']
    @keypass = props['pass']
    @cafile = props['cafile']
  else
    @host = host_or_file.untaint
    @port = port.untaint
    @keyfile = keyfile.untaint
    @keypass = keypass.untaint
    unless cafile.nil? || cafile.empty?
      @cafile = cafile.untaint
    end
  end
  if (!@port.is_a?(Integer))
    @port = 0
  end

  _dprint("WiKID.rb initialized: host=#{@host}, port=#{@port}, keyfile=#{@keyfile}, cafile=#{@cafile}")

  ## simple hack to allow for testing during gem installation (prevents security errors since keys may not yet be available)
  unless port == -1
    checkKeys()
  end

  return true
end

Instance Method Details

#chapVerify(username, domaincode, wikidChallenge = '', chapPassword = '', chapChallenge = '') ⇒ boolean

Note:

Not currently supported by the Open Source release of WiKID.

Verifies the credentials via challenge-response.

Returns:

  • (boolean)

    ‘true’ indicates credentials were valid, ‘false’ if credentials were invalid or an error occurred



522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
# File 'lib/WiKID.rb', line 522

def chapVerify(username, domaincode, wikidChallenge = '', chapPassword = '', chapChallenge = '')

  _dprint('chapVerify() called ...')
  reconnect()
  validCredentials = false
  valid_tag = 'VERIFY:VALID'
  _dprint('Checking Chap Credentials')

  mesg = "CHAPOFFVERIFY:" + username + "\t" + "nil" + "\t" + domaincode + "\t" + wikidChallenge

  reconnect {

    $sslsocket.puts(chapPassword.length)
    $sslsocket.puts(chapPassword)
    $sslsocket.puts(chapChallenge.length)
    $sslsocket.puts(chapChallenge.length)
    $sslsocket.flush

    _dprint("Reading in...")

    inputLine = $sslsocket.gets.chomp
    if (inputLine[0, valid_tag.length] == valid_tag)
      validCredentials = true
    end
  }

  return validCredentials
end

#checkCredentials(username, passcode, domaincode = '127000000001') ⇒ boolean

Verifies the credentials that are generated using the standard authentication method.

Parameters:

  • username (string)

    Users login ID in this authentication domain

  • passcode (string)

    Passcode provided by the user

  • domaincode (string) (defaults to: '127000000001')

    12 digit code representing the authentication domain

Returns:

  • (boolean)

    ‘true’ indicates credentials were valid, ‘false’ if credentials were invalid or an error occurred



464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
# File 'lib/WiKID.rb', line 464

def checkCredentials(username, passcode, domaincode = '127000000001')

  _dprint("checkCredentials(#{username}, #{passcode}, #{domaincode}) called ...")

  validCredentials = false
  offline_challenge = ''
  offline_response = ''
  chap_password = ''
  chap_challenge = ''
  valid_tag = 'VERIFY:VALID'

  _dprint('Checking Credentials...')

  mesg = "VERIFY:" + username + "\t" + passcode + "\t" + domaincode
  mesg = <<XML
<transaction>
    <type format="base">2</type>
    <data>
        <user-id>#{username}</user-id>
        <passcode>#{passcode}</passcode>
        <domaincode>#{domaincode}</domaincode>
        <offline-challenge encoding="none">#{offline_challenge}</offline-challenge>
        <offline-response encoding="none">#{offline_response}</offline-response>
        <chap-password encoding="none">#{chap_password}</chap-password>
        <chap-challenge encoding="none">#{chap_challenge}</chap-challenge>
        <result>null</result>
    </data>
</transaction>
XML

  reconnect {

    xml = _request(mesg)
    response = XPath.first(xml, '//data/result')

    if response =~ /VALID/
      validCredentials = true
    else
      validCredentials = false
    end
    _dprint('Read response: verdict = ' + validCredentials.to_s)
  }

  _dprint('Returning Results...')
  return validCredentials
end

#checkKeysObject

This method checks that the certificates are readable and accessible.



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/WiKID.rb', line 179

def checkKeys()

  data = nil
  if (@cafile.nil? || @cafile.empty? || !File.exists?(@cafile) || OpenSSL::X509::Certificate.new(File.read(@cafile)).nil?)
    warn 'CA certificate NOT OK, running without peer verification'
  else
    _dprint('CA certificate OK')
  end

  if (@keyfile.nil? || @keyfile.empty? || !File.exists?(@keyfile) || OpenSSL::X509::Certificate.new(File.read(@keyfile)).nil?)
    raise SecurityError, 'Public key NOT OK!'
  else
    _dprint('Public key OK')
  end

  if (!File.exists?(@keyfile) || OpenSSL::PKey::RSA.new(File.read(@keyfile), @keypass).nil?)
    raise SecurityError, 'Private key NOT OK!'
  else
    _dprint('Private key OK')
  end

end

#closeObject

This method simply closes the connection to the wAuth service.



160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/WiKID.rb', line 160

def close()
  _dprint('Closing Auth_WiKID connection ...')
  unless $sslsocket.nil?
    unless $sslsocket.closed?
      $sslsocket.puts('QUIT');
      $sslsocket.flush
      $sslsocket.close
    end
    $sslsocket = nil
    @socket.shutdown
  end
  @isConnected = false
end

#deleteUser(user_id, domaincode = ' 127000000001 ') ⇒ boolean

Delete a user by userid

Parameters:

  • user_id (string)

    The userid on the server, or a user object as returned by a call to findUser()

  • domaincode (string) (defaults to: ' 127000000001 ')

    12 digit code representing the authentication domain if first argument is a userid (string), not necessary if first argument is the user object, which will already have this

Returns:

  • (boolean)

    ‘ true ’ indicates deletion was successful



720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
# File 'lib/WiKID.rb', line 720

def deleteUser(user_id, domaincode = ' 127000000001 ')

  successful = false

  _dprint("deleteUser(#{user_id},#{domaincode})")

  if (user_id.is_a?(String))
    user_xml = findUser(user_id, domaincode)
  end

  if user_xml.nil?
    return false
  end

  _dprint("user: #{user_id}")

  mesg = <<XML
    <transaction>
      <type>7</type>
      <data>
        <domaincode>#{domaincode}</domaincode>
        <user-id>#{user_id}</user-id>
        #{user_xml}
      <result>null</result>
      <return-code>-2147483648</return-code>
    </data>
    </transaction>
XML


  reconnect {
    _dprint('deleting user ...')

    xml = _request(mesg)

    unless xml.nil?
      response = XPath.first(xml, '//data/result')
      _dprint("response: '#{response}'")

      if response.to_s =~ /SUCC?ESS/
        successful = true
      else
        successful = false
      end
    end

    return successful
  }

end

#findUser(username, domaincode = '127000000001') ⇒ String

Find a user by username

Parameters:

  • username (string)

    the textual id of the user to search for

  • domaincode (string) (defaults to: '127000000001')

    the 12 digit code representating the authentication domain

Returns:

  • (String)

    The XML representing the user object, if successful; nil if unsuccesful



615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
# File 'lib/WiKID.rb', line 615

def findUser(username, domaincode = '127000000001')

  _dprint("findUser() ...");

  user = nil

  mesg = <<XML
  <transaction>
    <type>5</type>
    <data>
      <domaincode>#{domaincode}</domaincode>
      <user-id>#{username}</user-id>
      <result>null</result>
      <return-code>-2147483648</return-code>
    </data>
  </transaction>
XML

  reconnect {
    _dprint("Looking up user ...");
    xml = _request(mesg)

    user_xml = XPath.first(xml, '//data/user')

    return user_xml
  }

end

#getDomainsstring

Note:

Not currently supported by the Open Source release of WiKID.

Fetches a list of domains served by the currently connected server code.

Returns:

  • (string)

    ‘ true ’ indicates credentials were valid, ‘ false ’ if credentials were invalid or an error occurred



784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
# File 'lib/WiKID.rb', line 784

def getDomains()

  _dprint("getDomains() called ...")

  valid_tag = "DOMAINLIST"
  _dprint("Getting Domains")

  mesg = <<XML
<transaction>
    <type>3</type>
    <data>
        <domain-list>null</domain-list>
    </data>
</transaction>
XML
  reconnect {
    xml = _request(mesg)
    domains = XPath.match(xml, '//data/domain-list')
  }
  _dprint("Returning Results...")
  return domains
end

#isConnectedboolean

Is the socket connected?

Returns:

  • (boolean)

    Status of handle: true indicates connection is active



369
370
371
# File 'lib/WiKID.rb', line 369

def isConnected()
  return @isConnected
end

#pingstring

Note:

This method should not be necessary in typical implementations, but is available nonetheless.

Send a big ping transaction to the server to verify the connection is good.

Returns:

  • (string)

    the raw response from the server



249
250
251
252
253
# File 'lib/WiKID.rb', line 249

def ping()
  mesg = '<transaction> <type>1</type> <data> <value>TX</value> </data> </transaction>'
  xml = _request(mesg)
  return xml
end

#preRegister(tokenCode, preRegCode, domaincode = '127000000001') ⇒ boolean

This method supports user pre-registration. You may upload a list of userids and pre-registration codes into the server via the WiKIDAdmin interface. Users can then use the pre-registration code provided to them securely by the administrator in conjunction with the registration code provided by the WiKID token to register in an expedited manner.

Parameters:

  • tokenCode (string)

    the registration code provided by the token

  • preRegCode (string)

    the code associated with the username that was uploaded to the server

  • domaincode (string) (defaults to: '127000000001')

    12 digit code representing the authentication server/domain

Returns:

  • (boolean)

    ‘true’ indicates that the pre-registration was successful; ‘false’ if not



567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
# File 'lib/WiKID.rb', line 567

def preRegister(tokenCode, preRegCode, domaincode = '127000000001')

  _dprint('preRegister() called ...')
  successful = false;

  mesg = <<XML
<transaction>
  <type>10</type>
  <data>
    <token-registration-code>#{tokenCode}</token-registration-code>
    <pre-registration-code>#{preRegCode}</pre-registration-code>
    <domaincode>#{domaincode}</domaincode>
    <error-code>null</error-code>
    <result>null</result>
  </data>
</transaction>
XML

  reconnect {
    _dprint('Pre-registering ...')
    xml = _request(mesg)

    response = XPath.first(xml, '//data/result')
    _dprint("response: '#{response}'")

    if response.to_s =~ /SUC?CESS/
      successful = true
    else
      successful = false
    end
  }

  _dprint("Read response: verdict = #{successful}")
  return successful

end

#reconnectboolean

This method reconnects to the wAuth server, if the socket handle is dead.

Returns:

  • (boolean)

    Whether the socket is connected



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
# File 'lib/WiKID.rb', line 285

def reconnect()

  _dprint("reconnect() called.")

  begin

    if ($sslsocket.nil? || $sslsocket.closed?)
      _dprint("Socket inactive.  Reconnecting...")

      #puts "Setting up SSL context ..."
      ctx = OpenSSL::SSL::SSLContext.new()

      # Options:
      #    "cert", "key", "client_ca", "ca_file", "ca_path",
      #    "timeout", "verify_mode", "verify_depth",
      #    "verify_callback", "options", "cert_store", "extra_chain_cert"

      ctx.cert = OpenSSL::X509::Certificate.new(File.read(@keyfile))
      ctx.key = OpenSSL::PKey::RSA.new(File.read(@keyfile), @keypass)

      if @cafile.nil? || @cafile.empty?
        ctx.ca_file = nil # @cafile
        ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE
      else

        ctx.ca_file = @cafile

        # this next bit might be redundant?
        ctx.cert_store = OpenSSL::X509::Store.new
        ctx.cert_store.set_default_paths
        ctx.cert_store.add_file(@cafile)

        ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER | OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT
      end
      # ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE

      ctx.timeout = @@timeout

      if ctx.cert.nil?
        _dprint("warning: peer certificate won't be verified this session.")
        ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE
      end

      _dprint("Opening socket to #{@host}:#{@port}...")
      @socket = TCPSocket.open(@host, @port)
      _dprint("socket open")
      #@socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, @@timeout)

      #@socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_SNDTIMEO, @@timeout)

      $sslsocket = OpenSSL::SSL::SSLSocket.new(@socket, ctx)
      _dprint("socket created")
      #$sslsocket.sync_close = true

      # $sslsocket should be good now
      _dprint("Connecting SSL socket ...")
      $sslsocket.connect

      _startConnection()

    end

    if block_given?
      #puts "Connecting SSL socket in block ..."
      $sslsocket.connect if $sslsocket.closed?
      yield
      #puts "SSL connection block finished."
    else
      #puts "SSL connection wanting to do something else ..."
      # do something non-OO
    end
  rescue Exception => ex
    warn "Error reading from server: #{ex}"
  end

end

#registerUsername(username, regcode, domaincode, groupname = '', passcode = '') ⇒ int

Creates an association between the userid and the device registered by the user.

Parameters:

  • username (string)

    Users login ID in this authentication domain

  • regcode (string)

    Registration code provided to user when setting up this domain on users device

  • domaincode (string)

    12 digit code representing this authentication domain

  • passcode (string) (defaults to: '')

    Optional passcode provided by the user, to link this device to an existing registration

Returns:

  • (int)

    Result code from the registration attempt



390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
# File 'lib/WiKID.rb', line 390

def registerUsername(username, regcode, domaincode, groupname = '', passcode = '')

  _dprint('registerUsername() called ...')
  valid_tag = 'REGUSER:SUCESS'

  if (!passcode.nil? && passcode.length > 0)
    _dprint('Adding new device ...')
    command = 'ADDREGUSER'
    type = 4;
    passcodeline = "<passcode>#{passcode}</passcode>";
    format = 'add';
  else
    _dprint('Registering user ...')
    command = 'REGUSER'
    type = 4;
    passcodeline = '<passcode>null</passcode>';
    format = 'new';
  end

  if (!groupname.nil? && groupname.length>0)
    groupnameline="<groupName>#{groupname}</groupName>"
  else
    groupnameline='<groupName>null</groupName>'
  end

  #mesg = "#{command}:#{username}\t#{regcode}\t#{domaincode}\t#{passcode}"
  mesg = <<XML
<transaction>
    <type format="#{format}">#{type}</type>
    <data>
    <user-id>#{username}</user-id>
    <registration-code>#{regcode}</registration-code>
    <domaincode>#{domaincode}</domaincode>
    #{passcodeline}
  #{groupnameline}
    <error-code>null</error-code>
    <result>null</result>
    </data>
</transaction>
XML

  #puts mesg
  reconnect {

    _dprint("registerUsername() sending '#{mesg}' ...")

    xml = _request(mesg)
    response = XPath.first(xml, '//data/result')
    _dprint("response: '#{response}'")
    if response.to_s =~ /SUCC?ESS/
      _dprint('Registered!')
      return 0
    else
      err = XPath.first(xml, '//data/error-code/text()')
      _dprint("Failed to register!  Error: #{err}")
      return err
    end
  }

end

#setDebug(newStatus) ⇒ Object

Modify the debug state of the current connection

Parameters:

  • newStatus (boolean)


813
814
815
# File 'lib/WiKID.rb', line 813

def setDebug(newStatus)
  @@DEBUG = (newStatus == true) ? true : false
end

#updateUser(user_id, domaincode = '127000000001', updateUserXml = '') ⇒ boolean

Update the previously “found” user

This method is used to update a user object on the server. The network client certificate that was used to establish the wClient connection must be authorized to perform this action.

Parameters:

  • user_id (string)

    The userid on the server, or a user object as returned by a call to findUser()

  • domaincode (string) (defaults to: '127000000001')

    12 digit code representing the authentication domain if first argument is a userid (string), not necessary if first argument is the user object, which will already have this

Returns:

  • (boolean)

    ‘true’ indicates the update was successful



659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
# File 'lib/WiKID.rb', line 659

def updateUser(user_id, domaincode = '127000000001', updateUserXml = '')

  successful = false

  _dprint("updateUser(#{user_id},#{domaincode})")

  if (user_id.is_a?(String))
    user_xml = findUser(user_id, domaincode)
  end

  if user_xml.nil?
    return false
  end

  _dprint("user_xml: #{user_xml}, updating to #{updateUserXml}")

  mesg = <<XML
    <transaction>
      <type>6</type>
      <data>
        <domaincode>#{domaincode}</domaincode>
        <user-id>#{user_id}</user-id>
        #{updateUserXml}
      <result>null</result>
      <return-code>-2147483648</return-code>
    </data>
    </transaction>
XML

  reconnect {
    _dprint('updating user ...')

    xml = _request(mesg)

    response = XPath.first(xml, '//data/result')
    _dprint("response: '#{response}'")

    if response.to_s =~ /SUCC?ESS/
      successful = true
    else
      successful = false
    end

  }

  return successful
end