Auth.pm 9.5 KB

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