.htaccess
5 months ago
Client.php
5 months ago
WellKnown.php
5 months ago
index.html
5 months ago
web.config
5 months ago
WellKnown.php
81 lines
| 1 | <?php |
| 2 | /* |
| 3 | * |
| 4 | * JetBackup @ package |
| 5 | * Created By Idan Ben-Ezra |
| 6 | * |
| 7 | * Copyrights @ JetApps |
| 8 | * https://www.jetapps.com |
| 9 | * |
| 10 | **/ |
| 11 | namespace JetBackup\SocketAPI\Client; |
| 12 | |
| 13 | use JetBackup\Entities\Util; |
| 14 | use JetBackup\SocketAPI\Exception\WellKnownException; |
| 15 | |
| 16 | class WellKnown { |
| 17 | |
| 18 | const WELL_KNOWN_FILENAME = '.jetbackup-well-known'; |
| 19 | const HASH_CHARS = '0123456789abcdef'; |
| 20 | const HASH_REGEX = '^[0-9a-f]{32}$'; |
| 21 | const HASH_LENGTH = 32; |
| 22 | |
| 23 | private $_details; |
| 24 | private $_file; |
| 25 | |
| 26 | private function __construct() { |
| 27 | $this->_details = Util::getpwuid(Util::geteuid()); |
| 28 | if (!$this->_details) throw new WellKnownException("[wellknown auth] Cannot get posix uid/gid details"); |
| 29 | $this->_file = preg_replace("#/+#", "/" ,$this->_details['dir'] . '/' . self::WELL_KNOWN_FILENAME); |
| 30 | } |
| 31 | |
| 32 | private static function _generateHash() { |
| 33 | $randomString = ''; |
| 34 | for ($i = 0; $i < self::HASH_LENGTH; $i++) $randomString .= self::HASH_CHARS[rand(0, strlen(self::HASH_CHARS)-1)]; |
| 35 | return $randomString; |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * @return string |
| 40 | * @throws WellKnownException |
| 41 | */ |
| 42 | private function _generate() { |
| 43 | if(file_exists($this->_file) && !@unlink($this->_file)) throw new WellKnownException("Failed deleting old well known file"); |
| 44 | $password = self::_generateHash(); |
| 45 | $umask = umask(077); |
| 46 | if(!file_put_contents($this->_file, $password)) throw new WellKnownException("Failed writing password to well known file"); |
| 47 | umask($umask); |
| 48 | return $password; |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * @return string |
| 53 | * @throws WellKnownException |
| 54 | */ |
| 55 | private function _fetch() { |
| 56 | if(file_exists($this->_file)) { |
| 57 | $stat = stat($this->_file); |
| 58 | if( |
| 59 | $stat['mtime'] > (time()-3600) && |
| 60 | substr(sprintf('%o', $stat['mode']), -4) == '0600' && |
| 61 | $this->_details['uid'] == $stat['uid'] && |
| 62 | ($password = file_get_contents($this->_file)) && |
| 63 | self::_validateHash($password) |
| 64 | ) return $password; |
| 65 | } |
| 66 | return $this->_generate(); |
| 67 | } |
| 68 | |
| 69 | private static function _validateHash($hash) { |
| 70 | return preg_match("/" . self::HASH_REGEX . "/", $hash); |
| 71 | } |
| 72 | |
| 73 | /** |
| 74 | * @return string |
| 75 | * @throws WellKnownException |
| 76 | */ |
| 77 | public static function getPassword() { |
| 78 | return (new WellKnown())->_fetch(); |
| 79 | } |
| 80 | } |
| 81 |