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.

269 lines
7.6 KiB

18 years ago
18 years ago
17 years ago
17 years ago
17 years ago
18 years ago
17 years ago
17 years ago
18 years ago
17 years ago
18 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 __isChildOfDevice(self, udi):
  33. obj = bus.get_object('org.freedesktop.Hal', udi)
  34. properties = obj.GetAllProperties(
  35. dbus_interface = 'org.freedesktop.Hal.Device')
  36. if not properties.has_key('info.parent'):
  37. return False
  38. if properties.has_key('info.bus') and properties['info.bus'] == 'usb_device':
  39. return False
  40. if properties['info.parent'] == self.__udi:
  41. return True
  42. return self.__isChildOfDevice(properties['info.parent'])
  43. def __findStorageDevice(self):
  44. for child in halManager.FindDeviceByCapability('storage'):
  45. if self.__isChildOfDevice(child):
  46. self.__storageUdi = child
  47. return
  48. raise Exception, '%s is not a storage device.' % self.__udi
  49. def __repr__(self):
  50. return "%s %s (%s)" % (self.vendor, self.product, self.serialNumber)
  51. def volumes(self):
  52. vols = []
  53. for volume in halManager.FindDeviceByCapability('volume'):
  54. deviceObj = bus.get_object('org.freedesktop.Hal',
  55. volume)
  56. deviceProperties = deviceObj.GetAllProperties(
  57. dbus_interface = 'org.freedesktop.Hal.Device')
  58. if deviceProperties['block.storage_device'] != self.__storageUdi:
  59. continue
  60. vols.append({'uuid' : deviceProperties['volume.uuid'],
  61. 'device' : deviceProperties['block.device']})
  62. return vols
  63. def listOptions(question, options, autodetect = True):
  64. if autodetect == True and len(options) == 1:
  65. print question
  66. print "* Using \"%s\" (only option)" % options[0]
  67. print
  68. return 0
  69. while True:
  70. try:
  71. print question
  72. for i in range(len(options)):
  73. print "%d) %s" % (i, options[i])
  74. print
  75. sys.stdout.write('[%s-%s]: ' % (0, len(options) - 1))
  76. optionId = int(sys.stdin.readline())
  77. print
  78. if optionId not in range(len(options)):
  79. raise Exception
  80. return optionId
  81. except KeyboardInterrupt: sys.exit()
  82. except Exception: pass
  83. else: break
  84. def writeConf(options, doc):
  85. try:
  86. f = open(options['configFile'], 'w')
  87. doc.writexml(f)
  88. f.close()
  89. except Exception, err:
  90. print 'Unable to save %s: %s' % (options['configFile'], err)
  91. sys.exit(1)
  92. else:
  93. print 'Done.'
  94. def shouldSave(options, items):
  95. print "\n".join(["%s\t\t: %s" % item for item in items])
  96. print
  97. print 'Save to %s ?' % options['configFile']
  98. sys.stdout.write('[Y/n] ')
  99. response = sys.stdin.readline().strip()
  100. if len(response) > 0 and response.lower() != 'y':
  101. sys.exit(1)
  102. def prettifyElement(element):
  103. tmp = minidom.parseString(element.toprettyxml())
  104. return tmp.lastChild
  105. def addUser(options):
  106. try:
  107. doc = minidom.parse(options['configFile'])
  108. except Exception, err:
  109. print 'Unable to read %s: %s' % (options['configFile'], err)
  110. sys.exit(1)
  111. devSection = doc.getElementsByTagName('devices')
  112. if len(devSection) == 0:
  113. print 'Malformed configuration file: No <devices> section found.'
  114. sys.exit(1)
  115. devicesObj = devSection[0].getElementsByTagName('device')
  116. if len(devicesObj) == 0:
  117. print 'No devices found.'
  118. print 'You must add a device (--add-device) before adding users'
  119. sys.exit(1)
  120. devices = []
  121. for device in devicesObj:
  122. devices.append(device.getAttribute('id'))
  123. device = devices[listOptions("Which device would you like to use for authentication ?",
  124. devices)]
  125. shouldSave(options, [
  126. ('User', options['userName']),
  127. ('Device', device)
  128. ])
  129. users = doc.getElementsByTagName('users')
  130. user = doc.createElement('user')
  131. user.attributes['id'] = options['userName']
  132. e = doc.createElement('device')
  133. t = doc.createTextNode(device)
  134. e.appendChild(t)
  135. user.appendChild(e)
  136. users[0].appendChild(prettifyElement(user))
  137. writeConf(options, doc)
  138. def addDevice(options):
  139. devices = []
  140. for udi in halManager.FindDeviceStringMatch('info.bus', 'usb_device'):
  141. try:
  142. devices.append(Device(udi))
  143. except Exception, ex:
  144. pass
  145. if len(devices) == 0:
  146. print 'No devices detected.'
  147. sys.exit()
  148. device = devices[listOptions("Please select the device you wish to add.", devices)]
  149. volumes = device.volumes()
  150. volume = volumes[listOptions("Which volume would you like to use for " \
  151. "storing data ?",
  152. ["%s (UUID: %s)" % (volume['device'],
  153. volume['uuid'] or "<UNDEFINED>")
  154. for volume in volumes]
  155. )]
  156. if volume['uuid'] == '':
  157. print 'WARNING: No UUID detected for device %s. One time pads will be disabled.' % volume['device']
  158. shouldSave(options,[
  159. ('Name', options['deviceName']),
  160. ('Vendor', device.vendor),
  161. ('Model', device.product),
  162. ('Serial', device.serialNumber),
  163. ('UUID', volume['uuid'] or "<UNDEFINED>")
  164. ])
  165. try:
  166. doc = minidom.parse(options['configFile'])
  167. except Exception, err:
  168. print 'Unable to read %s: %s' % (options['configFile'], err)
  169. sys.exit(1)
  170. devs = doc.getElementsByTagName('devices')
  171. dev = doc.createElement('device')
  172. dev.attributes['id'] = options['deviceName']
  173. for name, value in (('vendor', device.vendor),
  174. ('model', device.product),
  175. ('serial', device.serialNumber),
  176. ('volume_uuid', volume['uuid'])):
  177. if value == '':
  178. continue
  179. e = doc.createElement(name)
  180. t = doc.createTextNode(value)
  181. e.appendChild(t)
  182. dev.appendChild(e)
  183. # Disable one time pads if there's no device UUID
  184. if volume['uuid'] == '':
  185. e = doc.createElement('option')
  186. e.setAttribute('name', 'one_time_pad')
  187. e.appendChild(doc.createTextNode('false'))
  188. dev.appendChild(e)
  189. devs[0].appendChild(prettifyElement(dev))
  190. writeConf(options, doc)
  191. def usage():
  192. print 'Usage: %s [--config file] --add-device <name> [--no-autodetect]' % os.path.basename(__file__)
  193. sys.exit(1)
  194. import getopt
  195. try:
  196. opts, args = getopt.getopt(sys.argv[1:], "hd:nu:c:",
  197. ["help", "add-device=", "add-user=", "config="])
  198. except getopt.GetoptError:
  199. usage()
  200. if len(args) != 0:
  201. usage()
  202. options = { 'deviceName' : None, 'userName' : None,
  203. 'configFile' : '/etc/pamusb.conf' }
  204. for o, a in opts:
  205. if o in ("-h", "--help"):
  206. usage()
  207. if o in ("-d", "--add-device"):
  208. options['deviceName'] = a
  209. if o in ("-u", "--add-user"):
  210. options['userName'] = a
  211. if o in ("-c", "--config"):
  212. options['configFile'] = a
  213. if options['deviceName'] is not None and options['userName'] is not None:
  214. print 'You cannot use both --add-user and --add-device'
  215. usage()
  216. if options['deviceName'] is None and options['userName'] is None:
  217. usage()
  218. if options['deviceName'] is not None:
  219. bus = dbus.SystemBus()
  220. halService = bus.get_object('org.freedesktop.Hal',
  221. '/org/freedesktop/Hal/Manager')
  222. halManager = dbus.Interface(halService, 'org.freedesktop.Hal.Manager')
  223. try:
  224. addDevice(options)
  225. except KeyboardInterrupt:
  226. sys.exit(1)
  227. if options['userName'] is not None:
  228. try:
  229. addUser(options)
  230. except KeyboardInterrupt:
  231. sys.exit(1)