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.

255 lines
7.1 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
  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. 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 writeConf(options, doc):
  75. try:
  76. f = open(options['configFile'], 'w')
  77. f.write(doc.toxml())
  78. f.close()
  79. except Exception, err:
  80. print 'Unable to save %s: %s' % (options['configFile'], err)
  81. sys.exit(1)
  82. else:
  83. print 'Done.'
  84. def shouldSave(options, items):
  85. print "\n".join(["%s\t\t: %s" % item for item in items])
  86. print
  87. print 'Save to %s ?' % options['configFile']
  88. sys.stdout.write('[y/n] ')
  89. if sys.stdin.readline().strip() != 'y':
  90. sys.exit(1)
  91. def addUser(options):
  92. print 'adding user %s' % options['userName']
  93. try:
  94. doc = minidom.parse(options['configFile'])
  95. except Exception, err:
  96. print 'Unable to read %s: %s' % (options['configFile'], err)
  97. sys.exit(1)
  98. devSection = doc.getElementsByTagName('devices')
  99. if len(devSection) == 0:
  100. print 'Malformed configuration file: No <devices> section found.'
  101. sys.exit(1)
  102. devicesObj = devSection[0].getElementsByTagName('device')
  103. if len(devicesObj) == 0:
  104. print 'No devices found.'
  105. print 'You must add a device (--add-device) before adding users'
  106. sys.exit(1)
  107. devices = []
  108. for device in devicesObj:
  109. devices.append(device.getAttribute('id'))
  110. print devices
  111. device = devices[listOptions("Which device would you like to use for authentication ?",
  112. devices, False)]
  113. shouldSave(options, [
  114. ('User', options['userName']),
  115. ('Device', device)
  116. ])
  117. users = doc.getElementsByTagName('users')
  118. user = doc.createElement('user')
  119. user.attributes['id'] = options['userName']
  120. e = doc.createElement('device')
  121. t = doc.createTextNode(device)
  122. e.appendChild(t)
  123. user.appendChild(e)
  124. users[0].appendChild(user)
  125. writeConf(options, doc)
  126. def addDevice(options):
  127. devices = []
  128. for udi in halManager.FindDeviceStringMatch('info.bus', 'usb_device'):
  129. try:
  130. devices.append(Device(udi))
  131. except Exception, ex:
  132. pass
  133. if len(devices) == 0:
  134. print 'No devices detected.'
  135. sys.exit()
  136. device = devices[listOptions("Please select the device you wish to add.", devices)]
  137. volumes = device.volumes()
  138. volume = volumes[listOptions("Which volume would you like to use for " \
  139. "storing data ?",
  140. ["%s (UUID: %s)" % (volume['device'],
  141. volume['uuid'])
  142. for volume in volumes]
  143. )]
  144. uuid = volume['uuid']
  145. if volume['uuid'] == '':
  146. print 'WARNING: No UUID detected for device %s. One time pads will be disabled.' % volume['device']
  147. uuid = "<UNDEFINED>"
  148. shouldSave(options,[
  149. ('Name', options['deviceName']),
  150. ('Vendor', device.vendor),
  151. ('Model', device.product),
  152. ('Serial', device.serialNumber),
  153. ('UUID', uuid)
  154. ])
  155. try:
  156. doc = minidom.parse(options['configFile'])
  157. except Exception, err:
  158. print 'Unable to read %s: %s' % (options['configFile'], err)
  159. sys.exit(1)
  160. devs = doc.getElementsByTagName('devices')
  161. dev = doc.createElement('device')
  162. dev.attributes['id'] = options['deviceName']
  163. devs[0].appendChild(dev)
  164. for name, value in (('vendor', device.vendor),
  165. ('model', device.product),
  166. ('serial', device.serialNumber),
  167. ('volume_uuid', volume['uuid'])):
  168. if value == '':
  169. continue
  170. e = doc.createElement(name)
  171. t = doc.createTextNode(value)
  172. e.appendChild(t)
  173. dev.appendChild(e)
  174. # Disable one time pads if there's no device UUID
  175. if volume['uuid'] == '':
  176. e = doc.createElement('option')
  177. e.setAttribute('name', 'one_time_pad')
  178. e.appendChild(doc.createTextNode('false'))
  179. dev.appendChild(e)
  180. writeConf(options, doc)
  181. def usage():
  182. print 'Usage: %s [--config file] --add-device <name> [--no-autodetect]' % os.path.basename(__file__)
  183. sys.exit(1)
  184. import getopt
  185. try:
  186. opts, args = getopt.getopt(sys.argv[1:], "hd:nu:c:",
  187. ["help", "add-device=", "add-user=", "config="])
  188. except getopt.GetoptError:
  189. usage()
  190. if len(args) != 0:
  191. usage()
  192. options = { 'deviceName' : None, 'userName' : None,
  193. 'configFile' : '/etc/pamusb.conf' }
  194. for o, a in opts:
  195. if o in ("-h", "--help"):
  196. usage()
  197. if o in ("-d", "--add-device"):
  198. options['deviceName'] = a
  199. if o in ("-u", "--add-user"):
  200. options['userName'] = a
  201. if o in ("-c", "--config"):
  202. options['configFile'] = a
  203. if options['deviceName'] is not None and options['userName'] is not None:
  204. print 'You cannot use both --add-user and --add-device'
  205. usage()
  206. if options['deviceName'] is None and options['userName'] is None:
  207. usage()
  208. if options['deviceName'] is not None:
  209. bus = dbus.SystemBus()
  210. halService = bus.get_object('org.freedesktop.Hal',
  211. '/org/freedesktop/Hal/Manager')
  212. halManager = dbus.Interface(halService, 'org.freedesktop.Hal.Manager')
  213. try:
  214. addDevice(options)
  215. except KeyboardInterrupt:
  216. sys.exit(1)
  217. if options['userName'] is not None:
  218. try:
  219. addUser(options)
  220. except KeyboardInterrupt:
  221. sys.exit(1)