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