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.

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