apiauthaction.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. <?php
  2. /**
  3. * StatusNet, the distributed open-source microblogging tool
  4. *
  5. * Base class for API actions that require authentication
  6. *
  7. * PHP version 5
  8. *
  9. * LICENCE: This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU Affero General Public License as published by
  11. * the Free Software Foundation, either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU Affero General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Affero General Public License
  20. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  21. *
  22. * @category API
  23. * @package StatusNet
  24. * @author Adrian Lang <mail@adrianlang.de>
  25. * @author Brenda Wallace <shiny@cpan.org>
  26. * @author Craig Andrews <candrews@integralblue.com>
  27. * @author Dan Moore <dan@moore.cx>
  28. * @author Evan Prodromou <evan@status.net>
  29. * @author mEDI <medi@milaro.net>
  30. * @author Sarven Capadisli <csarven@status.net>
  31. * @author Zach Copley <zach@status.net>
  32. * @copyright 2009-2010 StatusNet, Inc.
  33. * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
  34. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  35. * @link http://status.net/
  36. */
  37. /* External API usage documentation. Please update when you change how this method works. */
  38. /*! @page authentication Authentication
  39. GNU social supports HTTP Basic Authentication and OAuth for API calls.
  40. @warning Currently, users who have created accounts without setting a
  41. password via OpenID, Facebook Connect, etc., cannot use the API until
  42. they set a password with their account settings panel.
  43. @section HTTP Basic Auth
  44. @section OAuth
  45. */
  46. if (!defined('GNUSOCIAL')) { exit(1); }
  47. /**
  48. * Actions extending this class will require auth
  49. *
  50. * @category API
  51. * @package StatusNet
  52. * @author Zach Copley <zach@status.net>
  53. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  54. * @link http://status.net/
  55. */
  56. class ApiAuthAction extends ApiAction
  57. {
  58. var $auth_user_nickname = null;
  59. var $auth_user_password = null;
  60. /**
  61. * Take arguments for running, looks for an OAuth request,
  62. * and outputs basic auth header if needed
  63. *
  64. * @param array $args $_REQUEST args
  65. *
  66. * @return boolean success flag
  67. *
  68. */
  69. protected function prepare(array $args=array())
  70. {
  71. parent::prepare($args);
  72. // NOTE: $this->scoped and $this->auth_user has to get set in
  73. // prepare(), not handle(), as subclasses use them in prepares.
  74. // Allow regular login session, but we have to double-check the
  75. // HTTP_REFERER value to avoid cross domain POSTing since the API
  76. // doesn't use the "token" form field.
  77. if (common_logged_in() && common_local_referer()) {
  78. $this->scoped = Profile::current();
  79. $this->auth_user = $this->scoped->getUser();
  80. if (!$this->auth_user->hasRight(Right::API)) {
  81. // TRANS: Authorization exception thrown when a user without API access tries to access the API.
  82. throw new AuthorizationException(_('Not allowed to use API.'));
  83. }
  84. // Let's run this in the same way as if we've just authenticated the user (basic/oauth auth)
  85. Event::handle('EndSetApiUser', array($this->auth_user));
  86. $this->access = self::READ_WRITE;
  87. } else {
  88. $oauthReq = $this->getOAuthRequest();
  89. if ($oauthReq instanceof OAuthRequest) {
  90. $this->checkOAuthRequest($oauthReq);
  91. } else {
  92. // If not using OAuth, check if there is a basic auth
  93. // and require it if the current action requires it.
  94. $this->checkBasicAuthUser($this->requiresAuth());
  95. }
  96. // NOTE: Make sure we're scoped properly based on the auths!
  97. if (isset($this->auth_user) && $this->auth_user instanceof User) {
  98. $this->scoped = $this->auth_user->getProfile();
  99. } else {
  100. $this->scoped = null;
  101. }
  102. }
  103. // legacy user transferral
  104. // TODO: remove when sure no extended classes need it
  105. $this->user = $this->auth_user;
  106. // Reject API calls with the wrong access level
  107. if ($this->isReadOnly($args) == false) {
  108. if ($this->access != self::READ_WRITE) {
  109. // TRANS: Client error 401.
  110. $msg = _('API resource requires read-write access, ' .
  111. 'but you only have read access.');
  112. $this->clientError($msg, 401);
  113. }
  114. }
  115. return true;
  116. }
  117. /**
  118. * Determine whether the request is an OAuth request.
  119. * This is to avoid doign any unnecessary DB lookups.
  120. *
  121. * @return mixed the OAuthRequest or false
  122. */
  123. function getOAuthRequest()
  124. {
  125. ApiOAuthAction::cleanRequest();
  126. $req = OAuthRequest::from_request();
  127. $consumer = $req->get_parameter('oauth_consumer_key');
  128. $accessToken = $req->get_parameter('oauth_token');
  129. // XXX: Is it good enough to assume it's not meant to be an
  130. // OAuth request if there is no consumer or token? --Z
  131. if (empty($consumer) || empty($accessToken)) {
  132. return false;
  133. }
  134. return $req;
  135. }
  136. /**
  137. * Verifies the OAuth request signature, sets the auth user
  138. * and access type (read-only or read-write)
  139. *
  140. * @param OAuthRequest $request the OAuth Request
  141. *
  142. * @return nothing
  143. */
  144. function checkOAuthRequest($request)
  145. {
  146. $datastore = new ApiGNUsocialOAuthDataStore();
  147. $server = new OAuthServer($datastore);
  148. $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
  149. $server->add_signature_method($hmac_method);
  150. try {
  151. $server->verify_request($request);
  152. $consumer = $request->get_parameter('oauth_consumer_key');
  153. $access_token = $request->get_parameter('oauth_token');
  154. $app = Oauth_application::getByConsumerKey($consumer);
  155. if (empty($app)) {
  156. common_log(
  157. LOG_WARNING,
  158. 'API OAuth - Couldn\'t find the OAuth app for consumer key: ' .
  159. $consumer
  160. );
  161. // TRANS: OAuth exception thrown when no application is found for a given consumer key.
  162. throw new OAuthException(_('No application for that consumer key.'));
  163. }
  164. // set the source attr
  165. if ($app->name != 'anonymous') {
  166. $this->source = $app->name;
  167. }
  168. $appUser = Oauth_application_user::getKV('token', $access_token);
  169. if (!empty($appUser)) {
  170. // If access_type == 0 we have either a request token
  171. // or a bad / revoked access token
  172. if ($appUser->access_type != 0) {
  173. // Set the access level for the api call
  174. $this->access = ($appUser->access_type & Oauth_application::$writeAccess)
  175. ? self::READ_WRITE : self::READ_ONLY;
  176. // Set the auth user
  177. if (Event::handle('StartSetApiUser', array(&$user))) {
  178. $user = User::getKV('id', $appUser->profile_id);
  179. }
  180. if ($user instanceof User) {
  181. if (!$user->hasRight(Right::API)) {
  182. // TRANS: Authorization exception thrown when a user without API access tries to access the API.
  183. throw new AuthorizationException(_('Not allowed to use API.'));
  184. }
  185. $this->auth_user = $user;
  186. Event::handle('EndSetApiUser', array($this->auth_user));
  187. } else {
  188. // If $user is not a real User, let's force it to null.
  189. $this->auth_user = null;
  190. }
  191. // FIXME: setting the value returned by common_current_user()
  192. // There should probably be a better method for this. common_set_user()
  193. // does lots of session stuff.
  194. global $_cur;
  195. $_cur = $this->auth_user;
  196. $msg = "API OAuth authentication for user '%s' (id: %d) on behalf of " .
  197. "application '%s' (id: %d) with %s access.";
  198. common_log(
  199. LOG_INFO,
  200. sprintf(
  201. $msg,
  202. $this->auth_user->nickname,
  203. $this->auth_user->id,
  204. $app->name,
  205. $app->id,
  206. ($this->access = self::READ_WRITE) ? 'read-write' : 'read-only'
  207. )
  208. );
  209. } else {
  210. // TRANS: OAuth exception given when an incorrect access token was given for a user.
  211. throw new OAuthException(_('Bad access token.'));
  212. }
  213. } else {
  214. // Also should not happen.
  215. // TRANS: OAuth exception given when no user was found for a given token (no token was found).
  216. throw new OAuthException(_('No user for that token.'));
  217. }
  218. } catch (OAuthException $e) {
  219. $this->logAuthFailure($e->getMessage());
  220. common_log(LOG_WARNING, 'API OAuthException - ' . $e->getMessage());
  221. $this->clientError($e->getMessage(), 401);
  222. }
  223. }
  224. /**
  225. * Does this API resource require authentication?
  226. *
  227. * @return boolean true
  228. */
  229. public function requiresAuth()
  230. {
  231. return true;
  232. }
  233. /**
  234. * Check for a user specified via HTTP basic auth. If there isn't
  235. * one, try to get one by outputting the basic auth header.
  236. *
  237. * @return boolean true or false
  238. */
  239. function checkBasicAuthUser($required = true)
  240. {
  241. $this->basicAuthProcessHeader();
  242. $realm = common_config('api', 'realm');
  243. if (empty($realm)) {
  244. $realm = common_config('site', 'name') . ' API';
  245. }
  246. if (empty($this->auth_user_nickname) && $required) {
  247. header('WWW-Authenticate: Basic realm="' . $realm . '"');
  248. // show error if the user clicks 'cancel'
  249. // TRANS: Client error thrown when authentication fails because a user clicked "Cancel".
  250. $this->clientError(_('Could not authenticate you.'), 401);
  251. } else {
  252. // $this->auth_user_nickname - i.e. PHP_AUTH_USER - will have a value since it was not empty
  253. $user = common_check_user($this->auth_user_nickname,
  254. $this->auth_user_password);
  255. Event::handle('StartSetApiUser', array(&$user));
  256. if ($user instanceof User) {
  257. if (!$user->hasRight(Right::API)) {
  258. // TRANS: Authorization exception thrown when a user without API access tries to access the API.
  259. throw new AuthorizationException(_('Not allowed to use API.'));
  260. }
  261. $this->auth_user = $user;
  262. Event::handle('EndSetApiUser', array($this->auth_user));
  263. } else {
  264. $this->auth_user = null;
  265. }
  266. if ($required && $this->auth_user instanceof User) {
  267. // By default, basic auth users have rw access
  268. $this->access = self::READ_WRITE;
  269. } elseif ($required) {
  270. $msg = sprintf(
  271. "basic auth nickname = %s",
  272. $this->auth_user_nickname
  273. );
  274. $this->logAuthFailure($msg);
  275. // We must present WWW-Authenticate in accordance to HTTP status code 401
  276. header('WWW-Authenticate: Basic realm="' . $realm . '"');
  277. // TRANS: Client error thrown when authentication fails.
  278. $this->clientError(_('Could not authenticate you.'), 401);
  279. } else {
  280. // all get rw access for actions that don't require auth
  281. $this->access = self::READ_WRITE;
  282. }
  283. }
  284. }
  285. /**
  286. * Read the HTTP headers and set the auth user. Decodes HTTP_AUTHORIZATION
  287. * param to support basic auth when PHP is running in CGI mode.
  288. *
  289. * @return void
  290. */
  291. function basicAuthProcessHeader()
  292. {
  293. $authHeaders = array('AUTHORIZATION',
  294. 'HTTP_AUTHORIZATION',
  295. 'REDIRECT_HTTP_AUTHORIZATION'); // rewrite for CGI
  296. $authorization_header = null;
  297. foreach ($authHeaders as $header) {
  298. if (isset($_SERVER[$header])) {
  299. $authorization_header = $_SERVER[$header];
  300. break;
  301. }
  302. }
  303. if (isset($_SERVER['PHP_AUTH_USER'])) {
  304. $this->auth_user_nickname = $_SERVER['PHP_AUTH_USER'];
  305. $this->auth_user_password = $_SERVER['PHP_AUTH_PW'];
  306. } elseif (isset($authorization_header)
  307. && strstr(substr($authorization_header, 0, 5), 'Basic')) {
  308. // Decode the HTTP_AUTHORIZATION header on php-cgi server self
  309. // on fcgid server the header name is AUTHORIZATION
  310. $auth_hash = base64_decode(substr($authorization_header, 6));
  311. list($this->auth_user_nickname,
  312. $this->auth_user_password) = explode(':', $auth_hash);
  313. // Set all to null on a empty basic auth request
  314. if (empty($this->auth_user_nickname)) {
  315. $this->auth_user_nickname = null;
  316. $this->auth_password = null;
  317. }
  318. }
  319. }
  320. /**
  321. * Log an API authentication failure. Collect the proxy and IP
  322. * and log them
  323. *
  324. * @param string $logMsg additional log message
  325. */
  326. function logAuthFailure($logMsg)
  327. {
  328. list($proxy, $ip) = common_client_ip();
  329. $msg = sprintf(
  330. 'API auth failure (proxy = %1$s, ip = %2$s) - ',
  331. $proxy,
  332. $ip
  333. );
  334. common_log(LOG_WARNING, $msg . $logMsg);
  335. }
  336. }