Hardware authentication for Linux using ordinary USB Flash Drives.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

260 lines
7.3 KiB

18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
  1. #!/usr/bin/env python
  2. #
  3. # Copyright (c) 2003-2007 Andrea Luzzardi <scox@sig11.org>
  4. #
  5. # This file is part of the pam_usb project. pam_usb is free software;
  6. # you can redistribute it and/or modify it under the terms of the GNU General
  7. # Public License version 2, as published by the Free Software Foundation.
  8. #
  9. # pam_usb is distributed in the hope that it will be useful, but WITHOUT ANY
  10. # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  11. # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  12. # details.
  13. #
  14. # You should have received a copy of the GNU General Public License along with
  15. # this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  16. # Place, Suite 330, Boston, MA 02111-1307 USA
  17. import dbus
  18. import sys
  19. import os
  20. from xml.dom import minidom
  21. class Device:
  22. def __init__(self, udi):
  23. self.__udi = udi
  24. self.__findStorageDevice()
  25. deviceObj = bus.get_object('org.freedesktop.Hal',
  26. udi)
  27. deviceProperties = deviceObj.GetAllProperties(
  28. dbus_interface = 'org.freedesktop.Hal.Device')
  29. self.vendor = deviceProperties['usb_device.vendor']
  30. self.product = deviceProperties['info.product']
  31. self.serialNumber = deviceProperties['usb_device.serial']
  32. def __findStorageDevice(self):
  33. for child in halManager.FindDeviceByCapability('storage'):
  34. obj = bus.get_object('org.freedesktop.Hal',
  35. child)
  36. properties = obj.GetAllProperties(
  37. dbus_interface = 'org.freedesktop.Hal.Device')
  38. if properties['storage.physical_device'] == self.__udi + '_if0':
  39. self.__storageUdi = child
  40. return
  41. raise Exception, '%s is not a storage device.' % self.__udi
  42. def __repr__(self):
  43. return "%s %s (%s)" % (self.vendor, self.product, self.serialNumber)
  44. def volumes(self):
  45. vols = []
  46. for volume in halManager.FindDeviceByCapability('volume'):
  47. deviceObj = bus.get_object('org.freedesktop.Hal',
  48. volume)
  49. deviceProperties = deviceObj.GetAllProperties(
  50. dbus_interface = 'org.freedesktop.Hal.Device')
  51. if deviceProperties['block.storage_device'] != self.__storageUdi:
  52. continue
  53. vols.append({'uuid' : deviceProperties['volume.uuid'],
  54. 'device' : deviceProperties['block.device']})
  55. return vols
  56. def listOptions(question, options, autodetect = True):
  57. if autodetect == True and len(options) == 1:
  58. print question
  59. print "* Using \"%s\" (only option)" % options[0]
  60. print
  61. return 0
  62. while True:
  63. try:
  64. print question
  65. for i in range(len(options)):
  66. print "%d) %s" % (i, options[i])
  67. print
  68. sys.stdout.write('[%s-%s]: ' % (0, len(options) - 1))
  69. optionId = int(sys.stdin.readline())
  70. print
  71. if optionId not in range(len(options)):
  72. raise Exception
  73. return optionId
  74. except KeyboardInterrupt: sys.exit()
  75. except Exception: pass
  76. else: break
  77. def writeConf(options, doc):
  78. try:
  79. f = open(options['configFile'], 'w')
  80. doc.writexml(f)
  81. f.close()
  82. except Exception, err:
  83. print 'Unable to save %s: %s' % (options['configFile'], err)
  84. sys.exit(1)
  85. else:
  86. print 'Done.'
  87. def shouldSave(options, items):
  88. print "\n".join(["%s\t\t: %s" % item for item in items])
  89. print
  90. print 'Save to %s ?' % options['configFile']
  91. sys.stdout.write('[y/n] ')
  92. if sys.stdin.readline().strip() != 'y':
  93. sys.exit(1)
  94. def prettifyElement(element):
  95. tmp = minidom.parseString(element.toprettyxml())
  96. return tmp.lastChild
  97. def addUser(options):
  98. try:
  99. doc = minidom.parse(options['configFile'])
  100. except Exception, err:
  101. print 'Unable to read %s: %s' % (options['configFile'], err)
  102. sys.exit(1)
  103. devSection = doc.getElementsByTagName('devices')
  104. if len(devSection) == 0:
  105. print 'Malformed configuration file: No <devices> section found.'
  106. sys.exit(1)
  107. devicesObj = devSection[0].getElementsByTagName('device')
  108. if len(devicesObj) == 0:
  109. print 'No devices found.'
  110. print 'You must add a device (--add-device) before adding users'
  111. sys.exit(1)
  112. devices = []
  113. for device in devicesObj:
  114. devices.append(device.getAttribute('id'))
  115. device = devices[listOptions("Which device would you like to use for authentication ?",
  116. devices)]
  117. shouldSave(options, [
  118. ('User', options['userName']),
  119. ('Device', device)
  120. ])
  121. users = doc.getElementsByTagName('users')
  122. user = doc.createElement('user')
  123. user.attributes['id'] = options['userName']
  124. e = doc.createElement('device')
  125. t = doc.createTextNode(device)
  126. e.appendChild(t)
  127. user.appendChild(e)
  128. users[0].appendChild(prettifyElement(user))
  129. writeConf(options, doc)
  130. def addDevice(options):
  131. devices = []
  132. for udi in halManager.FindDeviceStringMatch('info.bus', 'usb_device'):
  133. try:
  134. devices.append(Device(udi))
  135. except Exception, ex:
  136. pass
  137. if len(devices) == 0:
  138. print 'No devices detected.'
  139. sys.exit()
  140. device = devices[listOptions("Please select the device you wish to add.", devices)]
  141. volumes = device.volumes()
  142. volume = volumes[listOptions("Which volume would you like to use for " \
  143. "storing data ?",
  144. ["%s (UUID: %s)" % (volume['device'],
  145. volume['uuid'] or "<UNDEFINED>")
  146. for volume in volumes]
  147. )]
  148. if volume['uuid'] == '':
  149. print 'WARNING: No UUID detected for device %s. One time pads will be disabled.' % volume['device']
  150. shouldSave(options,[
  151. ('Name', options['deviceName']),
  152. ('Vendor', device.vendor),
  153. ('Model', device.product),
  154. ('Serial', device.serialNumber),
  155. ('UUID', volume['uuid'] or "<UNDEFINED>")
  156. ])
  157. try:
  158. doc = minidom.parse(options['configFile'])
  159. except Exception, err:
  160. print 'Unable to read %s: %s' % (options['configFile'], err)
  161. sys.exit(1)
  162. devs = doc.getElementsByTagName('devices')
  163. dev = doc.createElement('device')
  164. dev.attributes['id'] = options['deviceName']
  165. for name, value in (('vendor', device.vendor),
  166. ('model', device.product),
  167. ('serial', device.serialNumber),
  168. ('volume_uuid', volume['uuid'])):
  169. if value == '':
  170. continue
  171. e = doc.createElement(name)
  172. t = doc.createTextNode(value)
  173. e.appendChild(t)
  174. dev.appendChild(e)
  175. # Disable one time pads if there's no device UUID
  176. if volume['uuid'] == '':
  177. e = doc.createElement('option')
  178. e.setAttribute('name', 'one_time_pad')
  179. e.appendChild(doc.createTextNode('false'))
  180. dev.appendChild(e)
  181. devs[0].appendChild(prettifyElement(dev))
  182. writeConf(options, doc)
  183. def usage():
  184. print 'Usage: %s [--config file] --add-device <name> [--no-autodetect]' % os.path.basename(__file__)
  185. sys.exit(1)
  186. import getopt
  187. try:
  188. opts, args = getopt.getopt(sys.argv[1:], "hd:nu:c:",
  189. ["help", "add-device=", "add-user=", "config="])
  190. except getopt.GetoptError:
  191. usage()
  192. if len(args) != 0:
  193. usage()
  194. options = { 'deviceName' : None, 'userName' : None,
  195. 'configFile' : '/etc/pamusb.conf' }
  196. for o, a in opts:
  197. if o in ("-h", "--help"):
  198. usage()
  199. if o in ("-d", "--add-device"):
  200. options['deviceName'] = a
  201. if o in ("-u", "--add-user"):
  202. options['userName'] = a
  203. if o in ("-c", "--config"):
  204. options['configFile'] = a
  205. if options['deviceName'] is not None and options['userName'] is not None:
  206. print 'You cannot use both --add-user and --add-device'
  207. usage()
  208. if options['deviceName'] is None and options['userName'] is None:
  209. usage()
  210. if options['deviceName'] is not None:
  211. bus = dbus.SystemBus()
  212. halService = bus.get_object('org.freedesktop.Hal',
  213. '/org/freedesktop/Hal/Manager')
  214. halManager = dbus.Interface(halService, 'org.freedesktop.Hal.Manager')
  215. try:
  216. addDevice(options)
  217. except KeyboardInterrupt:
  218. sys.exit(1)
  219. if options['userName'] is not None:
  220. try:
  221. addUser(options)
  222. except KeyboardInterrupt:
  223. sys.exit(1)