Auth.pm 11 KB

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