keyhelper.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. (c) 2014-2018 - Copyright Red Hat Inc
  5. Authors:
  6. Patrick Uiterwijk <puiterwijk@redhat.com>
  7. """
  8. from __future__ import unicode_literals, print_function, absolute_import
  9. import sys
  10. import os
  11. import requests
  12. # Since this is run by sshd, we don't have a way to set environment
  13. # variables ahead of time
  14. if "PAGURE_CONFIG" not in os.environ and os.path.exists(
  15. "/etc/pagure/pagure.cfg"
  16. ):
  17. os.environ["PAGURE_CONFIG"] = "/etc/pagure/pagure.cfg"
  18. # Here starts the code
  19. from pagure.config import config as pagure_config
  20. # Get the arguments
  21. # Expect sshd config:
  22. # AuthorizedKeysCommand: <scriptpath> "%u" "%h" "%t" "%f"
  23. # <us> <username> <homedir> <keytype> <fingerprint>
  24. # At this moment, we ignore the homedir and fingerprint, since looking
  25. # up a key by fingerprint would require some model changes (ssh keys would
  26. # need to be stored in a fashion like DeployKeys).
  27. # But to not break installations in the future, we should ask installations
  28. # to set up sshd in a way that it will work if we use them in the future.
  29. if len(sys.argv) < 5:
  30. print("Invalid call, too few arguments", file=sys.stderr)
  31. sys.exit(1)
  32. username, userhome, keytype, fingerprint = sys.argv[1:5]
  33. username_lookup = pagure_config["SSH_KEYS_USERNAME_LOOKUP"]
  34. expect_username = pagure_config["SSH_KEYS_USERNAME_EXPECT"]
  35. if username in pagure_config["SSH_KEYS_USERNAME_FORBIDDEN"]:
  36. print("User is forbidden for keyhelper.", file=sys.stderr)
  37. sys.exit(1)
  38. if not username_lookup:
  39. if not expect_username:
  40. print("Pagure keyhelper configured incorrectly", file=sys.stderr)
  41. sys.exit(1)
  42. if username != expect_username:
  43. # Nothing to look up, this user is not git-related
  44. sys.exit(0)
  45. url = "%s/pv/ssh/lookupkey/" % pagure_config["APP_URL"]
  46. data = {"search_key": fingerprint}
  47. if username_lookup:
  48. data["username"] = username
  49. headers = {}
  50. if pagure_config.get("SSH_ADMIN_TOKEN"):
  51. headers["Authorization"] = "token %s" % pagure_config["SSH_ADMIN_TOKEN"]
  52. resp = requests.post(url, data=data, headers=headers)
  53. if not resp.status_code == 200:
  54. print(
  55. "Error during lookup request: status: %s" % resp.status_code,
  56. file=sys.stderr,
  57. )
  58. sys.exit(1)
  59. result = resp.json()
  60. if not result["found"]:
  61. # Everything OK, key just didn't exist.
  62. sys.exit(0)
  63. print(
  64. "%s %s"
  65. % (pagure_config["SSH_KEYS_OPTIONS"] % result, result["public_key"])
  66. )