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.

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