keyhelper.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. pagure_url = pagure_config["APP_URL"].rstrip("/")
  46. url = "%s/pv/ssh/lookupkey/" % pagure_url
  47. data = {"search_key": fingerprint}
  48. if username_lookup:
  49. data["username"] = username
  50. headers = {}
  51. if pagure_config.get("SSH_ADMIN_TOKEN"):
  52. headers["Authorization"] = "token %s" % pagure_config["SSH_ADMIN_TOKEN"]
  53. resp = requests.post(url, data=data, headers=headers)
  54. if not resp.status_code == 200:
  55. print(
  56. "Error during lookup request: status: %s" % resp.status_code,
  57. file=sys.stderr,
  58. )
  59. sys.exit(1)
  60. result = resp.json()
  61. if not result["found"]:
  62. # Everything OK, key just didn't exist.
  63. sys.exit(0)
  64. print(
  65. "%s %s"
  66. % (pagure_config["SSH_KEYS_OPTIONS"] % result, result["public_key"])
  67. )