]> git.mxchange.org Git - friendica.git/blob - src/Util/ExAuth.php
Review and Use statements
[friendica.git] / src / Util / ExAuth.php
1 <?php\r
2 \r
3 /*\r
4  * ejabberd extauth script for the integration with friendica\r
5  *\r
6  * Originally written for joomla by Dalibor Karlovic <dado@krizevci.info>\r
7  * modified for Friendica by Michael Vogel <icarus@dabo.de>\r
8  * published under GPL\r
9  *\r
10  * Latest version of the original script for joomla is available at:\r
11  * http://87.230.15.86/~dado/ejabberd/joomla-login\r
12  *\r
13  * Installation:\r
14  *\r
15  *      - Change it's owner to whichever user is running the server, ie. ejabberd\r
16  *        $ chown ejabberd:ejabberd /path/to/friendica/scripts/auth_ejabberd.php\r
17  *\r
18  *      - Change the access mode so it is readable only to the user ejabberd and has exec\r
19  *        $ chmod 700 /path/to/friendica/scripts/auth_ejabberd.php\r
20  *\r
21  *      - Edit your ejabberd.cfg file, comment out your auth_method and add:\r
22  *        {auth_method, external}.\r
23  *        {extauth_program, "/path/to/friendica/script/auth_ejabberd.php"}.\r
24  *\r
25  *      - Restart your ejabberd service, you should be able to login with your friendica auth info\r
26  *\r
27  * Other hints:\r
28  *      - if your users have a space or a @ in their nickname, they'll run into trouble\r
29  *        registering with any client so they should be instructed to replace these chars\r
30  *        " " (space) is replaced with "%20"\r
31  *        "@" is replaced with "(a)"\r
32  *\r
33  */\r
34 \r
35 namespace Friendica\Util;\r
36 \r
37 use Friendica\Core\Config;\r
38 use Friendica\Core\PConfig;\r
39 use Friendica\Database\DBM;\r
40 use Friendica\Model\User;\r
41 use dba;\r
42 \r
43 require_once 'include/dba.php';\r
44 \r
45 class ExAuth\r
46 {\r
47         private $bDebug;\r
48 \r
49         /**\r
50          * @brief Create the class\r
51          *\r
52          * @param boolean $bDebug Debug mode\r
53          */\r
54         public function __construct()\r
55         {\r
56                 $this->bDebug = (int) Config::get('jabber', 'debug');\r
57 \r
58                 openlog('auth_ejabberd', LOG_PID, LOG_USER);\r
59 \r
60                 $this->writeLog(LOG_NOTICE, 'start');\r
61         }\r
62 \r
63         /**\r
64          * @brief Standard input reading function, executes the auth with the provided\r
65          * parameters\r
66          *\r
67          * @return null\r
68          */\r
69         public function readStdin()\r
70         {\r
71                 while (!feof(STDIN)) {\r
72                         // Quit if the database connection went down\r
73                         if (!dba::connected()) {\r
74                                 $this->writeLog(LOG_ERR, 'the database connection went down');\r
75                                 return;\r
76                         }\r
77 \r
78                         $iHeader = fgets(STDIN, 3);\r
79                         $aLength = unpack('n', $iHeader);\r
80                         $iLength = $aLength['1'];\r
81 \r
82                         // No data? Then quit\r
83                         if ($iLength == 0) {\r
84                                 $this->writeLog(LOG_ERR, 'we got no data, quitting');\r
85                                 return;\r
86                         }\r
87 \r
88                         // Fetching the data\r
89                         $sData = fgets(STDIN, $iLength + 1);\r
90                         $this->writeLog(LOG_DEBUG, 'received data: ' . $sData);\r
91                         $aCommand = explode(':', $sData);\r
92                         if (is_array($aCommand)) {\r
93                                 switch ($aCommand[0]) {\r
94                                         case 'isuser':\r
95                                                 // Check the existance of a given username\r
96                                                 $this->isUser($aCommand);\r
97                                                 break;\r
98                                         case 'auth':\r
99                                                 // Check if the givven password is correct\r
100                                                 $this->auth($aCommand);\r
101                                                 break;\r
102                                         case 'setpass':\r
103                                                 // We don't accept the setting of passwords here\r
104                                                 $this->writeLog(LOG_NOTICE, 'setpass command disabled');\r
105                                                 fwrite(STDOUT, pack('nn', 2, 0));\r
106                                                 break;\r
107                                         default:\r
108                                                 // We don't know the given command\r
109                                                 $this->writeLog(LOG_NOTICE, 'unknown command ' . $aCommand[0]);\r
110                                                 fwrite(STDOUT, pack('nn', 2, 0));\r
111                                                 break;\r
112                                 }\r
113                         } else {\r
114                                 $this->writeLog(LOG_NOTICE, 'invalid command string ' . $sData);\r
115                                 fwrite(STDOUT, pack('nn', 2, 0));\r
116                         }\r
117                 }\r
118         }\r
119 \r
120         /**\r
121          * @brief Check if the given username exists\r
122          *\r
123          * @param array $aCommand The command array\r
124          */\r
125         private function isUser(array $aCommand)\r
126         {\r
127                 $a = get_app();\r
128 \r
129                 // Check if there is a username\r
130                 if (!isset($aCommand[1])) {\r
131                         $this->writeLog(LOG_NOTICE, 'invalid isuser command, no username given');\r
132                         fwrite(STDOUT, pack('nn', 2, 0));\r
133                         return;\r
134                 }\r
135 \r
136                 // Now we check if the given user is valid\r
137                 $sUser = str_replace(array('%20', '(a)'), array(' ', '@'), $aCommand[1]);\r
138 \r
139                 // Does the hostname match? So we try directly\r
140                 if ($a->get_hostname() == $aCommand[2]) {\r
141                         $this->writeLog(LOG_INFO, 'internal user check for ' . $sUser . '@' . $aCommand[2]);\r
142                         $found = dba::exists('user', ['nickname' => $sUser]);\r
143                 } else {\r
144                         $found = false;\r
145                 }\r
146 \r
147                 // If the hostnames doesn't match or there is some failure, we try to check remotely\r
148                 if (!$found) {\r
149                         $found = $this->checkUser($aCommand[2], $aCommand[1], true);\r
150                 }\r
151 \r
152                 if ($found) {\r
153                         // The user is okay\r
154                         $this->writeLog(LOG_NOTICE, 'valid user: ' . $sUser);\r
155                         fwrite(STDOUT, pack('nn', 2, 1));\r
156                 } else {\r
157                         // The user isn't okay\r
158                         $this->writeLog(LOG_WARNING, 'invalid user: ' . $sUser);\r
159                         fwrite(STDOUT, pack('nn', 2, 0));\r
160                 }\r
161         }\r
162 \r
163         /**\r
164          * @brief Check remote user existance via HTTP(S)\r
165          *\r
166          * @param string $host The hostname\r
167          * @param string $user Username\r
168          * @param boolean $ssl Should the check be done via SSL?\r
169          *\r
170          * @return boolean Was the user found?\r
171          */\r
172         private function checkUser($host, $user, $ssl)\r
173         {\r
174                 $this->writeLog(LOG_INFO, 'external user check for ' . $user . '@' . $host);\r
175 \r
176                 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/noscrape/' . $user;\r
177 \r
178                 $data = z_fetch_url($url);\r
179 \r
180                 if (!is_array($data)) {\r
181                         return false;\r
182                 }\r
183 \r
184                 if ($data['return_code'] != '200') {\r
185                         return false;\r
186                 }\r
187 \r
188                 $json = @json_decode($data['body']);\r
189                 if (!is_object($json)) {\r
190                         return false;\r
191                 }\r
192 \r
193                 return $json->nick == $user;\r
194         }\r
195 \r
196         /**\r
197          * @brief Authenticate the given user and password\r
198          *\r
199          * @param array $aCommand The command array\r
200          */\r
201         private function auth(array $aCommand)\r
202         {\r
203                 $a = get_app();\r
204 \r
205                 // check user authentication\r
206                 if (sizeof($aCommand) != 4) {\r
207                         $this->writeLog(LOG_NOTICE, 'invalid auth command, data missing');\r
208                         fwrite(STDOUT, pack('nn', 2, 0));\r
209                         return;\r
210                 }\r
211 \r
212                 // We now check if the password match\r
213                 $sUser = str_replace(array('%20', '(a)'), array(' ', '@'), $aCommand[1]);\r
214 \r
215                 // Does the hostname match? So we try directly\r
216                 if ($a->get_hostname() == $aCommand[2]) {\r
217                         $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]);\r
218 \r
219                         $aUser = dba::select('user', ['uid', 'password'], ['nickname' => $sUser], ['limit' => 1]);\r
220                         if (DBM::is_result($aUser)) {\r
221                                 $uid = User::authenticate($aUser, $aCommand[3]);\r
222                                 $Error = $uid === false;\r
223                         } else {\r
224                                 $this->writeLog(LOG_WARNING, 'user not found: ' . $sUser);\r
225                                 $Error = true;\r
226                                 $uid = -1;\r
227                         }\r
228                         if ($Error) {\r
229                                 $this->writeLog(LOG_INFO, 'check against alternate password for ' . $sUser . '@' . $aCommand[2]);\r
230                                 $sPassword = PConfig::get($uid, 'xmpp', 'password', null, true);\r
231                                 $Error = ($aCommand[3] != $sPassword);\r
232                         }\r
233                 } else {\r
234                         $Error = true;\r
235                 }\r
236 \r
237                 // If the hostnames doesn't match or there is some failure, we try to check remotely\r
238                 if ($Error) {\r
239                         $Error = !$this->checkCredentials($aCommand[2], $aCommand[1], $aCommand[3], true);\r
240                 }\r
241 \r
242                 if ($Error) {\r
243                         $this->writeLog(LOG_WARNING, 'authentification failed for user ' . $sUser . '@' . $aCommand[2]);\r
244                         fwrite(STDOUT, pack('nn', 2, 0));\r
245                 } else {\r
246                         $this->writeLog(LOG_NOTICE, 'authentificated user ' . $sUser . '@' . $aCommand[2]);\r
247                         fwrite(STDOUT, pack('nn', 2, 1));\r
248                 }\r
249         }\r
250 \r
251         /**\r
252          * @brief Check remote credentials via HTTP(S)\r
253          *\r
254          * @param string $host The hostname\r
255          * @param string $user Username\r
256          * @param string $password Password\r
257          * @param boolean $ssl Should the check be done via SSL?\r
258          *\r
259          * @return boolean Are the credentials okay?\r
260          */\r
261         private function checkCredentials($host, $user, $password, $ssl)\r
262         {\r
263                 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json';\r
264 \r
265                 $ch = curl_init();\r
266                 curl_setopt($ch, CURLOPT_URL, $url);\r
267                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);\r
268                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);\r
269                 curl_setopt($ch, CURLOPT_HEADER, true);\r
270                 curl_setopt($ch, CURLOPT_NOBODY, true);\r
271                 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);\r
272                 curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $password);\r
273 \r
274                 curl_exec($ch);\r
275                 $curl_info = @curl_getinfo($ch);\r
276                 $http_code = $curl_info['http_code'];\r
277                 curl_close($ch);\r
278 \r
279                 $this->writeLog(LOG_INFO, 'external auth for ' . $user . '@' . $host . ' returned ' . $http_code);\r
280 \r
281                 return $http_code == 200;\r
282         }\r
283 \r
284         /**\r
285          * @brief write data to the syslog\r
286          *\r
287          * @param integer $loglevel The syslog loglevel\r
288          * @param string $sMessage The syslog message\r
289          */\r
290         private function writeLog($loglevel, $sMessage)\r
291         {\r
292                 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {\r
293                         return;\r
294                 }\r
295                 syslog($loglevel, $sMessage);\r
296         }\r
297 \r
298         /**\r
299          * @brief destroy the class, close the syslog connection.\r
300          */\r
301         public function __destruct()\r
302         {\r
303                 $this->writeLog(LOG_NOTICE, 'stop');\r
304                 closelog();\r
305         }\r
306 }\r