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