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.

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