]> git.mxchange.org Git - friendica.git/blob - src/Util/ExAuth.php
Merge pull request #3971 from annando/no_template_escape
[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 dba;\r
41 \r
42 require_once 'include/dba.php';\r
43 \r
44 class ExAuth\r
45 {\r
46         private $bDebug;\r
47 \r
48         /**\r
49          * @brief Create the class\r
50          *\r
51          * @param boolean $bDebug Debug mode\r
52          */\r
53         public function __construct()\r
54         {\r
55                 $this->bDebug = (int) Config::get('jabber', 'debug');\r
56 \r
57                 openlog('auth_ejabberd', LOG_PID, LOG_USER);\r
58 \r
59                 $this->writeLog(LOG_NOTICE, 'start');\r
60         }\r
61 \r
62         /**\r
63          * @brief Standard input reading function, executes the auth with the provided\r
64          * parameters\r
65          *\r
66          * @return null\r
67          */\r
68         public function readStdin()\r
69         {\r
70                 while (!feof(STDIN)) {\r
71                         // Quit if the database connection went down\r
72                         if (!dba::connected()) {\r
73                                 $this->writeLog(LOG_ERR, 'the database connection went down');\r
74                                 return;\r
75                         }\r
76 \r
77                         $iHeader = fgets(STDIN, 3);\r
78                         $aLength = unpack('n', $iHeader);\r
79                         $iLength = $aLength['1'];\r
80 \r
81                         // No data? Then quit\r
82                         if ($iLength == 0) {\r
83                                 $this->writeLog(LOG_ERR, 'we got no data, quitting');\r
84                                 return;\r
85                         }\r
86 \r
87                         // Fetching the data\r
88                         $sData = fgets(STDIN, $iLength + 1);\r
89                         $this->writeLog(LOG_DEBUG, 'received data: ' . $sData);\r
90                         $aCommand = explode(':', $sData);\r
91                         if (is_array($aCommand)) {\r
92                                 switch ($aCommand[0]) {\r
93                                         case 'isuser':\r
94                                                 // Check the existance of a given username\r
95                                                 $this->isUser($aCommand);\r
96                                                 break;\r
97                                         case 'auth':\r
98                                                 // Check if the givven password is correct\r
99                                                 $this->auth($aCommand);\r
100                                                 break;\r
101                                         case 'setpass':\r
102                                                 // We don't accept the setting of passwords here\r
103                                                 $this->writeLog(LOG_NOTICE, 'setpass command disabled');\r
104                                                 fwrite(STDOUT, pack('nn', 2, 0));\r
105                                                 break;\r
106                                         default:\r
107                                                 // We don't know the given command\r
108                                                 $this->writeLog(LOG_NOTICE, 'unknown command ' . $aCommand[0]);\r
109                                                 fwrite(STDOUT, pack('nn', 2, 0));\r
110                                                 break;\r
111                                 }\r
112                         } else {\r
113                                 $this->writeLog(LOG_NOTICE, 'invalid command string ' . $sData);\r
114                                 fwrite(STDOUT, pack('nn', 2, 0));\r
115                         }\r
116                 }\r
117         }\r
118 \r
119         /**\r
120          * @brief Check if the given username exists\r
121          *\r
122          * @param array $aCommand The command array\r
123          */\r
124         private function isUser(array $aCommand)\r
125         {\r
126                 $a = get_app();\r
127 \r
128                 // Check if there is a username\r
129                 if (!isset($aCommand[1])) {\r
130                         $this->writeLog(LOG_NOTICE, 'invalid isuser command, no username given');\r
131                         fwrite(STDOUT, pack('nn', 2, 0));\r
132                         return;\r
133                 }\r
134 \r
135                 // Now we check if the given user is valid\r
136                 $sUser = str_replace(array('%20', '(a)'), array(' ', '@'), $aCommand[1]);\r
137 \r
138                 // Does the hostname match? So we try directly\r
139                 if ($a->get_hostname() == $aCommand[2]) {\r
140                         $this->writeLog(LOG_INFO, 'internal user check for ' . $sUser . '@' . $aCommand[2]);\r
141                         $found = dba::exists('user', ['nickname' => $sUser]);\r
142                 } else {\r
143                         $found = false;\r
144                 }\r
145 \r
146                 // If the hostnames doesn't match or there is some failure, we try to check remotely\r
147                 if (!$found) {\r
148                         $found = $this->checkUser($aCommand[2], $aCommand[1], true);\r
149                 }\r
150 \r
151                 if ($found) {\r
152                         // The user is okay\r
153                         $this->writeLog(LOG_NOTICE, 'valid user: ' . $sUser);\r
154                         fwrite(STDOUT, pack('nn', 2, 1));\r
155                 } else {\r
156                         // The user isn't okay\r
157                         $this->writeLog(LOG_WARNING, 'invalid user: ' . $sUser);\r
158                         fwrite(STDOUT, pack('nn', 2, 0));\r
159                 }\r
160         }\r
161 \r
162         /**\r
163          * @brief Check remote user existance via HTTP(S)\r
164          *\r
165          * @param string $host The hostname\r
166          * @param string $user Username\r
167          * @param boolean $ssl Should the check be done via SSL?\r
168          *\r
169          * @return boolean Was the user found?\r
170          */\r
171         private function checkUser($host, $user, $ssl)\r
172         {\r
173                 $this->writeLog(LOG_INFO, 'external user check for ' . $user . '@' . $host);\r
174 \r
175                 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/noscrape/' . $user;\r
176 \r
177                 $data = z_fetch_url($url);\r
178 \r
179                 if (!is_array($data)) {\r
180                         return false;\r
181                 }\r
182 \r
183                 if ($data['return_code'] != '200') {\r
184                         return false;\r
185                 }\r
186 \r
187                 $json = @json_decode($data['body']);\r
188                 if (!is_object($json)) {\r
189                         return false;\r
190                 }\r
191 \r
192                 return $json->nick == $user;\r
193         }\r
194 \r
195         /**\r
196          * @brief Authenticate the given user and password\r
197          *\r
198          * @param array $aCommand The command array\r
199          */\r
200         private function auth(array $aCommand)\r
201         {\r
202                 $a = get_app();\r
203 \r
204                 // check user authentication\r
205                 if (sizeof($aCommand) != 4) {\r
206                         $this->writeLog(LOG_NOTICE, 'invalid auth command, data missing');\r
207                         fwrite(STDOUT, pack('nn', 2, 0));\r
208                         return;\r
209                 }\r
210 \r
211                 // We now check if the password match\r
212                 $sUser = str_replace(array('%20', '(a)'), array(' ', '@'), $aCommand[1]);\r
213 \r
214                 // Does the hostname match? So we try directly\r
215                 if ($a->get_hostname() == $aCommand[2]) {\r
216                         $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]);\r
217 \r
218                         $aUser = dba::select('user', ['uid', 'password'], ['nickname' => $sUser], ['limit' => 1]);\r
219                         if (DBM::is_result($aUser)) {\r
220                                 $uid = $aUser['uid'];\r
221                                 $Error = $aUser['password'] != hash('whirlpool', $aCommand[3]);\r
222                         } else {\r
223                                 $this->writeLog(LOG_WARNING, 'user not found: ' . $sUser);\r
224                                 $Error = true;\r
225                                 $uid = -1;\r
226                         }\r
227                         if ($Error) {\r
228                                 $this->writeLog(LOG_INFO, 'check against alternate password for ' . $sUser . '@' . $aCommand[2]);\r
229                                 $sPassword = PConfig::get($uid, 'xmpp', 'password', null, true);\r
230                                 $Error = ($aCommand[3] != $sPassword);\r
231                         }\r
232                 } else {\r
233                         $Error = true;\r
234                 }\r
235 \r
236                 // If the hostnames doesn't match or there is some failure, we try to check remotely\r
237                 if ($Error) {\r
238                         $Error = !$this->checkCredentials($aCommand[2], $aCommand[1], $aCommand[3], true);\r
239                 }\r
240 \r
241                 if ($Error) {\r
242                         $this->writeLog(LOG_WARNING, 'authentification failed for user ' . $sUser . '@' . $aCommand[2]);\r
243                         fwrite(STDOUT, pack('nn', 2, 0));\r
244                 } else {\r
245                         $this->writeLog(LOG_NOTICE, 'authentificated user ' . $sUser . '@' . $aCommand[2]);\r
246                         fwrite(STDOUT, pack('nn', 2, 1));\r
247                 }\r
248         }\r
249 \r
250         /**\r
251          * @brief Check remote credentials via HTTP(S)\r
252          *\r
253          * @param string $host The hostname\r
254          * @param string $user Username\r
255          * @param string $password Password\r
256          * @param boolean $ssl Should the check be done via SSL?\r
257          *\r
258          * @return boolean Are the credentials okay?\r
259          */\r
260         private function checkCredentials($host, $user, $password, $ssl)\r
261         {\r
262                 $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json';\r
263 \r
264                 $ch = curl_init();\r
265                 curl_setopt($ch, CURLOPT_URL, $url);\r
266                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);\r
267                 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);\r
268                 curl_setopt($ch, CURLOPT_HEADER, true);\r
269                 curl_setopt($ch, CURLOPT_NOBODY, true);\r
270                 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);\r
271                 curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $password);\r
272 \r
273                 curl_exec($ch);\r
274                 $curl_info = @curl_getinfo($ch);\r
275                 $http_code = $curl_info['http_code'];\r
276                 curl_close($ch);\r
277 \r
278                 $this->writeLog(LOG_INFO, 'external auth for ' . $user . '@' . $host . ' returned ' . $http_code);\r
279 \r
280                 return $http_code == 200;\r
281         }\r
282 \r
283         /**\r
284          * @brief write data to the syslog\r
285          *\r
286          * @param integer $loglevel The syslog loglevel\r
287          * @param string $sMessage The syslog message\r
288          */\r
289         private function writeLog($loglevel, $sMessage)\r
290         {\r
291                 if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) {\r
292                         return;\r
293                 }\r
294                 syslog($loglevel, $sMessage);\r
295         }\r
296 \r
297         /**\r
298          * @brief destroy the class, close the syslog connection.\r
299          */\r
300         public function __destruct()\r
301         {\r
302                 $this->writeLog(LOG_NOTICE, 'stop');\r
303                 closelog();\r
304         }\r
305 }\r