]>
git.defcon.no Git - hermes/blob - api/lib/auth_base.php
a2ce62c36bd0715c6fedcbc83aa2705e8271354d
2 require_once('config.php');
4 $config = get_config();
6 function authlevel_value( $level )
20 function authlevel_name( $level )
25 return 'limited_read';
35 /*******************************
36 * Load authentication plugin ..
37 *******************************/
38 if ( preg_match('/^\w+$/', $config['auth_backend']))
40 if ( !@include_once
( 'lib/auth_plugins/' . $config['auth_backend'] . ".php" ) )
41 { print json_encode( array( 'response' => 'error', 'cause' => 'auth-load' ) ); exit; }
44 { print json_encode( array( 'response' => 'error', 'cause' => 'config-error' ) ); exit; }
45 /*******************************/
47 function new_key( $hex = false )
49 // Basically this is at the moment a slightly modified
50 // version of generate_password() from user_functiions.php
51 // The behaviour/output of this function is expected to change
52 // so using generate_password() directly does not make sense...
55 while ( strlen( $string ) < $length )
58 $string .= substr(md5(rand().rand()), 0, $length+
1);
61 $string .= crypt( substr(sha1(rand()), 0, $length+
1) );
62 $string = preg_replace( '/\W/', '', $string);
65 return substr( $string, 1, $length );
68 function simple_authfail()
70 print json_encode( array( 'response' => 'failed', 'cause' => 'unauthorized', 'description' => 'Not authorized') );
74 function token_auth( )
78 // TODO: Part of ping/pong requirement.
79 // Run a function to clear all authkeys older than 5 minutes.
82 if ( array_key_exists('session', $_GET )
83 && array_key_exists('auth_key', $_GET ) )
85 if ( ! check_session($_GET['session'] ) ) simple_authfail();
86 if ( ! check_authkey($_GET['auth_key'] ) ) simple_authfail();
88 else simple_authfail();
91 function get_cookie_path ()
93 $name = $_SERVER["SCRIPT_NAME"];
94 $file = basename($name);
95 $path = preg_replace("/".$file."/", "", $name);
100 function check_authkey ( $key )
102 // TODO: Make real, actual checks...
103 if ( $key ) return true;
107 function expire_authkeys()
111 // Force deletion of sessions that have expired keys.
112 $query = sprintf("SELECT session, sessid FROM %s WHERE `last` < DATE_SUB( NOW(), INTERVAL %d MINUTE)",
113 $config['sessionkeys_table'],
114 $config['sessionkey_lifetime']);
115 $result = sql_dbquery( $config['provision_db'], $query );
116 while ( $row = @mysql_fetch_row
( $result ) )
118 remove_session( $row[0], $row[1] );
121 $query = sprintf("DELETE FROM %s WHERE `last` < DATE_SUB( NOW(), INTERVAL %d MINUTE)",
122 $config['sessionkeys_table'],
123 $config['sessionkey_lifetime']);
125 sql_dbexec( $config['provision_db'], $query );
128 function update_authkey ( $session, $authid )
132 $key = substr(new_key(), 0, 8);
136 // TODO: Refresh cookie
138 $remote = $_SERVER['REMOTE_ADDR'];
139 $query = sprintf("INSERT INTO %s ( `sessid`, `session`, `authid`, `client`, `key`, `last` )
140 VALUES ( '%s', '%s', '%s', '%s', '%s', NOW() )
141 ON DUPLICATE KEY UPDATE `key` = '%s', `last` = NOW()",
142 $config['sessionkeys_table'],
149 if ( ! sql_dbexec( $config['provision_db'], $query ) )
153 $_SESSION['kkey'] = $key;
154 $_SESSION['when'] = time();
158 function check_session ( $name )
160 session_name( $name );
162 if ( ! $_SESSION['authid'] )
164 return clear_credentials($name);
166 if ( ! $_COOKIE['client_key'] )
168 return clear_credentials($name);
171 $authid = $_SESSION['authid'];
172 $type = $_SESSION['type'];
173 $client_key = $_COOKIE['client_key'];
175 $level = get_authorization( $type, $authid );
176 if ( $level == false )
178 return clear_credentials($name);
181 $session_key = md5( $name . $authid );
182 if ( $client_key != $session_key )
184 return clear_credentials($name);
187 // If we got this far, things are looking good.
191 function set_credentials( $authid, $type )
193 $name = new_key(true);
194 session_name( $name );
196 $_SESSION['authid'] = $authid;
197 $_SESSION['type'] = $type;
199 $client_key = md5( $name . $authid );
200 setcookie('client_key', $client_key, time()+
180*60, get_cookie_path() );
205 function clear_credentials($name)
209 setcookie('client_key', '', 0, get_cookie_path() );
211 remove_session($name);
214 $query = sprintf("DELETE FROM %s WHERE `session` = '%s'",
215 $config['sessionkeys_table'],
217 sql_dbexec( $config['provision_db'], $query );
222 function remove_session ($name, $id = null )
227 setcookie($name, '', 0, "/");
230 $current_session = session_name( );
231 $current_sessid = session_id( );
236 setcookie( $name, '', 0, "/");
240 if ( $current_session && $current_session != $name )
242 session_id($current_sessid);
246 function add_apikey ( $host, $level )
249 if ( !is_numeric($level) ) return false;
253 // Try to add the new key to authorizations first. If this
254 // fails, there will be the least amount of data to clean up ...
255 if ( ! update_authorization( "key", $key, $level ) ) return false;
257 $query = sprintf("INSERT INTO %s ( host, apikey ) VALUES ( '%s', '%s' )",
258 $config['apikeys_table'],
262 if ( ! sql_dbexec( $config['provision_db'], $query ) ) return false;
266 function remove_apikey( $key )
269 if ( ! verify_apikey( $key, true ) ) return false;
270 if ( ! remove_authorization( $key ) ) return false;
272 $query = sprintf("DELETE FROM %s WHERE apikey = '%s'",
273 $config['apikeys_table'],
275 if ( ! sql_dbexec( $config['provision_db'], $query ) ) return false;
280 function verify_apikey( $key, $skip_hostcheck = false )
284 $query = sprintf("SELECT host FROM %s WHERE apikey = '%s'",
285 $config['apikeys_table'],
287 $row = sql_dbquery_single( $config['provision_db'], $query );
288 if (!$row) return false;
289 $host = $row['host'];
291 if ( $host && ( $skip_hostcheck ) )
294 if ( $host == $_SERVER['REMOTE_ADDR'] ) return true;
299 function list_apikeys ()
302 $query = sprintf("SELECT k.apikey AS apikey, k.host AS host,
303 a.access_level AS access_level
304 FROM %s k INNER JOIN %s a ON k.apikey = a.authid
305 WHERE a.type = 'key'",
306 $config['apikeys_table'],
307 $config['authorizations_table']);
309 $result = sql_dbquery( $config['provision_db'], $query);
310 if ( ! $result ) return $list;
311 while ( $row = @mysql_fetch_assoc
( $result ) )
313 array_push( $list, array(
314 'api_key' => $row['apikey'],
315 'host' => $row['host'],
316 'level' => authlevel_name( $row['access_level'] )
323 function list_users ()
326 $query = sprintf("SELECT authid, access_level
328 WHERE type = 'user'",
329 $config['authorizations_table']);
331 $result = sql_dbquery( $config['provision_db'], $query);
332 if ( ! $result ) return $list;
333 while ( $row = @mysql_fetch_assoc
( $result ) )
335 $username = $row['authid'];
336 $user_data = authuser_getinfo( $username );
338 // TODO: Remove invalid users here?
339 if ( ! $user_data ) continue;
341 array_push( $list, array(
343 'name' => $user_data['name'],
344 'email' => $user_data['email'],
345 'level' => authlevel_name( $row['access_level'] )
354 function update_authorization( $type, $authid, $level )
357 if ( !is_numeric($level) ) return false;
358 if ( ($type != "key") && ($type != "user") ) return false;
360 $query = sprintf("INSERT INTO %s ( authid, type, access_level ) VALUES ( '%s', '%s', %d )
361 ON DUPLICATE KEY UPDATE access_level=%d",
362 $config['authorizations_table'],
366 if ( ! sql_dbexec( $config['provision_db'], $query ) ) return false;
370 function remove_authorization( $authid )
373 $query = sprintf("DELETE FROM %s WHERE authid = '%s'",
374 $config['authorizations_table'],
375 sql_clean($authid) );
376 //print $query . "\n\n";
377 if ( ! sql_dbexec( $config['provision_db'], $query ) ) return false;
382 function get_authorization( $type, $authid )
386 // If API-key is used, but key fails verification, write is impossible.
387 if ( ( $type == "key" ) && ( ! verify_apikey( $authid, true ) ) )
390 // If User-login is used, but backend is unable to provide info, fail.
391 if ( ( $type == "user" ) && ( ! authuser_getinfo( $authid ) ) )
394 // The only types of access control supported are "user" or "key".
395 if ( ($type != "user" ) && ($type != "key") )
398 $query = sprintf("SELECT access_level FROM %s WHERE authid = '%s'",
399 $config['authorizations_table'],
400 sql_clean($authid) );
401 $row = sql_dbquery_single( $config['provision_db'], $query );
402 if (!$row) return false;
403 $level = $row['access_level'];
407 function can_write ( )
409 // Stub, to be called on any API nodes that write data in the DB.
410 $authid = $_SESSION['authid'];
411 $type = $_SESSION['type'];
413 $level = get_authorization( $type, $authid );
414 if ( $level >= authlevel_value('read_write') ) return $level;