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.

276 lines
6.7 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 subprocess
  24. import syslog
  25. import gi
  26. import threading
  27. gi.require_version('UDisks', '2.0')
  28. from gi.repository import GLib
  29. from gi.repository import UDisks
  30. import xml.etree.ElementTree as et
  31. class HotPlugDevice:
  32. def __init__(self, serial):
  33. self.__udi = None
  34. self.__serial = serial
  35. self.__callbacks = []
  36. self.__running = False
  37. def run(self):
  38. self.__scanDevices()
  39. self.__registerSignals()
  40. self.__running = True
  41. GLib.MainLoop().run()
  42. print('signals registered')
  43. def addCallback(self, callback):
  44. self.__callbacks.append(callback)
  45. def __scanDevices(self):
  46. for udi in udisksObjectManager.get_objects():
  47. if udi.get_block():
  48. device = udisks.get_drive_for_block(udi.get_block())
  49. if device:
  50. self.__deviceAdded(device)
  51. def __registerSignals(self):
  52. for signal, callback in (('object-added', self.__objectAdded),
  53. ('object-removed', self.__objectRemoved)):
  54. udisksObjectManager.connect(signal, callback)
  55. def __objectAdded(self, _, udi):
  56. if udi.get_block():
  57. device = udisks.get_drive_for_block(udi.get_block())
  58. if device:
  59. self.__deviceAdded(device)
  60. def __objectRemoved(self, _, udi):
  61. if udi.get_block():
  62. device = udisks.get_drive_for_block(udi.get_block())
  63. if device:
  64. self.__deviceRemoved(device)
  65. def __deviceAdded(self, udi):
  66. if self.__udi is not None:
  67. return
  68. if udi.get_property('serial') != self.__serial:
  69. return
  70. self.__udi = udi
  71. if self.__running:
  72. [ cb('added') for cb in self.__callbacks ]
  73. def __deviceRemoved(self, udi):
  74. if self.__udi is None:
  75. return
  76. if self.__udi != udi:
  77. return
  78. self.__udi = None
  79. if self.__running:
  80. [ cb('removed') for cb in self.__callbacks ]
  81. class Log:
  82. def __init__(self):
  83. syslog.openlog('pamusb-agent', syslog.LOG_PID | syslog.LOG_PERROR,
  84. syslog.LOG_AUTH)
  85. def info(self, message):
  86. self.__logMessage(syslog.LOG_NOTICE, message)
  87. def error(self, message):
  88. self.__logMessage(syslog.LOG_ERR, message)
  89. def __logMessage(self, priority, message):
  90. syslog.syslog(priority, message)
  91. def usage():
  92. print('Usage: %s [--help] [--config=path] [--daemon] [--check=path]' % \
  93. os.path.basename(__file__))
  94. sys.exit(1)
  95. def runAs(uid, gid):
  96. def set_id():
  97. os.setuid(uid)
  98. os.setgid(gid)
  99. return set_id
  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/security/pam_usb.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. logger = Log()
  125. doc = et.parse(options['configFile'])
  126. users = doc.findall('users/user')
  127. def userDeviceThread(user):
  128. userName = user.get('id')
  129. uid = pwd.getpwnam(userName)[2]
  130. gid = pwd.getpwnam(userName)[3]
  131. os.environ = None
  132. events = {
  133. 'lock' : [],
  134. 'unlock' : []
  135. }
  136. for hotplug in user.findall('agent'):
  137. henvs = {}
  138. for henv in hotplug.findall('env'):
  139. henv_var = re.sub(r'^(.*?)=.*$', '\\1', henv.text)
  140. henv_arg = re.sub(r'^.*?=(.*)$', '\\1', henv.text)
  141. henvs[henv_var] = henv_arg
  142. events[hotplug.get('event')].append(
  143. {
  144. 'env': henvs,
  145. 'cmd': hotplug.find('cmd').text
  146. }
  147. )
  148. deviceName = user.find('device').text.strip()
  149. devices = doc.findall("devices/device")
  150. for device in devices:
  151. if device.get('id') == deviceName:
  152. break
  153. logger.error('Device %s not found in configuration file' % deviceName)
  154. sys.exit(1)
  155. serial = device.find('serial').text.strip()
  156. def authChangeCallback(event):
  157. if event == 'removed':
  158. logger.info('Device "%s" has been removed, ' \
  159. 'locking down user "%s"...' % (deviceName, userName))
  160. for l in events['lock']:
  161. cmd = l['cmd']
  162. logger.info('Running "%s"' % cmd)
  163. subprocess.run(cmd.split(), env=l['env'], preexec_fn=runAs(uid, gid))
  164. logger.info('Locked.')
  165. return
  166. logger.info('Device "%s" has been inserted. ' \
  167. 'Performing verification...' % deviceName)
  168. cmdLine = "%s --debug --config=%s --service=pamusb-agent %s" % (
  169. options['check'], options['configFile'], userName)
  170. logger.info('Executing "%s"' % cmdLine)
  171. if not os.system(cmdLine):
  172. logger.info('Authentication succeeded. ' \
  173. 'Unlocking user "%s"...' % userName)
  174. for l in events['unlock']:
  175. cmd = l['cmd']
  176. logger.info('Running "%s"' % cmd)
  177. subprocess.run(cmd.split(), env=l['env'], preexec_fn=runAs(uid, gid))
  178. logger.info('Unlocked.')
  179. else:
  180. logger.info('Authentication failed for device %s. ' \
  181. 'Keeping user "%s" locked down.' % (deviceName, userName))
  182. hpDev = HotPlugDevice(serial)
  183. hpDev.addCallback(authChangeCallback)
  184. logger.info('Watching device "%s" for user "%s"' % (deviceName, userName))
  185. hpDev.run()
  186. udisks = UDisks.Client.new_sync()
  187. udisksObjectManager = udisks.get_object_manager()
  188. sysUsers= []
  189. validUsers = []
  190. with open('/etc/passwd', 'r') as f:
  191. for line in f.readlines():
  192. sysUser = re.sub(r'^(.*?):.*', '\\1', line[:-1])
  193. sysUsers.append(sysUser)
  194. f.close()
  195. logger.info('pamusb-agent up and running.')
  196. for userObj in users:
  197. userId = userObj.get('id')
  198. for sysUser_ in sysUsers:
  199. if (userId == sysUser_ and
  200. userObj not in validUsers):
  201. validUsers.append(userObj)
  202. # logger.error('User %s not found in configuration file' % username)
  203. for user in validUsers:
  204. threading.Thread(
  205. target=userDeviceThread,
  206. args=(user,)
  207. ).start()
  208. if options['daemon'] and os.fork():
  209. sys.exit(0)
  210. def sig_handler(sig, frame):
  211. logger.info('Stopping agent.')
  212. sys.exit(0)
  213. sys_signals = ['SIGINT', 'SIGTERM', 'SIGTSTP', 'SIGTTIN', 'SIGTTOU']
  214. for i in sys_signals:
  215. signal.signal(getattr(signal, i), sig_handler)