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.

223 lines
5.6 KiB

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