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.

216 lines
5.7 KiB

18 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
17 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
17 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 os
  18. import sys
  19. import pwd
  20. import getopt
  21. import syslog
  22. import gobject
  23. import dbus
  24. if getattr(dbus, 'version', (0,0,0)) >= (0,41,0):
  25. import dbus.glib
  26. try:
  27. # Python 2.5
  28. import xml.etree.ElementTree as et
  29. except ImportError:
  30. # Python 2.4
  31. try:
  32. import cElementTree as et
  33. except ImportError:
  34. import elementtree.ElementTree as et
  35. class HotPlugDevice:
  36. def __init__(self, serial):
  37. self.__udi = None
  38. self.__serial = serial
  39. self.__callbacks = []
  40. self.__bus = dbus.SystemBus()
  41. self.__running = False
  42. def run(self):
  43. self.__scanDevices()
  44. self.__registerSignals()
  45. self.__running = True
  46. gobject.MainLoop().run()
  47. print 'signals registered'
  48. def addCallback(self, callback):
  49. self.__callbacks.append(callback)
  50. def __scanDevices(self):
  51. halService = self.__bus.get_object('org.freedesktop.Hal',
  52. '/org/freedesktop/Hal/Manager')
  53. halManager = dbus.Interface(halService, 'org.freedesktop.Hal.Manager')
  54. for udi in halManager.FindDeviceStringMatch('info.bus', 'usb_device'):
  55. self.__deviceAdded(udi)
  56. def __registerSignals(self):
  57. for signal, callback in (('DeviceAdded', self.__deviceAdded),
  58. ('DeviceRemoved', self.__deviceRemoved)):
  59. self.__bus.add_signal_receiver(callback,
  60. signal,
  61. 'org.freedesktop.Hal.Manager',
  62. 'org.freedesktop.Hal',
  63. '/org/freedesktop/Hal/Manager')
  64. def __deviceAdded(self, udi):
  65. if self.__udi is not None:
  66. return
  67. deviceObj = self.__bus.get_object('org.freedesktop.Hal',
  68. udi)
  69. deviceProperties = deviceObj.GetAllProperties(
  70. dbus_interface = 'org.freedesktop.Hal.Device')
  71. if not deviceProperties.has_key('usb_device.serial'):
  72. return
  73. if deviceProperties['usb_device.serial'] != self.__serial:
  74. return
  75. self.__udi = udi
  76. if self.__running:
  77. [ cb('added') for cb in self.__callbacks ]
  78. def __deviceRemoved(self, udi):
  79. if self.__udi is None:
  80. return
  81. if self.__udi != udi:
  82. return
  83. self.__udi = None
  84. if self.__running:
  85. [ cb('removed') for cb in self.__callbacks ]
  86. class Log:
  87. def __init__(self):
  88. syslog.openlog('pamusb-agent', syslog.LOG_PID | syslog.LOG_PERROR,
  89. syslog.LOG_AUTH)
  90. def info(self, message):
  91. self.__logMessage(syslog.LOG_NOTICE, message)
  92. def error(self, message):
  93. self.__logMessage(syslog.LOG_ERR, message)
  94. def __logMessage(self, priority, message):
  95. syslog.syslog(priority, message)
  96. def usage():
  97. print 'Usage: %s [--help] [--config=path] [--daemon] [--check=path]' % \
  98. os.path.basename(__file__)
  99. sys.exit(1)
  100. import getopt
  101. try:
  102. opts, args = getopt.getopt(sys.argv[1:], "hc:dc:",
  103. ["help", "config=", "daemon", "check="])
  104. except getopt.GetoptError:
  105. usage()
  106. options = {'configFile' : '/etc/pamusb.conf',
  107. 'daemon' : False,
  108. 'check' : '/usr/bin/pamusb-check'}
  109. if len(args) != 0:
  110. usage()
  111. for o, a in opts:
  112. if o in ('-h', '--help'):
  113. usage()
  114. if o in ('-c', '--config'):
  115. options['configFile'] = a
  116. if o in ('-d', '--daemon'):
  117. options['daemon'] = True
  118. if o in ('-c', '--check'):
  119. options['check'] = a
  120. if not os.path.exists(options['check']):
  121. print '%s not found.' % options['check']
  122. print "You might specify manually pamusb-check's location using --check."
  123. usage()
  124. username = pwd.getpwuid(os.getuid())[0]
  125. logger = Log()
  126. doc = et.parse(options['configFile'])
  127. users = doc.findall('users/user')
  128. for user in users:
  129. if user.get('id') == username:
  130. break
  131. else:
  132. logger.error('User %s not found in configuration file' % username)
  133. sys.exit(1)
  134. events = {
  135. 'lock' : [],
  136. 'unlock' : []
  137. }
  138. for hotplug in user.findall('agent'):
  139. events[hotplug.get('event')].append(hotplug.text)
  140. deviceName = user.find('device').text.strip()
  141. devices = doc.findall("devices/device")
  142. for device in devices:
  143. if device.get('id') == deviceName:
  144. break
  145. else:
  146. logger.error('Device %s not found in configurtion file' % deviceName)
  147. sys.exit(1)
  148. serial = device.find('serial').text.strip()
  149. def authChangeCallback(event):
  150. if event == 'removed':
  151. logger.info('Device "%s" has been removed, ' \
  152. 'locking down user "%s"...' % (deviceName, username))
  153. for cmd in events['lock']:
  154. logger.info('Running "%s"' % cmd)
  155. os.system(cmd)
  156. logger.info('Locked.')
  157. return
  158. logger.info('Device "%s" has been inserted. ' \
  159. 'Performing verification...' % deviceName)
  160. cmdLine = "%s --quiet --config=%s --service=pamusb-agent %s" % (
  161. options['check'], options['configFile'], username)
  162. logger.info('Executing "%s"' % cmdLine)
  163. if not os.system(cmdLine):
  164. logger.info('Authentication succeeded. ' \
  165. 'Unlocking user "%s"...' % username)
  166. for cmd in events['unlock']:
  167. logger.info('Running "%s"' % cmd)
  168. os.system(cmd)
  169. logger.info('Unlocked.')
  170. else:
  171. logger.info('Authentication failed for device %s. ' \
  172. 'Keeping user "%s" locked down.' % (deviceName, username))
  173. hpDev = HotPlugDevice(serial)
  174. hpDev.addCallback(authChangeCallback)
  175. if options['daemon'] and os.fork():
  176. sys.exit(0)
  177. logger.info('pamusb-agent up and running.')
  178. logger.info('Watching device "%s" for user "%s"' % (deviceName, username))
  179. try:
  180. hpDev.run()
  181. except KeyboardInterrupt:
  182. logger.error('Caught keyboard interruption, exiting...')