Token.pm 11.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s):    Myk Melez <myk@mozilla.org>

################################################################################
# Module Initialization
################################################################################

# Make it harder for us to do dangerous things in Perl.
use strict;

29
# Bundle the functions in this file together into the "Bugzilla::Token" package.
30
package Bugzilla::Token;
31

32
use Bugzilla::Constants;
33
use Bugzilla::Error;
34
use Bugzilla::Mailer;
35
use Bugzilla::Util;
36

37
use Date::Format;
38
use Date::Parse;
39 40

################################################################################
41
# Public Functions
42 43
################################################################################

44 45 46 47 48 49 50
# Creates and sends a token to create a new user account.
# It assumes that the login has the correct format and is not already in use.
sub issue_new_user_account_token {
    my $login_name = shift;
    my $dbh = Bugzilla->dbh;
    my $template = Bugzilla->template;
    my $vars = {};
51

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
    # Is there already a pending request for this login name? If yes, do not throw
    # an error because the user may have lost his email with the token inside.
    # But to prevent using this way to mailbomb an email address, make sure
    # the last request is at least 10 minutes old before sending a new email.
    trick_taint($login_name);

    my $pending_requests =
        $dbh->selectrow_array('SELECT COUNT(*)
                                 FROM tokens
                                WHERE tokentype = ?
                                  AND ' . $dbh->sql_istrcmp('eventdata', '?') . '
                                  AND issuedate > NOW() - ' . $dbh->sql_interval(10, 'MINUTE'),
                               undef, ('account', $login_name));

    ThrowUserError('too_soon_for_new_token', {'type' => 'account'}) if $pending_requests;

    my ($token, $token_ts) = _create_token(undef, 'account', $login_name);

    $vars->{'email'} = $login_name . Bugzilla->params->{'emailsuffix'};
    $vars->{'token_ts'} = $token_ts;
    $vars->{'token'} = $token;

    my $message;
    $template->process('account/email/request-new.txt.tmpl', $vars, \$message)
      || ThrowTemplateError($template->error());

    MessageToMTA($message);
}
80

81 82
sub IssueEmailChangeToken {
    my ($userid, $old_email, $new_email) = @_;
83
    my $email_suffix = Bugzilla->params->{'emailsuffix'};
84

85
    my ($token, $token_ts) = _create_token($userid, 'emailold', $old_email . ":" . $new_email);
86

87
    my $newtoken = _create_token($userid, 'emailnew', $old_email . ":" . $new_email);
88 89 90

    # Mail the user the token along with instructions for using it.

91 92
    my $template = Bugzilla->template;
    my $vars = {};
93

94 95
    $vars->{'oldemailaddress'} = $old_email . $email_suffix;
    $vars->{'newemailaddress'} = $new_email . $email_suffix;
96
    
97
    $vars->{'max_token_age'} = MAX_TOKEN_AGE;
98
    $vars->{'token_ts'} = $token_ts;
99

100
    $vars->{'token'} = $token;
101
    $vars->{'emailaddress'} = $old_email . $email_suffix;
102 103

    my $message;
104
    $template->process("account/email/change-old.txt.tmpl", $vars, \$message)
105
      || ThrowTemplateError($template->error());
106

107
    MessageToMTA($message);
108

109
    $vars->{'token'} = $newtoken;
110
    $vars->{'emailaddress'} = $new_email . $email_suffix;
111 112

    $message = "";
113
    $template->process("account/email/change-new.txt.tmpl", $vars, \$message)
114
      || ThrowTemplateError($template->error());
115

116
    MessageToMTA($message);
117 118
}

119 120
# Generates a random token, adds it to the tokens table, and sends it
# to the user with instructions for using it to change their password.
121
sub IssuePasswordToken {
122
    my $loginname = shift;
123
    my $dbh = Bugzilla->dbh;
124 125
    my $template = Bugzilla->template;
    my $vars = {};
126

127
    # Retrieve the user's ID from the database.
128 129 130 131 132 133 134 135 136 137 138 139
    trick_taint($loginname);
    my ($userid, $too_soon) =
        $dbh->selectrow_array('SELECT profiles.userid, tokens.issuedate
                                 FROM profiles
                            LEFT JOIN tokens
                                   ON tokens.userid = profiles.userid
                                  AND tokens.tokentype = ?
                                  AND tokens.issuedate > NOW() - ' .
                                      $dbh->sql_interval(10, 'MINUTE') . '
                                WHERE ' . $dbh->sql_istrcmp('login_name', '?'),
                                undef, ('password', $loginname));

140
    ThrowUserError('too_soon_for_new_token', {'type' => 'password'}) if $too_soon;
141

142
    my ($token, $token_ts) = _create_token($userid, 'password', $::ENV{'REMOTE_ADDR'});
143 144

    # Mail the user the token along with instructions for using it.
145
    $vars->{'token'} = $token;
146
    $vars->{'emailaddress'} = $loginname . Bugzilla->params->{'emailsuffix'};
147

148
    $vars->{'max_token_age'} = MAX_TOKEN_AGE;
149 150
    $vars->{'token_ts'} = $token_ts;

151
    my $message = "";
152 153
    $template->process("account/password/forgotten-password.txt.tmpl", 
                                                               $vars, \$message)
154
      || ThrowTemplateError($template->error());
155

156
    MessageToMTA($message);
157 158
}

159 160 161 162 163 164 165
sub IssueSessionToken {
    # Generates a random token, adds it to the tokens table, and returns
    # the token to the caller.

    my $data = shift;
    return _create_token(Bugzilla->user->id, 'session', $data);
}
166

167
sub CleanTokenTable {
168 169
    my $dbh = Bugzilla->dbh;
    $dbh->bz_lock_tables('tokens WRITE');
170 171 172
    $dbh->do('DELETE FROM tokens
              WHERE ' . $dbh->sql_to_days('NOW()') . ' - ' .
                        $dbh->sql_to_days('issuedate') . ' >= ?',
173
              undef, MAX_TOKEN_AGE);
174
    $dbh->bz_unlock_tables();
175 176
}

177
sub GenerateUniqueToken {
178
    # Generates a unique random token.  Uses generate_random_password 
179 180 181
    # for the tokens themselves and checks uniqueness by searching for
    # the token in the "tokens" table.  Gives up if it can't come up
    # with a token after about one hundred tries.
182
    my ($table, $column) = @_;
183

184 185 186
    my $token;
    my $duplicate = 1;
    my $tries = 0;
187 188
    $table ||= "tokens";
    $column ||= "token";
189

190
    my $dbh = Bugzilla->dbh;
191
    my $sth = $dbh->prepare("SELECT userid FROM $table WHERE $column = ?");
192 193

    while ($duplicate) {
194 195
        ++$tries;
        if ($tries > 100) {
196
            ThrowCodeError("token_generation_error");
197
        }
198
        $token = generate_random_password();
199 200
        $sth->execute($token);
        $duplicate = $sth->fetchrow_array;
201 202 203 204
    }
    return $token;
}

205 206 207
# Cancels a previously issued token and notifies the system administrator.
# This should only happen when the user accidentally makes a token request
# or when a malicious hacker makes a token request on behalf of a user.
208
sub Cancel {
209
    my ($token, $cancelaction, $vars) = @_;
210
    my $dbh = Bugzilla->dbh;
211
    my $template = Bugzilla->template;
212
    $vars ||= {};
213

214
    # Get information about the token being cancelled.
215
    trick_taint($token);
216
    my ($issuedate, $tokentype, $eventdata, $loginname) =
217
        $dbh->selectrow_array('SELECT ' . $dbh->sql_date_format('issuedate') . ',
218
                                      tokentype, eventdata, login_name
219
                                 FROM tokens
220
                            LEFT JOIN profiles
221 222 223
                                   ON tokens.userid = profiles.userid
                                WHERE token = ?',
                                undef, $token);
224

225 226 227
    # If we are cancelling the creation of a new user account, then there
    # is no entry in the 'profiles' table.
    $loginname ||= $eventdata;
228
    $vars->{'emailaddress'} = $loginname . Bugzilla->params->{'emailsuffix'};
229
    $vars->{'maintainer'} = Bugzilla->params->{'maintainer'};
230
    $vars->{'remoteaddress'} = $::ENV{'REMOTE_ADDR'};
231
    $vars->{'token'} = $token;
232 233 234 235
    $vars->{'tokentype'} = $tokentype;
    $vars->{'issuedate'} = $issuedate;
    $vars->{'eventdata'} = $eventdata;
    $vars->{'cancelaction'} = $cancelaction;
236

237
    # Notify the user via email about the cancellation.
238

239
    my $message;
240
    $template->process("account/cancel-token.txt.tmpl", $vars, \$message)
241
      || ThrowTemplateError($template->error());
242

243
    MessageToMTA($message);
244 245

    # Delete the token from the database.
246
    DeleteToken($token);
247 248
}

249 250 251
sub DeletePasswordTokens {
    my ($userid, $reason) = @_;
    my $dbh = Bugzilla->dbh;
252 253 254 255 256 257 258

    detaint_natural($userid);
    my $tokens = $dbh->selectcol_arrayref('SELECT token FROM tokens
                                           WHERE userid = ? AND tokentype = ?',
                                           undef, ($userid, 'password'));

    foreach my $token (@$tokens) {
259
        Bugzilla::Token::Cancel($token, $reason);
260
    }
261 262
}

263
# Returns an email change token if the user has one. 
264
sub HasEmailChangeToken {
265
    my $userid = shift;
266
    my $dbh = Bugzilla->dbh;
267 268 269 270 271 272

    my $token = $dbh->selectrow_array('SELECT token FROM tokens
                                       WHERE userid = ?
                                       AND (tokentype = ? OR tokentype = ?) ' .
                                       $dbh->sql_limit(1),
                                       undef, ($userid, 'emailnew', 'emailold'));
273 274 275
    return $token;
}

276
# Returns the userid, issuedate and eventdata for the specified token
277
sub GetTokenData {
278
    my ($token) = @_;
279 280
    my $dbh = Bugzilla->dbh;

281 282
    return unless defined $token;
    trick_taint($token);
283

284 285 286 287 288 289
    return $dbh->selectrow_array(
        "SELECT userid, " . $dbh->sql_date_format('issuedate') . ", eventdata 
         FROM   tokens 
         WHERE  token = ?", undef, $token);
}

290
# Deletes specified token
291
sub DeleteToken {
292
    my ($token) = @_;
293 294
    my $dbh = Bugzilla->dbh;

295 296 297 298 299 300 301 302 303 304 305 306
    return unless defined $token;
    trick_taint($token);

    $dbh->bz_lock_tables('tokens WRITE');
    $dbh->do("DELETE FROM tokens WHERE token = ?", undef, $token);
    $dbh->bz_unlock_tables();
}

################################################################################
# Internal Functions
################################################################################

307 308
# Generates a unique token and inserts it into the database
# Returns the token and the token timestamp
309
sub _create_token {
310
    my ($userid, $tokentype, $eventdata) = @_;
311
    my $dbh = Bugzilla->dbh;
312

313
    detaint_natural($userid) if defined $userid;
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
    trick_taint($tokentype);
    trick_taint($eventdata);

    $dbh->bz_lock_tables('tokens WRITE');

    my $token = GenerateUniqueToken();

    $dbh->do("INSERT INTO tokens (userid, issuedate, token, tokentype, eventdata)
        VALUES (?, NOW(), ?, ?, ?)", undef, ($userid, $token, $tokentype, $eventdata));

    $dbh->bz_unlock_tables();

    if (wantarray) {
        my (undef, $token_ts, undef) = GetTokenData($token);
        $token_ts = str2time($token_ts);
        return ($token, $token_ts);
    } else {
        return $token;
    }
}
334

335
1;