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.

245 lines
6.1 KiB

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