Auth.pm 7.6 KB

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