summaryrefslogtreecommitdiff
path: root/LedgerSMB/Session/DB.pm
blob: f7f1e6728bed2819d92fb89f37a0fc4345cd8ba6 (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 Session;
  31. use MIME::Base64;
  32. use strict;
  33. sub session_check {
  34. use Time::HiRes qw(gettimeofday);
  35. my $path = ($ENV{SCRIPT_NAME});
  36. $path =~ s|[^/]*$||;
  37. my ( $cookie, $form ) = @_;
  38. if ($cookie eq 'Login'){
  39. return session_create($form);
  40. }
  41. my $timeout;
  42. my $dbh = $form->{dbh};
  43. my $checkQuery = $dbh->prepare(
  44. "SELECT u.username, s.transaction_id
  45. FROM session as s
  46. JOIN users as u ON (s.users_id = u.id)
  47. WHERE s.session_id = ?
  48. AND token = ?
  49. AND s.last_used > now() - ?::interval"
  50. );
  51. my $updateAge = $dbh->prepare(
  52. "UPDATE session
  53. SET last_used = now()
  54. WHERE session_id = ?;"
  55. );
  56. my ($sessionID, $token, $company) = split(/:/, $cookie);
  57. $form->{company} ||= $company;
  58. #must be an integer
  59. $sessionID =~ s/[^0-9]//g;
  60. $sessionID = int $sessionID;
  61. if ( !$form->{timeout} ) {
  62. $timeout = "1 day";
  63. }
  64. else {
  65. $timeout = "$form->{timeout} seconds";
  66. }
  67. $checkQuery->execute( $sessionID, $token, $timeout )
  68. || $form->dberror(
  69. __FILE__ . ':' . __LINE__ . ': Looking for session: ' );
  70. my $sessionValid = $checkQuery->rows;
  71. if ($sessionValid) {
  72. #user has a valid session cookie, now check the user
  73. my ( $sessionLogin, $sessionTransaction ) = $checkQuery->fetchrow_array;
  74. my $login = $form->{login};
  75. $login =~ s/[^a-zA-Z0-9._+\@'-]//g;
  76. if (( $sessionLogin eq $login ))
  77. {
  78. $updateAge->execute( $sessionID )
  79. || $form->dberror(
  80. __FILE__ . ':' . __LINE__ . ': Updating session age: ' );
  81. my $newCookieValue =
  82. $sessionID . ':' . $token . ':' . $form->{company};
  83. #now update the cookie in the browser
  84. print qq|Set-Cookie: LedgerSMB=$newCookieValue; path=$path;\n|;
  85. return 1;
  86. }
  87. else {
  88. #something's wrong, they have the cookie, but wrong user or the wrong transaction id. Hijack attempt?
  89. #destroy the session
  90. my $sessionDestroy = $dbh->prepare("");
  91. #delete the cookie in the browser
  92. print qq|Set-Cookie: LedgerSMB=; path=$path;\n|;
  93. return 0;
  94. }
  95. }
  96. else {
  97. #cookie is not valid
  98. #delete the cookie in the browser
  99. print qq|Set-Cookie: LedgerSMB=; path=$path;\n|;
  100. return 0;
  101. }
  102. }
  103. sub session_create {
  104. my ($lsmb) = @_;
  105. my $path = ($ENV{SCRIPT_NAME});
  106. $path =~ s|[^/]*$||;
  107. use Time::HiRes qw(gettimeofday);
  108. my $dbh = $lsmb->{dbh};
  109. my $login = $lsmb->{login};
  110. #microseconds are more than random enough for transaction_id
  111. my ( $ignore, $newTransactionID ) = gettimeofday();
  112. $newTransactionID = int $newTransactionID;
  113. if ( !$ENV{GATEWAY_INTERFACE} ) {
  114. #don't create cookies or sessions for CLI use
  115. return 1;
  116. }
  117. # TODO Change this to use %myconfig
  118. my $deleteExisting = $dbh->prepare(
  119. "DELETE
  120. FROM session
  121. WHERE session.users_id = (select id from users where username = ?)"
  122. );
  123. my $seedRandom = $dbh->prepare("SELECT setseed(?);");
  124. my $fetchSequence =
  125. $dbh->prepare("SELECT nextval('session_session_id_seq'), md5(random());");
  126. my $createNew = $dbh->prepare(
  127. "INSERT INTO session (session_id, users_id, token, transaction_id)
  128. VALUES(?, (SELECT id
  129. FROM users
  130. WHERE username = ?), ?, ?);"
  131. );
  132. # this is assuming that the login is safe, which might be a bad assumption
  133. # so, I'm going to remove some chars, which might make previously valid
  134. # logins invalid --CM
  135. # I am changing this to use HTTP Basic Auth credentials for now. -- CT
  136. my $auth = $ENV{HTTP_AUTHORIZATION};
  137. $auth =~ s/^Basic //i;
  138. #delete any existing stale sessions with this login if they exist
  139. if ( !$lsmb->{timeout} ) {
  140. $lsmb->{timeout} = 86400;
  141. }
  142. print STDERR "Breakpoint\n";
  143. $deleteExisting->execute( $login)
  144. || $lsmb->dberror(
  145. __FILE__ . ':' . __LINE__ . ': Delete from session: ' );
  146. #doing the random stuff in the db so that LedgerSMB won't
  147. #require a good random generator - maybe this should be reviewed,
  148. #pgsql's isn't great either -CM
  149. #
  150. #I think we should be OK. The random number generator is only a small part
  151. #of the credentials in 1.3.x, and for people that need greater security, there
  152. #is always Kerberos.... -- CT
  153. $fetchSequence->execute()
  154. || $lsmb->dberror( __FILE__ . ':' . __LINE__ . ': Fetch sequence id: ' );
  155. my ( $newSessionID, $newToken ) = $fetchSequence->fetchrow_array;
  156. #create a new session
  157. $createNew->execute( $newSessionID, $login, $newToken, $newTransactionID )
  158. || $lsmb->dberror( __FILE__ . ':' . __LINE__ . ': Create new session: ' );
  159. #reseed the random number generator
  160. my $randomSeed = 1.0 * ( '0.' . ( time() ^ ( $$ + ( $$ << 15 ) ) ) );
  161. $seedRandom->execute($randomSeed)
  162. || $lsmb->dberror(
  163. __FILE__ . ':' . __LINE__ . ': Reseed random generator: ' );
  164. my $newCookieValue = $newSessionID . ':' . $newToken . ':'
  165. . $lsmb->{company};
  166. print STDERR "Breakpoint\n";
  167. #now set the cookie in the browser
  168. #TODO set domain from ENV, also set path to install path
  169. print qq|Set-Cookie: LedgerSMB=$newCookieValue; path=$path;\n|;
  170. $lsmb->{LedgerSMB} = $newCookieValue;
  171. $lsmb->{dbh}->commit;
  172. }
  173. sub session_destroy {
  174. my ($form) = @_;
  175. my $login = $form->{login};
  176. $login =~ s/[^a-zA-Z0-9._+\@'-]//g;
  177. # use the central database handle
  178. my $dbh = ${LedgerSMB::Sysconfig::GLOBALDBH};
  179. my $deleteExisting = $dbh->prepare( "
  180. DELETE FROM session
  181. WHERE users_id = (select id from users where username = ?)
  182. " );
  183. $deleteExisting->execute($login)
  184. || $form->dberror(
  185. __FILE__ . ':' . __LINE__ . ': Delete from session: ' );
  186. #delete the cookie in the browser
  187. print qq|Set-Cookie: LedgerSMB=; path=/;\n|;
  188. }
  189. sub password_check {
  190. use Digest::MD5;
  191. my ( $form, $username, $password ) = @_;
  192. $username =~ s/[^a-zA-Z0-9._+\@'-]//g;
  193. # use the central database handle
  194. my $dbh = ${LedgerSMB::Sysconfig::GLOBALDBH};
  195. my $fetchPassword = $dbh->prepare(
  196. "SELECT u.username, uc.password, uc.crypted_password
  197. FROM users as u, users_conf as uc
  198. WHERE u.username = ?
  199. AND u.id = uc.id;"
  200. );
  201. $fetchPassword->execute($username)
  202. || $form->dberror( __FILE__ . ':' . __LINE__ . ': Fetching password : ' );
  203. my ( $dbusername, $md5Password, $cryptPassword ) =
  204. $fetchPassword->fetchrow_array;
  205. if ( $dbusername ne $username ) {
  206. # User data retrieved from db not for the requested user
  207. return 0;
  208. }
  209. elsif ($cryptPassword) {
  210. #First time login from old system, check crypted password
  211. if ( ( crypt $password, substr( $username, 0, 2 ) ) eq $cryptPassword )
  212. {
  213. #password was good, convert to md5 password and null crypted
  214. my $updatePassword = $dbh->prepare(
  215. "UPDATE users_conf
  216. SET password = md5(?),
  217. crypted_password = null
  218. FROM users
  219. WHERE users_conf.id = users.id
  220. AND users.username = ?;"
  221. );
  222. $updatePassword->execute( $password, $username )
  223. || $form->dberror(
  224. __FILE__ . ':' . __LINE__ . ': Converting password : ' );
  225. return 1;
  226. }
  227. else {
  228. return 0; #password failed
  229. }
  230. }
  231. elsif ($md5Password) {
  232. if ( $md5Password ne ( Digest::MD5::md5_hex $password) ) {
  233. return 0;
  234. }
  235. else {
  236. return 1;
  237. }
  238. }
  239. else {
  240. #both the md5Password and cryptPasswords were blank
  241. return 0;
  242. }
  243. }
  244. 1;