Report abuse

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
require 'open3'
#
# Access username and password from mac os x keychain
#
# Author: Thomas Flemming (thomasfl at usit dot uio dot no) 2009
#
# synposis
#
#    read_password www.webdav.org
#    userame: tiger
#    password: scott
#
#  To add username and password to you keychain
#
#   1. Go to a webpage protected with http(s) authentication
#   2. Type in username and password, and check the
#      box for adding username and password to keychain
#   3. Run this script.
#   4. A Keychain dialog windows should appear. Click
#      on the button to allow access to the program "security".
#
# User Keychain Access to remove privilegies, username or passwords
# from keychain.
#
def decode_hex_string(hex_str)
  str = ""
  i = true
  hex_str.split("").each do | char |
    if(i)
      str += char
      i = false
    else
      str += char + " "
      i = true
    end
  end
  decoded_str = ""
  str.split(' ').each do |val|
    decoded_str += val.hex.chr
  end
  return decoded_str
end

def fetch_keychain_password(server)
  command = "security find-internet-password -g -s " + server
  username = nil
  password = nil

  Open3.popen3(command) do |stdin, stdout, stderr|
    stderr = stderr.readlines.join("")
    stderr=~ /^password: "(.*)"$/
    password = $1

    if(!password)
      stderr=~ /^password: (0x.*)$/
      password = $1
      if(password)
        password = decode_hex_string( password.sub(/^0x/,"") )
      end
    end
    stdout = stdout.readlines.join("")
    stdout =~ /"acct"[^=]*="(.*)"/
    username = $1

  end
  return [username, password]
end

host = ARGV[0]
if(!host)
  puts "read_password: error: missing hostname"
  puts "read_password: usage read_password hostname"
  exit
end
result = fetch_keychain_password(host)
if(result[0])
  puts "Username:" + result[0]
  puts "Password:" + result[1]
else
  puts "Username and password not set for " + host
  puts "[Instructions for adding username and password for "
  puts "to server with Safari and Keychain...]"
end