ssh.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace SshModel;
  3. function get_ssh_keys($id) {
  4. $ini = parse_ini_file('../includes/config.ini');
  5. try {
  6. $ldapconn = ldap_connect($ini['hostname'], $ini['port']);
  7. ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
  8. ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);
  9. } catch (Exception $e) {
  10. die ('ERROR: ' . $e->getMessage());
  11. }
  12. $filter = "(&(uid=" . $id . ")(objectClass=ldapPublicKey))";
  13. $attributes = array("ldapPublicKey");
  14. if ($ldapconn) {
  15. $ldap_bind = ldap_bind($ldapconn, $ini['binddn'], $ini["bindpw"]);
  16. if ($ldap_bind) {
  17. $res = ldap_search($ldapconn, $ini['basedn'], $filter, $attributes);
  18. $info = ldap_get_entries($ldapconn, $res);
  19. if ($info["count"] > 0) {
  20. $keys = array();
  21. // if user has ssh keys
  22. if (isset($info[0]["sshpublickey"])) {
  23. for ($i = 0; $i < $info[0]["sshpublickey"]["count"]; $i++) {
  24. $key = $info[0]["sshpublickey"][$i];
  25. $key_name = array();
  26. preg_match("/\S+@\S+/", $key, $key_name);
  27. $keys[] = [$key_name[0] => $key];
  28. }
  29. return $keys;
  30. }
  31. }
  32. }
  33. }
  34. return false;
  35. }
  36. function add_ssh_key($id, $new_key) {
  37. $ini = parse_ini_file('../includes/config.ini');
  38. try {
  39. $ldapconn = ldap_connect($ini['hostname'], $ini['port']);
  40. ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
  41. ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);
  42. } catch (Exception $e) {
  43. die ('ERROR: ' . $e->getMessage());
  44. }
  45. if (!$ldapconn) {
  46. return false;
  47. }
  48. $ldap_bind = @ldap_bind($ldapconn, $ini['binddn'], $ini["bindpw"]);
  49. if (!$ldap_bind) {
  50. return false;
  51. }
  52. $dn = "uid=" . $id . "," . $ini['basedn'];
  53. $entry['sshPublicKey'] = $new_key;
  54. $res = @ldap_mod_add($ldapconn, $dn, $entry);
  55. return $res;
  56. }
  57. function del_ssh_key($id, $key) {
  58. $ini = parse_ini_file('../includes/config.ini');
  59. try {
  60. $ldapconn = ldap_connect($ini['hostname'], $ini['port']);
  61. ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
  62. ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);
  63. } catch (Exception $e) {
  64. die ('ERROR: ' . $e->getMessage());
  65. }
  66. if (!$ldapconn) {
  67. return false;
  68. }
  69. $ldap_bind = @ldap_bind($ldapconn, $ini['binddn'], $ini["bindpw"]);
  70. if (!$ldap_bind) {
  71. return false;
  72. }
  73. $dn = "uid=" . $id . "," . $ini['basedn'];
  74. $entry["sshPublicKey"] = $key;
  75. $res = @ldap_mod_del($ldapconn, $dn, $entry);
  76. return $res;
  77. }