Token.pm 10 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::Config;
33
use Bugzilla::Error;
34
use Bugzilla::Mailer;
35
use Bugzilla::Util;
36

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

40 41
# This module requires that its caller have said "require globals.pl" to import
# relevant functions from that script.
42

43 44 45 46 47 48 49
################################################################################
# Constants
################################################################################

# The maximum number of days a token will remain valid.
my $maxtokenage = 3;

50
################################################################################
51
# Public Functions
52 53
################################################################################

54 55 56
sub IssueEmailChangeToken {
    my ($userid, $old_email, $new_email) = @_;

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

59
    my $newtoken = _create_token($userid, 'emailnew', $old_email . ":" . $new_email);
60 61 62

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

63 64
    my $template = Bugzilla->template;
    my $vars = {};
65

66 67
    $vars->{'oldemailaddress'} = $old_email . Param('emailsuffix');
    $vars->{'newemailaddress'} = $new_email . Param('emailsuffix');
68 69 70
    
    $vars->{'max_token_age'} = $maxtokenage;
    $vars->{'token_ts'} = $token_ts;
71

72
    $vars->{'token'} = $token;
73
    $vars->{'emailaddress'} = $old_email . Param('emailsuffix');
74 75

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

79
    MessageToMTA($message);
80

81
    $vars->{'token'} = $newtoken;
82
    $vars->{'emailaddress'} = $new_email . Param('emailsuffix');
83 84

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

88
    MessageToMTA($message);
89 90
}

91 92
# 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.
93
sub IssuePasswordToken {
94
    my $loginname = shift;
95
    my $dbh = Bugzilla->dbh;
96 97
    my $template = Bugzilla->template;
    my $vars = {};
98

99
    # Retrieve the user's ID from the database.
100 101 102 103 104 105 106 107 108 109 110 111 112
    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));

    ThrowUserError('too_soon_for_new_token') if $too_soon;
113

114
    my ($token, $token_ts) = _create_token($userid, 'password', $::ENV{'REMOTE_ADDR'});
115 116

    # Mail the user the token along with instructions for using it.
117
    $vars->{'token'} = $token;
118
    $vars->{'emailaddress'} = $loginname . Param('emailsuffix');
119

120 121 122
    $vars->{'max_token_age'} = $maxtokenage;
    $vars->{'token_ts'} = $token_ts;

123
    my $message = "";
124 125
    $template->process("account/password/forgotten-password.txt.tmpl", 
                                                               $vars, \$message)
126
      || ThrowTemplateError($template->error());
127

128
    MessageToMTA($message);
129 130
}

131 132 133 134 135 136 137
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);
}
138

139
sub CleanTokenTable {
140 141
    my $dbh = Bugzilla->dbh;
    $dbh->bz_lock_tables('tokens WRITE');
142 143 144 145
    $dbh->do('DELETE FROM tokens
              WHERE ' . $dbh->sql_to_days('NOW()') . ' - ' .
                        $dbh->sql_to_days('issuedate') . ' >= ?',
              undef, $maxtokenage);
146
    $dbh->bz_unlock_tables();
147 148
}

149
sub GenerateUniqueToken {
150
    # Generates a unique random token.  Uses generate_random_password 
151 152 153
    # 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.
154
    my ($table, $column) = @_;
155

156 157 158
    my $token;
    my $duplicate = 1;
    my $tries = 0;
159 160
    $table ||= "tokens";
    $column ||= "token";
161

162
    my $dbh = Bugzilla->dbh;
163
    my $sth = $dbh->prepare("SELECT userid FROM $table WHERE $column = ?");
164 165

    while ($duplicate) {
166 167
        ++$tries;
        if ($tries > 100) {
168
            ThrowCodeError("token_generation_error");
169
        }
170
        $token = generate_random_password();
171 172
        $sth->execute($token);
        $duplicate = $sth->fetchrow_array;
173 174 175 176
    }
    return $token;
}

177 178 179
# 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.
180
sub Cancel {
181
    my ($token, $cancelaction, $vars) = @_;
182
    my $dbh = Bugzilla->dbh;
183
    $vars ||= {};
184

185
    # Get information about the token being cancelled.
186 187 188
    trick_taint($token);
    my ($issuedate, $tokentype, $eventdata, $loginname, $realname) =
        $dbh->selectrow_array('SELECT ' . $dbh->sql_date_format('issuedate') . ',
189
                                      tokentype, eventdata, login_name, realname
190 191 192 193 194
                                 FROM tokens
                           INNER JOIN profiles
                                   ON tokens.userid = profiles.userid
                                WHERE token = ?',
                                undef, $token);
195 196

    # Get the email address of the Bugzilla maintainer.
197
    my $maintainer = Param('maintainer');
198

199
    my $template = Bugzilla->template;
200

201
    $vars->{'emailaddress'} = $loginname . Param('emailsuffix');
202 203
    $vars->{'maintainer'} = $maintainer;
    $vars->{'remoteaddress'} = $::ENV{'REMOTE_ADDR'};
204
    $vars->{'token'} = $token;
205 206 207 208
    $vars->{'tokentype'} = $tokentype;
    $vars->{'issuedate'} = $issuedate;
    $vars->{'eventdata'} = $eventdata;
    $vars->{'cancelaction'} = $cancelaction;
209

210
    # Notify the user via email about the cancellation.
211

212
    my $message;
213
    $template->process("account/cancel-token.txt.tmpl", $vars, \$message)
214
      || ThrowTemplateError($template->error());
215

216
    MessageToMTA($message);
217 218

    # Delete the token from the database.
219
    DeleteToken($token);
220 221
}

222 223 224
sub DeletePasswordTokens {
    my ($userid, $reason) = @_;
    my $dbh = Bugzilla->dbh;
225 226 227 228 229 230 231

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

    foreach my $token (@$tokens) {
232
        Bugzilla::Token::Cancel($token, $reason);
233
    }
234 235
}

236
# Returns an email change token if the user has one. 
237
sub HasEmailChangeToken {
238
    my $userid = shift;
239
    my $dbh = Bugzilla->dbh;
240 241 242 243 244 245

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

249
# Returns the userid, issuedate and eventdata for the specified token
250
sub GetTokenData {
251
    my ($token) = @_;
252 253
    my $dbh = Bugzilla->dbh;

254 255
    return unless defined $token;
    trick_taint($token);
256

257 258 259 260 261 262
    return $dbh->selectrow_array(
        "SELECT userid, " . $dbh->sql_date_format('issuedate') . ", eventdata 
         FROM   tokens 
         WHERE  token = ?", undef, $token);
}

263
# Deletes specified token
264
sub DeleteToken {
265
    my ($token) = @_;
266 267
    my $dbh = Bugzilla->dbh;

268 269 270 271 272 273 274 275 276 277 278 279
    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
################################################################################

280 281
# Generates a unique token and inserts it into the database
# Returns the token and the token timestamp
282
sub _create_token {
283
    my ($userid, $tokentype, $eventdata) = @_;
284
    my $dbh = Bugzilla->dbh;
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306

    detaint_natural($userid);
    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;
    }
}
307

308
1;