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.

174 lines
6.0 KiB

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, force = False):
  57. if force == False and len(options) == 1:
  58. return 0
  59. while True:
  60. try:
  61. print question
  62. for i in range(len(options)):
  63. print "%d) %s" % (i, options[i])
  64. print
  65. sys.stdout.write('[%s-%s]: ' % (0, len(options) - 1))
  66. optionId = int(sys.stdin.readline())
  67. print
  68. if optionId not in range(len(options)):
  69. raise Exception
  70. return optionId
  71. except KeyboardInterrupt: sys.exit()
  72. except Exception: pass
  73. else: break
  74. def addDevice(options):
  75. devices = []
  76. for udi in halManager.FindDeviceStringMatch('info.bus', 'usb_device'):
  77. try:
  78. devices.append(Device(udi))
  79. except Exception, ex:
  80. pass
  81. if len(devices) == 0:
  82. print 'No devices detected.'
  83. sys.exit()
  84. device = devices[listOptions("Please select the device you wish to add.",
  85. devices, force = options['force'])]
  86. volumes = device.volumes()
  87. volume = volumes[listOptions("Which volume would you like to use for " \
  88. "storing data ?",
  89. ["%s (UUID: %s)" % (volume['device'],
  90. volume['uuid'])
  91. for volume in volumes],
  92. force = options['force'])]
  93. print 'Name\t\t: %s' % options['deviceName']
  94. print 'Vendor\t\t: %s' % device.vendor
  95. print 'Model\t\t: %s' % device.product
  96. print 'Serial\t\t: %s' % device.serialNumber
  97. print 'Volume UUID\t: %s (%s)' % (volume['uuid'], volume['device'])
  98. print
  99. print 'Save device to %s ?' % options['configFile']
  100. sys.stdout.write('[y/n] ')
  101. if sys.stdin.readline().strip() != 'y':
  102. sys.exit(1)
  103. doc = minidom.parse(options['configFile'])
  104. devs = doc.getElementsByTagName('devices')
  105. dev = doc.createElement('device')
  106. dev.attributes['id'] = options['deviceName']
  107. devs[0].appendChild(dev)
  108. for name, value in (('vendor', device.vendor),
  109. ('model', device.product),
  110. ('serial', device.serialNumber),
  111. ('volume_uuid', volume['uuid'])):
  112. e = doc.createElement(name)
  113. t = doc.createTextNode(value)
  114. e.appendChild(t)
  115. dev.appendChild(e)
  116. f = open(options['configFile'], 'w')
  117. f.write(doc.toxml())
  118. f.close()
  119. print 'Done.'
  120. def usage():
  121. print 'Usage: %s [--config file] --add-device <name> [--no-autodetect]' % os.path.basename(__file__)
  122. sys.exit(1)
  123. import getopt
  124. try:
  125. opts, args = getopt.getopt(sys.argv[1:], "ha:nc:",
  126. ["help", "add-device=", "no-autodetect",
  127. "config="])
  128. except getopt.GetoptError:
  129. usage()
  130. if len(args) != 0:
  131. usage()
  132. options = { 'force' : False, 'deviceName' : None,
  133. 'configFile' : '/etc/pusb/pusb.conf' }
  134. for o, a in opts:
  135. if o in ("-h", "--help"):
  136. usage()
  137. if o in ("-a", "--add-device"):
  138. options['deviceName'] = a
  139. if o in ("-n", "--no-autodetect"):
  140. options['force'] = True
  141. if o in ("-c", "--config"):
  142. options['configFile'] = a
  143. if options['deviceName'] is None:
  144. usage()
  145. bus = dbus.SystemBus()
  146. halService = bus.get_object('org.freedesktop.Hal',
  147. '/org/freedesktop/Hal/Manager')
  148. halManager = dbus.Interface(halService, 'org.freedesktop.Hal.Manager')
  149. addDevice(options)