Auth.pm 12 KB

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