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.

215 lines
5.5 KiB

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