Auth.pm 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. package Trog::Auth;
  2. use strict;
  3. use warnings;
  4. no warnings 'experimental';
  5. use feature qw{signatures state};
  6. use Trog::Log qw{:all};
  7. use UUID::Tiny ':std';
  8. use Digest::SHA 'sha256';
  9. use Authen::TOTP;
  10. use Imager::QRCode;
  11. use Trog::SQLite;
  12. =head1 Trog::Auth
  13. An SQLite3 authdb.
  14. =head1 Termination Conditions
  15. Throws exceptions in the event the session database cannot be accessed.
  16. =head1 FUNCTIONS
  17. =head2 session2user(STRING sessid) = STRING
  18. Translate a session UUID into a username.
  19. Returns empty string on no active session.
  20. =cut
  21. sub session2user ($sessid) {
  22. my $dbh = _dbh();
  23. my $rows = $dbh->selectall_arrayref( "SELECT name FROM sess_user WHERE session=?", { Slice => {} }, $sessid );
  24. return '' unless ref $rows eq 'ARRAY' && @$rows;
  25. return $rows->[0]->{name};
  26. }
  27. =head2 acls4user(STRING username) = ARRAYREF
  28. Return the list of ACLs belonging to the user.
  29. The function of ACLs are to allow you to access content tagged 'private' which are also tagged with the ACL name.
  30. The 'admin' ACL is the only special one, as it allows for authoring posts, configuring tCMS, adding series (ACLs) and more.
  31. =cut
  32. sub acls4user ($username) {
  33. my $dbh = _dbh();
  34. my $records = $dbh->selectall_arrayref( "SELECT acl FROM user_acl WHERE username = ?", { Slice => {} }, $username );
  35. return () unless ref $records eq 'ARRAY' && @$records;
  36. my @acls = map { $_->{acl} } @$records;
  37. return \@acls;
  38. }
  39. =head2 totp(user, domain)
  40. Enable TOTP 2fa for the specified user, or if already enabled return the existing info.
  41. Returns a QR code and URI for pasting into authenticator apps.
  42. =cut
  43. sub totp ( $user, $domain ) {
  44. my $totp = _totp();
  45. my $dbh = _dbh();
  46. my $failure = 0;
  47. my $message = "TOTP Secret generated successfully.";
  48. # Make sure we re-generate the same one in case the user forgot.
  49. my $secret;
  50. my $worked = $dbh->selectall_arrayref( "SELECT totp_secret FROM user WHERE name = ?", { Slice => {} }, $user );
  51. if ( ref $worked eq 'ARRAY' && @$worked ) {
  52. $secret = $worked->[0]{totp_secret};
  53. }
  54. $failure = -1 if $secret;
  55. my $uri = $totp->generate_otp(
  56. user => "$user\@$domain",
  57. issuer => $domain,
  58. #XXX verifier apps will only do 30s :(
  59. period => 30,
  60. digits => 6,
  61. $secret ? ( secret => $secret ) : (),
  62. );
  63. if ( !$secret ) {
  64. $secret = $totp->secret();
  65. $dbh->do( "UPDATE user SET totp_secret=? WHERE name=?", undef, $secret, $user ) or return ( undef, undef, 1, "Failed to store TOTP secret." );
  66. }
  67. # This is subsequently served via authenticated _serve() in TCMS.pm
  68. my $qr = "$user\@$domain.bmp";
  69. if ( !-f "totp/$qr" ) {
  70. my $qrcode = Imager::QRCode->new(
  71. size => 4,
  72. margin => 3,
  73. level => 'L',
  74. casesensitive => 1,
  75. lightcolor => Imager::Color->new( 255, 255, 255 ),
  76. darkcolor => Imager::Color->new( 0, 0, 0 ),
  77. );
  78. my $img = $qrcode->plot($uri);
  79. $img->write( file => "totp/$qr", type => "bmp" ) or return ( undef, undef, 1, "Could not write totp/$qr: " . $img->errstr );
  80. }
  81. return ( $uri, $qr, $failure, $message );
  82. }
  83. sub _totp {
  84. state $totp;
  85. if ( !$totp ) {
  86. my $cfg = Trog::Config->get();
  87. my $global_secret = $cfg->param('totp.secret');
  88. die "Global secret must be set in tCMS configuration totp section!" unless $global_secret;
  89. $totp = Authen::TOTP->new( secret => $global_secret );
  90. die "Cannot instantiate TOTP client!" unless $totp;
  91. $totp->{DEBUG} = 1 if is_debug();
  92. }
  93. return $totp;
  94. }
  95. =head2 expected_totp_code(totp, secret, when, digits)
  96. Return the expected totp code at a given time with a given secret.
  97. =cut
  98. #XXX authen::totp does not expose this, sigh
  99. sub expected_totp_code {
  100. my ( $self, $secret, $when, $digits ) = @_;
  101. $self //= _totp();
  102. $when //= time;
  103. my $period = 30;
  104. $digits //= 6;
  105. $self->{secret} = $secret;
  106. my $T = sprintf( "%016x", int( $when / $period ) );
  107. my $Td = pack( 'H*', $T );
  108. my $hmac = $self->hmac($Td);
  109. # take the 4 least significant bits (1 hex char) from the encrypted string as an offset
  110. my $offset = hex( substr( $hmac, -1 ) );
  111. # take the 4 bytes (8 hex chars) at the offset (* 2 for hex), and drop the high bit
  112. my $encrypted = hex( substr( $hmac, $offset * 2, 8 ) ) & 0x7fffffff;
  113. return sprintf( "%0" . $digits . "d", ( $encrypted % ( 10**$digits ) ) );
  114. }
  115. =head2 clear_totp
  116. Clear the totp codes for all users
  117. =cut
  118. sub clear_totp {
  119. my $dbh = _dbh();
  120. $dbh->do("UPDATE user SET totp_secret=null") or die "Could not clear user TOTP secrets";
  121. #TODO notify users this has happened
  122. }
  123. =head2 mksession(user, pass, token) = STRING
  124. Create a session for the user and waste all other sessions.
  125. Returns a session ID, or blank string in the event the user does not exist or incorrect auth was passed.
  126. =cut
  127. sub mksession ( $user, $pass, $token ) {
  128. my $dbh = _dbh();
  129. my $totp = _totp();
  130. # Check the password
  131. my $records = $dbh->selectall_arrayref( "SELECT salt FROM user WHERE name = ?", { Slice => {} }, $user );
  132. return '' unless ref $records eq 'ARRAY' && @$records;
  133. my $salt = $records->[0]->{salt};
  134. my $hash = sha256( $pass . $salt );
  135. my $worked = $dbh->selectall_arrayref( "SELECT name, totp_secret FROM user WHERE hash=? AND name = ?", { Slice => {} }, $hash, $user );
  136. return '' unless ref $worked eq 'ARRAY' && @$worked;
  137. my $uid = $worked->[0]{name};
  138. my $secret = $worked->[0]{totp_secret};
  139. # Validate the 2FA Token. If we have no secret, allow login so they can see their QR code, and subsequently re-auth.
  140. if ($secret) {
  141. return '' unless $token;
  142. DEBUG("TOTP Auth: Sent code $token, expect ".expected_totp_code());
  143. my $rc = $totp->validate_otp( otp => $token, secret => $secret, tolerance => 5, period => 30, digits => 6 );
  144. return '' unless $rc;
  145. }
  146. # Issue cookie
  147. my $uuid = create_uuid_as_string( UUID_V1, UUID_NS_DNS );
  148. $dbh->do( "INSERT OR REPLACE INTO session (id,username) VALUES (?,?)", undef, $uuid, $uid ) or return '';
  149. return $uuid;
  150. }
  151. =head2 killsession(user) = BOOL
  152. Delete the provided user's session from the auth db.
  153. =cut
  154. sub killsession ($user) {
  155. my $dbh = _dbh();
  156. $dbh->do( "DELETE FROM session WHERE username=?", undef, $user );
  157. return 1;
  158. }
  159. =head2 useradd(user, pass) = BOOL
  160. Adds a user identified by the provided password into the auth DB.
  161. Returns True or False (likely false when user already exists).
  162. =cut
  163. sub useradd ( $user, $pass, $acls ) {
  164. my $dbh = _dbh();
  165. my $salt = create_uuid();
  166. my $hash = sha256( $pass . $salt );
  167. my $res = $dbh->do( "INSERT OR REPLACE INTO user (name,salt,hash) VALUES (?,?,?)", undef, $user, $salt, $hash );
  168. return unless $res && ref $acls eq 'ARRAY';
  169. #XXX this is clearly not normalized with an ACL mapping table, will be an issue with large number of users
  170. foreach my $acl (@$acls) {
  171. return unless $dbh->do( "INSERT OR REPLACE INTO user_acl (username,acl) VALUES (?,?)", undef, $user, $acl );
  172. }
  173. return 1;
  174. }
  175. # Ensure the db schema is OK, and give us a handle
  176. sub _dbh {
  177. my $file = 'schema/auth.schema';
  178. my $dbname = "config/auth.db";
  179. return Trog::SQLite::dbh( $file, $dbname );
  180. }
  181. 1;