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.

173 lines
6.0 KiB

  1. #!/usr/bin/env python2.4
  2. #
  3. # Copyright (c) 2003-2006 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. from xml.dom import minidom
  20. class Device:
  21. def __init__(self, udi):
  22. self.__udi = udi
  23. self.__findStorageDevice()
  24. deviceObj = bus.get_object('org.freedesktop.Hal',
  25. udi)
  26. deviceProperties = deviceObj.GetAllProperties(
  27. dbus_interface = 'org.freedesktop.Hal.Device')
  28. self.vendor = deviceProperties['usb_device.vendor']
  29. self.product = deviceProperties['info.product']
  30. self.serialNumber = deviceProperties['usb_device.serial']
  31. def __findStorageDevice(self):
  32. for child in halManager.FindDeviceByCapability('storage'):
  33. obj = bus.get_object('org.freedesktop.Hal',
  34. child)
  35. properties = obj.GetAllProperties(
  36. dbus_interface = 'org.freedesktop.Hal.Device')
  37. if properties['storage.physical_device'] == self.__udi + '_if0':
  38. self.__storageUdi = child
  39. return
  40. raise Exception, '%s is not a storage device.' % self.__udi
  41. def __repr__(self):
  42. return "%s %s (%s)" % (self.vendor, self.product, self.serialNumber)
  43. def volumes(self):
  44. vols = []
  45. for volume in halManager.FindDeviceByCapability('volume'):
  46. deviceObj = bus.get_object('org.freedesktop.Hal',
  47. volume)
  48. deviceProperties = deviceObj.GetAllProperties(
  49. dbus_interface = 'org.freedesktop.Hal.Device')
  50. if deviceProperties['block.storage_device'] != self.__storageUdi:
  51. continue
  52. vols.append({'uuid' : deviceProperties['volume.uuid'],
  53. 'device' : deviceProperties['block.device']})
  54. return vols
  55. def listOptions(question, options, force = False):
  56. if force == False and len(options) == 1:
  57. return 0
  58. while True:
  59. try:
  60. print question
  61. for i in range(len(options)):
  62. print "%d) %s" % (i, options[i])
  63. print
  64. sys.stdout.write('[%s-%s]: ' % (0, len(options) - 1))
  65. optionId = int(sys.stdin.readline())
  66. print
  67. if optionId not in range(len(options)):
  68. raise Exception
  69. return optionId
  70. except KeyboardInterrupt: sys.exit()
  71. except Exception: pass
  72. else: break
  73. def addDevice(options):
  74. devices = []
  75. for udi in halManager.FindDeviceStringMatch('info.bus', 'usb_device'):
  76. try:
  77. devices.append(Device(udi))
  78. except Exception, ex:
  79. pass
  80. if len(devices) == 0:
  81. print 'No devices detected.'
  82. sys.exit()
  83. device = devices[listOptions("Please select the device you wish to add.",
  84. devices, force = options['force'])]
  85. volumes = device.volumes()
  86. volume = volumes[listOptions("Which volume would you like to use for " \
  87. "storing data ?",
  88. ["%s (UUID: %s)" % (volume['device'],
  89. volume['uuid'])
  90. for volume in volumes],
  91. force = options['force'])]
  92. print 'Name\t\t: %s' % options['deviceName']
  93. print 'Vendor\t\t: %s' % device.vendor
  94. print 'Model\t\t: %s' % device.product
  95. print 'Serial\t\t: %s' % device.serialNumber
  96. print 'Volume UUID\t: %s (%s)' % (volume['uuid'], volume['device'])
  97. print
  98. print 'Save device to %s ?' % options['configFile']
  99. sys.stdout.write('[y/n] ')
  100. if sys.stdin.readline().strip() != 'y':
  101. sys.exit(1)
  102. doc = minidom.parse(options['configFile'])
  103. devs = doc.getElementsByTagName('devices')
  104. dev = doc.createElement('device')
  105. dev.attributes['id'] = options['deviceName']
  106. devs[0].appendChild(dev)
  107. for name, value in (('vendor', device.vendor),
  108. ('model', device.product),
  109. ('serial', device.serialNumber),
  110. ('volume_uuid', volume['uuid'])):
  111. e = doc.createElement(name)
  112. t = doc.createTextNode(value)
  113. e.appendChild(t)
  114. dev.appendChild(e)
  115. f = open(options['configFile'], 'w')
  116. f.write(doc.toxml())
  117. f.close()
  118. print 'Done.'
  119. def usage():
  120. print 'Usage: %s [--config file] --add-device <name> [--no-autodetect]' % sys.argv[0]
  121. sys.exit(1)
  122. import getopt
  123. try:
  124. opts, args = getopt.getopt(sys.argv[1:], "ha:nc:",
  125. ["help", "add-device=", "no-autodetect",
  126. "config="])
  127. except getopt.GetoptError:
  128. usage()
  129. if len(args) != 0:
  130. usage()
  131. options = { 'force' : False, 'deviceName' : None,
  132. 'configFile' : '/etc/pam_usb/pusb.conf' }
  133. for o, a in opts:
  134. if o in ("-h", "--help"):
  135. usage()
  136. if o in ("-a", "--add-device"):
  137. options['deviceName'] = a
  138. if o in ("-n", "--no-autodetect"):
  139. options['force'] = True
  140. if o in ("-c", "--config"):
  141. options['configFile'] = a
  142. if options['deviceName'] is None:
  143. usage()
  144. bus = dbus.SystemBus()
  145. halService = bus.get_object('org.freedesktop.Hal',
  146. '/org/freedesktop/Hal/Manager')
  147. halManager = dbus.Interface(halService, 'org.freedesktop.Hal.Manager')
  148. addDevice(options)