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.

298 lines
7.1 KiB

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