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.

266 lines
7.9 KiB

18 years ago
18 years ago
18 years ago
13 years ago
18 years ago
13 years ago
13 years ago
13 years ago
18 years ago
13 years ago
13 years ago
18 years ago
13 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
18 years ago
13 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
18 years ago
13 years ago
  1. #!/usr/bin/env python2
  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.UDisks',
  25. udi)
  26. deviceProperties = dbus.Interface(deviceObj, dbus.PROPERTIES_IFACE)
  27. if deviceProperties.Get('org.freedesktop.UDisks.Device', 'DeviceIsRemovable') != 1:
  28. # Workaround for removable devices with fixed media (such as SD cards)
  29. if not "mmcblk" in udi:
  30. raise Exception, 'Not a removable device'
  31. self.vendor = deviceProperties.Get('org.freedesktop.UDisks.Device', 'DriveVendor')
  32. self.product = deviceProperties.Get('org.freedesktop.UDisks.Device', 'DriveModel')
  33. self.serialNumber = deviceProperties.Get('org.freedesktop.UDisks.Device', 'DriveSerial')
  34. if len(self.volumes()) < 1:
  35. raise Exception, 'Device does not contain any volume'
  36. def volumes(self):
  37. vols = []
  38. for udi in halManager.get_dbus_method('EnumerateDevices')():
  39. deviceObj = bus.get_object('org.freedesktop.UDisks',
  40. udi)
  41. deviceProperties = dbus.Interface(deviceObj, dbus.PROPERTIES_IFACE)
  42. if deviceProperties.Get('org.freedesktop.UDisks.Device', 'DeviceIsPartition') != 1:
  43. continue
  44. if deviceProperties.Get('org.freedesktop.UDisks.Device', 'PartitionSlave') != self.__udi:
  45. continue
  46. vols.append({'uuid' : deviceProperties.Get('org.freedesktop.UDisks.Device', 'IdUuid'),
  47. 'device' : deviceProperties.Get('org.freedesktop.UDisks.Device', 'DeviceFile')})
  48. return vols
  49. def __repr__(self):
  50. if self.product is not None:
  51. return "%s %s (%s)" % (self.vendor, self.product, self.serialNumber)
  52. return self.serialNumber
  53. def listOptions(question, options, autodetect = True):
  54. if autodetect == True and len(options) == 1:
  55. print question
  56. print "* Using \"%s\" (only option)" % options[0]
  57. print
  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. response = sys.stdin.readline().strip()
  90. if len(response) > 0 and response.lower() != 'y':
  91. sys.exit(1)
  92. def prettifyElement(element):
  93. tmp = minidom.parseString(element.toprettyxml())
  94. return tmp.lastChild
  95. def addUser(options):
  96. try:
  97. doc = minidom.parse(options['configFile'])
  98. except Exception, err:
  99. print 'Unable to read %s: %s' % (options['configFile'], err)
  100. sys.exit(1)
  101. devSection = doc.getElementsByTagName('devices')
  102. if len(devSection) == 0:
  103. print 'Malformed configuration file: No <devices> section found.'
  104. sys.exit(1)
  105. devicesObj = devSection[0].getElementsByTagName('device')
  106. if len(devicesObj) == 0:
  107. print 'No devices found.'
  108. print 'You must add a device (--add-device) before adding users'
  109. sys.exit(1)
  110. devices = []
  111. for device in devicesObj:
  112. devices.append(device.getAttribute('id'))
  113. device = devices[listOptions("Which device would you like to use for authentication ?",
  114. devices)]
  115. shouldSave(options, [
  116. ('User', options['userName']),
  117. ('Device', device)
  118. ])
  119. users = doc.getElementsByTagName('users')
  120. user = doc.createElement('user')
  121. user.attributes['id'] = options['userName']
  122. e = doc.createElement('device')
  123. t = doc.createTextNode(device)
  124. e.appendChild(t)
  125. user.appendChild(e)
  126. users[0].appendChild(prettifyElement(user))
  127. writeConf(options, doc)
  128. def addDevice(options):
  129. devices = []
  130. for udi in halManager.get_dbus_method('EnumerateDevices')():
  131. try:
  132. if options['verbose']:
  133. print 'Inspecting %s' % udi
  134. devices.append(Device(udi))
  135. except Exception, ex:
  136. if options['verbose']:
  137. print "\tInvalid: %s" % ex
  138. pass
  139. else:
  140. if options['verbose']:
  141. print "\tValid"
  142. if len(devices) == 0:
  143. print 'No devices detected. Try running in verbose (-v) mode to see what\'s going on.'
  144. sys.exit()
  145. device = devices[listOptions("Please select the device you wish to add.", devices)]
  146. volumes = device.volumes()
  147. volume = volumes[listOptions("Which volume would you like to use for " \
  148. "storing data ?",
  149. ["%s (UUID: %s)" % (volume['device'],
  150. volume['uuid'] or "<UNDEFINED>")
  151. for volume in volumes]
  152. )]
  153. if volume['uuid'] == '':
  154. print 'WARNING: No UUID detected for device %s. One time pads will be disabled.' % volume['device']
  155. shouldSave(options,[
  156. ('Name', options['deviceName']),
  157. ('Vendor', device.vendor or "Unknown"),
  158. ('Model', device.product or "Unknown"),
  159. ('Serial', device.serialNumber),
  160. ('UUID', volume['uuid'] or "Unknown")
  161. ])
  162. try:
  163. doc = minidom.parse(options['configFile'])
  164. except Exception, err:
  165. print 'Unable to read %s: %s' % (options['configFile'], err)
  166. sys.exit(1)
  167. devs = doc.getElementsByTagName('devices')
  168. dev = doc.createElement('device')
  169. dev.attributes['id'] = options['deviceName']
  170. for name, value in (('vendor', device.vendor),
  171. ('model', device.product),
  172. ('serial', device.serialNumber),
  173. ('volume_uuid', volume['uuid'])):
  174. if value is None or value == '':
  175. continue
  176. e = doc.createElement(name)
  177. t = doc.createTextNode(value)
  178. e.appendChild(t)
  179. dev.appendChild(e)
  180. # Disable one time pads if there's no device UUID
  181. if volume['uuid'] == '':
  182. e = doc.createElement('option')
  183. e.setAttribute('name', 'one_time_pad')
  184. e.appendChild(doc.createTextNode('false'))
  185. dev.appendChild(e)
  186. devs[0].appendChild(prettifyElement(dev))
  187. writeConf(options, doc)
  188. def usage():
  189. print 'Usage: %s [--help] [--verbose] [--config=path] [--add-user=name | --add-device=name]' % os.path.basename(__file__)
  190. sys.exit(1)
  191. import getopt
  192. try:
  193. opts, args = getopt.getopt(sys.argv[1:], "hvd:nu:c:",
  194. ["help", "verbose", "add-device=", "add-user=", "config="])
  195. except getopt.GetoptError:
  196. usage()
  197. if len(args) != 0:
  198. usage()
  199. options = { 'deviceName' : None, 'userName' : None,
  200. 'configFile' : '/etc/pamusb.conf', 'verbose' : False }
  201. for o, a in opts:
  202. if o in ("-h", "--help"):
  203. usage()
  204. if o in ("-v", "--verbose"):
  205. options['verbose'] = True
  206. if o in ("-d", "--add-device"):
  207. options['deviceName'] = a
  208. if o in ("-u", "--add-user"):
  209. options['userName'] = a
  210. if o in ("-c", "--config"):
  211. options['configFile'] = a
  212. if options['deviceName'] is not None and options['userName'] is not None:
  213. print 'You cannot use both --add-user and --add-device'
  214. usage()
  215. if options['deviceName'] is None and options['userName'] is None:
  216. usage()
  217. if options['deviceName'] is not None:
  218. bus = dbus.SystemBus()
  219. halService = bus.get_object('org.freedesktop.UDisks',
  220. '/org/freedesktop/UDisks')
  221. halManager = dbus.Interface(halService, 'org.freedesktop.UDisks')
  222. try:
  223. addDevice(options)
  224. except KeyboardInterrupt:
  225. sys.exit(1)
  226. if options['userName'] is not None:
  227. try:
  228. addUser(options)
  229. except KeyboardInterrupt:
  230. sys.exit(1)