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.

294 lines
7.0 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. for henv in hotplug.findall('env'):
  152. henv_var = re.sub(r'^(.*?)=.*$', '\\1', henv.text)
  153. henv_arg = re.sub(r'^.*?=(.*)$', '\\1', henv.text)
  154. henvs[henv_var] = henv_arg
  155. events[hotplug.get('event')].append(
  156. {
  157. 'env': henvs,
  158. 'cmd': hotplug.find('cmd').text
  159. }
  160. )
  161. deviceName = user.find('device').text.strip()
  162. devices = doc.findall("devices/device")
  163. for device in devices:
  164. if device.get('id') == deviceName:
  165. break
  166. logger.error('Device %s not found in configuration file' % deviceName)
  167. sys.exit(1)
  168. serial = device.find('serial').text.strip()
  169. def authChangeCallback(event):
  170. if event == 'removed':
  171. logger.info('Device "%s" has been removed, ' \
  172. 'locking down user "%s"...' % (deviceName, userName))
  173. for l in events['lock']:
  174. cmd = l['cmd']
  175. logger.info('Running "%s"' % cmd)
  176. subprocess.run(cmd.split(), env=l['env'], preexec_fn=runAs(uid, gid))
  177. logger.info('Locked.')
  178. return
  179. logger.info('Device "%s" has been inserted. ' \
  180. 'Performing verification...' % deviceName)
  181. cmdLine = "%s --debug --config=%s --service=pamusb-agent %s" % (
  182. options['check'], options['configFile'], userName)
  183. logger.info('Executing "%s"' % cmdLine)
  184. if not os.system(cmdLine):
  185. logger.info('Authentication succeeded. ' \
  186. 'Unlocking user "%s"...' % userName)
  187. for l in events['unlock']:
  188. cmd = l['cmd']
  189. logger.info('Running "%s"' % cmd)
  190. subprocess.run(cmd.split(), env=l['env'], preexec_fn=runAs(uid, gid))
  191. logger.info('Unlocked.')
  192. else:
  193. logger.info('Authentication failed for device %s. ' \
  194. 'Keeping user "%s" locked down.' % (deviceName, userName))
  195. hpDev = HotPlugDevice(serial)
  196. hpDev.addCallback(authChangeCallback)
  197. logger.info('Watching device "%s" for user "%s"' % (deviceName, userName))
  198. hpDev.run()
  199. udisks = UDisks.Client.new_sync()
  200. udisksObjectManager = udisks.get_object_manager()
  201. sysUsers= []
  202. validUsers = []
  203. with open('/etc/passwd', 'r') as f:
  204. for line in f.readlines():
  205. sysUser = re.sub(r'^(.*?):.*', '\\1', line[:-1])
  206. sysUsers.append(sysUser)
  207. f.close()
  208. logger.info('pamusb-agent up and running.')
  209. for userObj in users:
  210. userId = userObj.get('id')
  211. for sysUser_ in sysUsers:
  212. if (userId == sysUser_ and
  213. userObj not in validUsers):
  214. validUsers.append(userObj)
  215. # logger.error('User %s not found in configuration file' % username)
  216. for user in validUsers:
  217. threading.Thread(
  218. target=userDeviceThread,
  219. args=(user,)
  220. ).start()
  221. if options['daemon'] and os.fork():
  222. sys.exit(0)
  223. def sig_handler(sig, frame):
  224. logger.info('Stopping agent.')
  225. sys.exit(0)
  226. sys_signals = ['SIGINT', 'SIGTERM', 'SIGTSTP', 'SIGTTIN', 'SIGTTOU']
  227. for i in sys_signals:
  228. signal.signal(getattr(signal, i), sig_handler)