Auth.pm 9.8 KB

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