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.

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