# class DBus::DBusCookieSHA1

# Authentication class using SHA1 crypto algorithm¶ ↑

`Class` for 'CookieSHA1' type authentication. Implements the AUTH DBUS_COOKIE_SHA1 mechanism.

### Public Instance Methods

authenticate() click to toggle source

the autenticate method (called in stage one of authentification)

       # File lib/dbus/auth.rb
    52 def authenticate
    53   require "etc"
    54   # number of retries we have for auth
    55   @retries = 1
    56   hex_encode(Etc.getlogin).to_s # server expects it to be binary
    57 end

data(hexdata) click to toggle source

handles the interesting crypto stuff, check the rbus-project for more info: rbus.rubyforge.org/

       # File lib/dbus/auth.rb
    65 def data(hexdata)
    66   require "digest/sha1"
    67   data = hex_decode(hexdata)
    68   # name of cookie file, id of cookie in file, servers random challenge
    69   context, id, s_challenge = data.split(" ")
    70   # Random client challenge
    71   c_challenge = 1.upto(s_challenge.bytesize / 2).map { rand(255).to_s }.join
    72   # Search cookie file for id
    73   path = File.join(ENV["HOME"], ".dbus-keyrings", context)
    74   DBus.logger.debug "path: #{path.inspect}"
    75   File.foreach(path) do |line|
    76     if line.index(id).zero?
    77       # Right line of file, read cookie
    78       cookie = line.split(" ")[2].chomp
    79       DBus.logger.debug "cookie: #{cookie.inspect}"
    80       # Concatenate and encrypt
    81       to_encrypt = [s_challenge, c_challenge, cookie].join(":")
    82       sha = Digest::SHA1.hexdigest(to_encrypt)
    83       # the almighty tcp server wants everything hex encoded
    84       hex_response = hex_encode("#{c_challenge} #{sha}")
    85       # Return response
    86       response = [:AuthOk, hex_response]
    87       return response
    88     end
    89   end
    90   # a little rescue magic
    91   unless @retries <= 0
    92     puts "ERROR: Could not auth, will now exit."
    93     puts "ERROR: Unable to locate cookie, retry in 1 second."
    94     @retries -= 1
    95     sleep 1
    96     data(hexdata)
    97   end
    98 end

hex_decode(encoded) click to toggle source

decode hex to plain

        # File lib/dbus/auth.rb
    107 def hex_decode(encoded)
    108   encoded.scan(/[[:xdigit:]]{2}/).map { |h| h.hex.chr }.join
    109 end

hex_encode(plain) click to toggle source

encode plain to hex

        # File lib/dbus/auth.rb
    101 def hex_encode(plain)
    102   return nil if plain.nil?
    103   plain.to_s.unpack("H*")[0]
    104 end

name() click to toggle source

returns the modules name

       # File lib/dbus/auth.rb
    60 def name
    61   "DBUS_COOKIE_SHA1"
    62 end