summaryrefslogtreecommitdiff
path: root/LedgerSMB/Auth/DB.pm
blob: 9afc8675847eb02e36905493c839cb20f7b6eca8 (plain)
  1. #=====================================================================
  2. # LedgerSMB
  3. # Small Medium Business Accounting software
  4. # http://www.ledgersmb.org/
  5. #
  6. #
  7. # Copyright (C) 2006
  8. # This work contains copyrighted information from a number of sources all used
  9. # with permission. It is released under the GNU General Public License
  10. # Version 2 or, at your option, any later version. See COPYRIGHT file for
  11. # details.
  12. #
  13. #
  14. #======================================================================
  15. #
  16. # This file has undergone whitespace cleanup.
  17. #
  18. #======================================================================
  19. # This package contains session related functions:
  20. #
  21. # check - checks validity of session based on the user's cookie and login
  22. #
  23. # create - creates a new session, writes cookie upon success
  24. #
  25. # destroy - destroys session
  26. #
  27. # password_check - compares the password with the stored cryted password
  28. # (ver. < 1.2) and the md5 one (ver. >= 1.2)
  29. #====================================================================
  30. package LedgerSMB::Auth;
  31. use MIME::Base64;
  32. use LedgerSMB::Sysconfig;
  33. use strict;
  34. sub session_check {
  35. use Time::HiRes qw(gettimeofday);
  36. my ( $cookie, $form ) = @_;
  37. my $path = ($ENV{SCRIPT_NAME});
  38. $path =~ s|[^/]*$||;
  39. if ($cookie eq 'Login'){
  40. return session_create($form);
  41. }
  42. my $timeout;
  43. my $dbh = $form->{dbh};
  44. my $checkQuery = $dbh->prepare(
  45. "SELECT * FROM session_check(?, ?)");
  46. my ($sessionID, $token, $company) = split(/:/, $cookie);
  47. $form->{company} ||= $company;
  48. #must be an integer
  49. $sessionID =~ s/[^0-9]//g;
  50. $sessionID = int $sessionID;
  51. if ( !$form->{timeout} ) {
  52. $timeout = "1 day";
  53. }
  54. else {
  55. $timeout = "$form->{timeout} seconds";
  56. }
  57. $checkQuery->execute( $sessionID, $token)
  58. || $form->dberror(
  59. __FILE__ . ':' . __LINE__ . ': Looking for session: ' );
  60. my $sessionValid = $checkQuery->rows;
  61. if ($sessionValid) {
  62. #user has a valid session cookie, now check the user
  63. my ( $session_ref) = $checkQuery->fetchrow_hashref('NAME_lc');
  64. my $login = $form->{login};
  65. $login =~ s/[^a-zA-Z0-9._+\@'-]//g;
  66. if (( $session_ref ))
  67. {
  68. my $newCookieValue =
  69. $session_ref->{session_id} . ':' . $session_ref->{token} . ':' . $form->{company};
  70. #now update the cookie in the browser
  71. print qq|Set-Cookie: ${LedgerSMB::Sysconfig::cookie_name}=$newCookieValue; path=$path;\n|;
  72. return 1;
  73. }
  74. else {
  75. #something's wrong, they have the cookie, but wrong user or the wrong transaction id. Hijack attempt?
  76. #destroy the session
  77. my $sessionDestroy = $dbh->prepare("");
  78. #delete the cookie in the browser
  79. print qq|Set-Cookie: ${LedgerSMB::Sysconfig::cookie_name}=; path=$path;\n|;
  80. return 0;
  81. }
  82. }
  83. else {
  84. #cookie is not valid
  85. #delete the cookie in the browser
  86. print qq|Set-Cookie: ${LedgerSMB::Sysconfig::cookie_name}=; path=$path;\n|;
  87. return 0;
  88. }
  89. }
  90. sub session_create {
  91. my ($lsmb) = @_;
  92. my $path = ($ENV{SCRIPT_NAME});
  93. $path =~ s|[^/]*$||;
  94. use Time::HiRes qw(gettimeofday);
  95. my $dbh = $lsmb->{dbh};
  96. my $login = $lsmb->{login};
  97. #microseconds are more than random enough for transaction_id
  98. my ( $ignore, $newTransactionID ) = gettimeofday();
  99. $newTransactionID = int $newTransactionID;
  100. if ( !$ENV{GATEWAY_INTERFACE} ) {
  101. #don't create cookies or sessions for CLI use
  102. return 1;
  103. }
  104. # TODO Change this to use %myconfig
  105. my $deleteExisting = $dbh->prepare(
  106. "DELETE
  107. FROM session
  108. WHERE session.users_id = (select id from users where username = ?)"
  109. );
  110. my $seedRandom = $dbh->prepare("SELECT setseed(?);");
  111. my $fetchSequence =
  112. $dbh->prepare("SELECT nextval('session_session_id_seq'), md5(random()::text);");
  113. my $createNew = $dbh->prepare(
  114. "INSERT INTO session (session_id, users_id, token, transaction_id)
  115. VALUES(?, (SELECT id
  116. FROM users
  117. WHERE username = SESSION_USER), ?, ?);"
  118. );
  119. # this is assuming that the login is safe, which might be a bad assumption
  120. # so, I'm going to remove some chars, which might make previously valid
  121. # logins invalid --CM
  122. # I am changing this to use HTTP Basic Auth credentials for now. -- CT
  123. my $auth = $ENV{HTTP_AUTHORIZATION};
  124. $auth =~ s/^Basic //i;
  125. #delete any existing stale sessions with this login if they exist
  126. if ( !$lsmb->{timeout} ) {
  127. $lsmb->{timeout} = 86400;
  128. }
  129. $deleteExisting->execute( $login)
  130. || $lsmb->dberror(
  131. __FILE__ . ':' . __LINE__ . ': Delete from session: ' . $DBI::errstr);
  132. #doing the random stuff in the db so that LedgerSMB won't
  133. #require a good random generator - maybe this should be reviewed,
  134. #pgsql's isn't great either -CM
  135. #
  136. #I think we should be OK. The random number generator is only a small part
  137. #of the credentials in 1.3.x, and for people that need greater security, there
  138. #is always Kerberos.... -- CT
  139. $fetchSequence->execute()
  140. || $lsmb->dberror( __FILE__ . ':' . __LINE__ . ': Fetch sequence id: ' );
  141. my ( $newSessionID, $newToken ) = $fetchSequence->fetchrow_array;
  142. #create a new session
  143. $createNew->execute( $newSessionID, $newToken, $newTransactionID )
  144. || $lsmb->dberror( __FILE__ . ':' . __LINE__ . ": Create new session: \n".
  145. $lsmb->{dbh}->errstr() );
  146. #reseed the random number generator
  147. my $randomSeed = 1.0 * ( '0.' . ( time() ^ ( $$ + ( $$ << 15 ) ) ) );
  148. $seedRandom->execute($randomSeed)
  149. || $lsmb->dberror(
  150. __FILE__ . ':' . __LINE__ . ': Reseed random generator: ' );
  151. my $newCookieValue = $newSessionID . ':' . $newToken . ':'
  152. . $lsmb->{company};
  153. #now set the cookie in the browser
  154. #TODO set domain from ENV, also set path to install path
  155. print qq|Set-Cookie: ${LedgerSMB::Sysconfig::cookie_name}=$newCookieValue; path=$path;\n|;
  156. $lsmb->{LedgerSMB} = $newCookieValue;
  157. $lsmb->{dbh}->commit;
  158. }
  159. sub session_destroy {
  160. my ($form) = @_;
  161. my $login = $form->{login};
  162. $login =~ s/[^a-zA-Z0-9._+\@'-]//g;
  163. # use the central database handle
  164. my $dbh = $form->{dbh};
  165. my $deleteExisting = $dbh->prepare( "
  166. DELETE FROM session
  167. WHERE users_id = (select id from users where username = ?)
  168. " );
  169. $deleteExisting->execute($login)
  170. || $form->dberror(
  171. __FILE__ . ':' . __LINE__ . ': Delete from session: ' );
  172. #delete the cookie in the browser
  173. print qq|Set-Cookie: ${LedgerSMB::Sysconfig::cookie_name}=; path=/;\n|;
  174. }
  175. sub get_credentials {
  176. # Handling of HTTP Basic Auth headers
  177. my $auth = $ENV{'HTTP_AUTHORIZATION'};
  178. $auth =~ s/Basic //i; # strip out basic authentication preface
  179. $auth = MIME::Base64::decode($auth);
  180. my $return_value = {};
  181. ($return_value->{login}, $return_value->{password}) = split(/:/, $auth);
  182. if (defined $LedgerSMB::Sysconfig::force_username_case){
  183. if (lc($LedgerSMB::Sysconfig::force_username_case) eq 'lower'){
  184. $return_value->{login} = lc($return_value->{login});
  185. } elsif (lc($LedgerSMB::Sysconfig::force_username_case) eq 'upper'){
  186. $return_value->{login} = uc($return_value->{login});
  187. }
  188. }
  189. return $return_value;
  190. }
  191. sub credential_prompt{
  192. print "WWW-Authenticate: Basic realm=\"LedgerSMB\"\n";
  193. print "Status: 401 Unauthorized\n\n";
  194. print "Please enter your credentials.\n";
  195. exit;
  196. }
  197. sub password_check {
  198. use Digest::MD5;
  199. my ( $form, $username, $password ) = @_;
  200. $username =~ s/[^a-zA-Z0-9._+\@'-]//g;
  201. # use the central database handle
  202. my $dbh = ${LedgerSMB::Sysconfig::GLOBALDBH};
  203. my $fetchPassword = $dbh->prepare(
  204. "SELECT u.username, uc.password, uc.crypted_password
  205. FROM users as u, users_conf as uc
  206. WHERE u.username = ?
  207. AND u.id = uc.id;"
  208. );
  209. $fetchPassword->execute($username)
  210. || $form->dberror( __FILE__ . ':' . __LINE__ . ': Fetching password : ' );
  211. my ( $dbusername, $md5Password, $cryptPassword ) =
  212. $fetchPassword->fetchrow_array;
  213. if ( $dbusername ne $username ) {
  214. # User data retrieved from db not for the requested user
  215. return 0;
  216. }
  217. elsif ($cryptPassword) {
  218. #First time login from old system, check crypted password
  219. if ( ( crypt $password, substr( $username, 0, 2 ) ) eq $cryptPassword )
  220. {
  221. #password was good, convert to md5 password and null crypted
  222. my $updatePassword = $dbh->prepare(
  223. "UPDATE users_conf
  224. SET password = md5(?),
  225. crypted_password = null
  226. FROM users
  227. WHERE users_conf.id = users.id
  228. AND users.username = ?;"
  229. );
  230. $updatePassword->execute( $password, $username )
  231. || $form->dberror(
  232. __FILE__ . ':' . __LINE__ . ': Converting password : ' );
  233. return 1;
  234. }
  235. else {
  236. return 0; #password failed
  237. }
  238. }
  239. elsif ($md5Password) {
  240. if ( $md5Password ne ( Digest::MD5::md5_hex $password) ) {
  241. return 0;
  242. }
  243. else {
  244. return 1;
  245. }
  246. }
  247. else {
  248. #both the md5Password and cryptPasswords were blank
  249. return 0;
  250. }
  251. }
  252. 1;