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.

261 lines
7.3 KiB

18 years ago
18 years ago
17 years ago
18 years ago
17 years ago
18 years ago
18 years ago
17 years ago
17 years ago
17 years ago
17 years ago
17 years ago
17 years ago
18 years ago
17 years ago
18 years ago
18 years ago
17 years ago
18 years ago
17 years ago
18 years ago
17 years ago
18 years ago
17 years ago
17 years ago
17 years ago
18 years ago
17 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. doc.writexml(f)
  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 prettifyElement(element):
  92. return element
  93. # tmp = minidom.parseString(element.toprettyxml())
  94. # return tmp.lastChild
  95. def addUser(options):
  96. print 'adding user %s' % options['userName']
  97. try:
  98. doc = minidom.parse(options['configFile'])
  99. except Exception, err:
  100. print 'Unable to read %s: %s' % (options['configFile'], err)
  101. sys.exit(1)
  102. devSection = doc.getElementsByTagName('devices')
  103. if len(devSection) == 0:
  104. print 'Malformed configuration file: No <devices> section found.'
  105. sys.exit(1)
  106. devicesObj = devSection[0].getElementsByTagName('device')
  107. if len(devicesObj) == 0:
  108. print 'No devices found.'
  109. print 'You must add a device (--add-device) before adding users'
  110. sys.exit(1)
  111. devices = []
  112. for device in devicesObj:
  113. devices.append(device.getAttribute('id'))
  114. print devices
  115. device = devices[listOptions("Which device would you like to use for authentication ?",
  116. devices, False)]
  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'])
  146. for volume in volumes]
  147. )]
  148. uuid = volume['uuid']
  149. if volume['uuid'] == '':
  150. print 'WARNING: No UUID detected for device %s. One time pads will be disabled.' % volume['device']
  151. uuid = "<UNDEFINED>"
  152. shouldSave(options,[
  153. ('Name', options['deviceName']),
  154. ('Vendor', device.vendor),
  155. ('Model', device.product),
  156. ('Serial', device.serialNumber),
  157. ('UUID', uuid)
  158. ])
  159. try:
  160. doc = minidom.parse(options['configFile'])
  161. except Exception, err:
  162. print 'Unable to read %s: %s' % (options['configFile'], err)
  163. sys.exit(1)
  164. devs = doc.getElementsByTagName('devices')
  165. dev = doc.createElement('device')
  166. dev.attributes['id'] = options['deviceName']
  167. for name, value in (('vendor', device.vendor),
  168. ('model', device.product),
  169. ('serial', device.serialNumber),
  170. ('volume_uuid', volume['uuid'])):
  171. if value == '':
  172. continue
  173. e = doc.createElement(name)
  174. t = doc.createTextNode(value)
  175. e.appendChild(t)
  176. dev.appendChild(e)
  177. # Disable one time pads if there's no device UUID
  178. if volume['uuid'] == '':
  179. e = doc.createElement('option')
  180. e.setAttribute('name', 'one_time_pad')
  181. e.appendChild(doc.createTextNode('false'))
  182. dev.appendChild(e)
  183. devs[0].appendChild(prettifyElement(dev))
  184. writeConf(options, doc)
  185. def usage():
  186. print 'Usage: %s [--config file] --add-device <name> [--no-autodetect]' % os.path.basename(__file__)
  187. sys.exit(1)
  188. import getopt
  189. try:
  190. opts, args = getopt.getopt(sys.argv[1:], "hd:nu:c:",
  191. ["help", "add-device=", "add-user=", "config="])
  192. except getopt.GetoptError:
  193. usage()
  194. if len(args) != 0:
  195. usage()
  196. options = { 'deviceName' : None, 'userName' : None,
  197. 'configFile' : '/etc/pamusb.conf' }
  198. for o, a in opts:
  199. if o in ("-h", "--help"):
  200. usage()
  201. if o in ("-d", "--add-device"):
  202. options['deviceName'] = a
  203. if o in ("-u", "--add-user"):
  204. options['userName'] = a
  205. if o in ("-c", "--config"):
  206. options['configFile'] = a
  207. if options['deviceName'] is not None and options['userName'] is not None:
  208. print 'You cannot use both --add-user and --add-device'
  209. usage()
  210. if options['deviceName'] is None and options['userName'] is None:
  211. usage()
  212. if options['deviceName'] is not None:
  213. bus = dbus.SystemBus()
  214. halService = bus.get_object('org.freedesktop.Hal',
  215. '/org/freedesktop/Hal/Manager')
  216. halManager = dbus.Interface(halService, 'org.freedesktop.Hal.Manager')
  217. try:
  218. addDevice(options)
  219. except KeyboardInterrupt:
  220. sys.exit(1)
  221. if options['userName'] is not None:
  222. try:
  223. addUser(options)
  224. except KeyboardInterrupt:
  225. sys.exit(1)