view release on metacpan or search on metacpan
1. What Problems are We Trying to Solve?
-----------------------------------------
Problem 1: No Secure Single Sign-On.
There is not as far as we know, an Apache module which will securely transfer
credentials from a login on one trusted host to multiple cooperating hosts,
across multiple DNS domains and across a range of SSL capabilities.
Problem 2: HTTP Cookie Weaknesses.
Not implicit from problem (1), is the subtle fact that considerable
care must be taken to securely share credentials within a single DNS
domain using HTTP state management (aka Netscape Cookies) as described
in [RFC2109] and [RFC2965]. In fact, the traps and pitfalls are so numerous
that [RFC2964] generally forbids the use of cookies for any kind of security
authentication.
One way to look at this package is as a very simple cryptographic
protocol designed to defend against attacks which exploit known cookie
vulnerabilities.
2. Summary of Features
-----------------------
* Secure sharing of multi-level credentials within and across DNS domains.
* Support for different representations of credentials with the ability to
chain and interoperate between them.
* Built-in defense against on-line guessing attacks.
* Built-in session timeout, both idle and hard-limit.
* Built-in SU-type function for admins to switch user ID's.
* Encapsulated database interface.
3. Known Security Issues with HTTP Cookies
-------------------------------------------
Issue 1: The Caching Problem
Even if no passive or active adversary is sitting between the client
and server, an unauthorized user might still see the wrong data because
any web-caching device along the way might cough up a request such
as http://www.acme.com/creditcards.txt without ever referring it to
the server, if a previous authorized user made the same request. This
is a no-no for the web-cache to do, but it happens anyway.
Solution: There is no real solution, and RFC2964 is correct to discourage
plaintext cookie-based authentication even over secure networks (like on an
intranet). On the other hand, this really is a bug (what if web-caches
ignored POST arguments).
Issue 2: Wildcard Cookies Don't Always Go Where Intended
Suppose in a heterogeneous environment with many .acme.com hosts, an
authentication system is setup to share cookies between bruce.acme.com
and wendel.acme.com. Upon successful login, bruce issues an .acme.com
cookie to a user who can then request resources from wendel. Even
if you don't admit either passive or active adversaries on the network, the
user's identity might still be compromised. If hopkins.acme.com is
compromised and the user visits *any* other compromised site, say
www.fantasyland.org, a trojan .html document with a malicious image
tag <img src="http://hopkins.acme.com">, will send the identity cookies
directly to hopkins who is waiting for them. (This is the old 3rd-party
cookie bugaboo exploited by *click.com.)
Solution: Regardless of the mechanism used for representing user
credentials (cookies, URL's, etc), there will be some set of hosts
included in the system (whether spanned by wildcard matches or server
side redirects). No untrusted host should be in that set. This is
just classic host security.
Issue 3: Secure Wildcard Cookies Don't Always Have Intended Protection
The underlying weakness in issue (2) is perhaps more relevant for so-called
secure cookies (with secure flag is set). Even where host security can be
assumed across a large heterogeneous environment, there might be one
host which only supports 40-bit SSL, say hopkins.acme.org again. Supposed
bruce and wendel were properly configured for only 128-bit cipher suites
and issued only secure cookies for the .acme.com domain. Then a malicious
image tag <img src="https://hopkins.acme.com"> will force a connection
to hopkins. If 40-bit encryption is negotiated (see next issue), the user's
credentials are reduced from 128-bits to 40-bits.
Unlike issue (2), we cannot pass this off as a matter of host security,
because hopkins is not compromised. A passive adversary who obtains
a 40-bit encrypted copy of the credentials. He can then do an offline crack
in order to assume the users identity. Naively, bruce and wendel might
think an implausible work factor of 2^128 would be necessary.
Solution: A cookie-based authentication module must be configurable
to treat a wildcard .acme.com domain as essentially weak. Cookies
used for strong authentication must be either confined to a single
host, or to a more restrictive wildcard like '.secure.acme.com'. The
demo software shows examples of both.
Issue 4: SSLv2 Rollback Vulnerability
An active adversary can force an SSL client and server to negotiate the
*weakest* cipher suite which they share in common [SSL]. Recall that the
SSL cipher negotiation was intended to negotiate the *strongest* cipher
suite. Thus under the stronger threat model of an active adversary, we are
far more likely to find a target such as hopkins to exploit in issue (3).
For a variety of reasons (sometimes legal and political), the larger the
DNS domain (in number or geography) the greater the likelihood of there
being one host which supports SSLv2 and 40-bits, or a newer SSL/TLS but
only 40-bits.
Solution: Same as issue (3).
Issue 5: Persistent Cookies are Often Stored in Filesystem
If a cookie is ever set with a future expiration date, browsers will copy
it, in the clear, to the filesystem for use upon next invocation of the
browser. Such filesystems often shared across networks and so are
available to a wide variety of users.
Solution: The fundamental session cookies in secure system should be
ephemeral. This does not preclude the use of persistent cookies as an
initial user identity token if the threat model is appropriate (perhaps
on a single-user laptop).
adversary. This is achieved in a rather mundane way, namely by avoiding
all the pitfalls of the enumerated issues in Sect. 3.
In the case of URL credentials, the current implementation requires all
URL's to be explicitly configured. All redirects are automatic, occurring
under SSL of a specified strength. There should be no surprises here; if
URL credentials were stolen, the adversary would have had to crack one of
a small number of SSL connections under the complete control of the security
administrator.
In the case of Cookie credentials, *multiple* cookies are issued, one for
each anticipated security level. For example, a user who logs in with an
X.509 client certificate might be issued 3 cookies: one cleartext cookie
intended for non-sensitive data, one SSL (secure flag) cookie broadly
distributed to .acme.com with 40-bit crypto possible, and finally one SSL
cookie intended only for the 128-bit originating host. An adversary who
manages to steal either the cleartext or the 40-bit cookie cannot use it to
acquire 128-bit level resources, because the cookies themselves have
unforgeable assertions of security level which are checked during session
authentication as described in the next section.
5.3 Credential Format
----------------------
Credentials in Apache::SecSess have a similar format:
URL Credentials:
realm=E_k(md5(hash),hash)
Cookie Credentials:
realm:qop,authqop=E_k(md5(hash),hash)
(The only difference is that the quality of protection parameters
discussed below, qop and authqop, are repeated in the clear for cookie
credentials in order to ease processing.)
The string 'realm' is any symbol (without obvious special characters
':', '=', etc) which is used to identify cooperating security services,
thus providing a way to put credentials into their own namespace.
if ($t > $ts + 60*$life) { # hard timeout
$uri = $self->timeoutURL;
return {
message => "Expired, redirecting '$uid' to '$uri?type=expire'.",
uri => "$uri?type=expire"
};
}
if ($t > $ts + 60*($idle+$renew)) { # idle timeout
$uri = $self->timeoutURL;
return {
message => "Cookie idle too long '$uid'.",
uri => "$uri?type=idle"
};
}
if ($t > $ts + 60*$renew) { # renew
$uri = $self->renewURL;
$requri = $self->requested_uri($r);
return {
message => "Renewing credentials for user '$uid'.",
renew => 'true',
uri => "$uri?url=$requri"
#
=head1 NAME
Apache::SecSess - Secure Apache session management library
=head1 SYNOPSIS
In startup.pl,
$My::obj = Apache::SecSess::Cookie::X509->new(...)
In httpd.conf,
<Location /protected>
PerlAuthenHandler $My::obj->authen
...
</Location>
See section EXAMPLE below for more details.
methods are specific Apache phase handlers designed to manage a user's
session lifecycle, including: initiating, renewing and terminating the
session. Each of these objects is an instance of some subclass of
Apache::SecSess, which treats a particular security paradigm.
=head1 CLASS HIERARCHY
Below is a diagram of the class hierarchy
SecSess
`+-Cookie
| `+--BasicAuth (for debugging)
| +--LoginForm
| +--X509
| +--X509PIN
| `--URL
`-URL
`---Cookie
SecSess contains (in addition to common code) all Apache phase handlers
(Currently only PerlAuthenHandler are needed). At this level credentials
and status are considered opaque objects. The important methods are:
->authen() Used to protect underlying resources. Checks credentials for freshness and validity.
->issue() Used as the "initial" identity authentication before issuing credentials (cookies or mangled URLs) used by ->authen().
->renew() Will re-issue credentials if proper conditions are satisfied
->delete() Will delete credentials where relevant (i.e. deletes cookies).
At one level beneath SecSess (SecSess::Cookie.pm and SecSess::URL.pm),
are the methods for interpreting and manipulating credentials.
At the lowest level, are subclasses which "know" how to interpret the
*initial* identifying information during the issuance of credentials.
So, *::Cookie::LoginForm presents the client with a user/password
login form for identification. And thus the difference between
*::Cookie::URL and *::URL::Cookie is that the former will issue cookies
after validating an URL credential, and the latter will "issue" an URL
credential (typically it will redirect to a resource with realm=cred in
the URL) after validating a cookie.
=head1 CREDENTIAL FORMAT
Credentials in Apache::SecSess have a similar format:
URL Credentials (defined in Apache::SecSess::URL):
realm=E_k(md5(hash),hash)
Cookie Credentials: (defined in Apache::SecSess::Cookie):
realm:qop,authqop=E_k(md5(hash),hash)
The string 'realm' is any symbol (without obvious special characters
':', '=', etc) which is used to identify cooperating security services,
thus providing a way to put credentials into their own namespace.
The 'hash' is a string representation of a Perl hash of the form:
hash = {uid => str, timestamp => int, qop => int, authqop => int}
See README and Wrapper.pm for further details.
Note that no attempt is made to check the correctness of the QOP
settings against the values of the httpd.conf directive SSLCipherSuite.
This would be mistake in fact because the session strength is dependent
on global factors as described in README. Nevertheless, you should
check your assumptions about your local site's openssl with the script
utils/minstren which prints the weakest cipher strength for common
SSLCipherSuite arguments. At my site, I was surprised to find
ALL:!ADH:!EXP:!EXP56 => 56 bits.
=head2 Cookie Domain Argument
cookieDomain => <hashref>
The cookieDomain argument expects a hash reference of the form:
{ 'qop,authqop' => 'domain_string', ... }
where 'domain_string' is literally the HTTP Set-Cookie domain string, and
where the integers 'qop' and 'authqop' serve to define the session and
authentication qualities of protections as described above. A cookie will
be issued with the given domain and of the given strengths for each entry
in this hash. The HTTP Set-Cookie secure flag is set if and only if 'qop'
is nonzero. As a convenient shorthand,
int => 'domain_string'
is equivalent to
'int,int' => 'domain_string'
Here are some examples taken from the demo.
argument chainURLS expects an array reference which defines a list of places
to go for more (typically cookie) credentials. For example,
chainURLS => [
'https://milt.sec.acme.com/authen',
'https://noam.acme.org/authen'
]
says that when URL credentials are issued, the client will be redirected
to each of the specified sites, in turn. Each of these is expected to
be protected by a PerlAuthenHandler of type Apache::SecSess::Cookie::URL,
which will issue local cookies.
The argument issueURL is used to tell the remote sites (listed in chainURLS
arg) where to redirect the client back to, in order to continue chaining.
See the URL-Chaining example and the demo for more details.
=head2 Database Object Argument
dbo => Apache::SecSess::DBI->new(
UNFINISHED. Apache::SecSess was designed to abstractly handle user
information. All user ID, password, X.509 DN queries are handled through
an opaque object of class Apache::SecSess::DBI.
Since there is no documentation for this version, you must follow the
instructions in INSTALL to get it to work. Read db/* for more
info.
=head1 EXAMPLES
=head2 A Simple Cookie Example
Assuming all resources under directory /protected on one or more hosts
in a DNS domain need to be protected, place the following directive
into 'httpd.conf':
<Location /protected>
SetHandler perl-script
PerlHandler Apache::YourContentHandler
PerlAuthenHandler $Acme::obj->authen
require valid-user
</Location>
On each such host, the secure session object $Acme::obj must be instantiated
from a 'startup.pl' file as in the following example, which uses an X.509
certificate for the original identification and authentication:
use Apache::SecSess::DBI;
use Apache::SecSess::Cookie::X509;
## X.509 certificate authentication, issuing multiple cookies
$Acme::obj = Apache::SecSess::Cookie::X509->new(
dbo => SecSessDBI->new( ... ),
secretFile => 'ckysec.txt',
lifeTime => 1440, idleTime => 60, renewRate => 5,
authRealm => 'Acme',
cookieDomain => {
0 => '.acme.com',
40 => '.acme.com',
128 => 'tom.acme.com'
},
minSessQOP => 128, minAuthQOP => 128,
Suppose the original request is https://noam.acme.org/protected,
which is handled by:
<Location /protected>
PerlAuthenHandler $Acme::noam->authen
...
</Location>
where the authen() method is of an object of class
Apache::SecSess::Cookie::URL instantiated as:
$Acme::noam = Apache::SecSess::Cookie::URL->new(
dbo => Apache::SecSess::DBI->new(...),
secretFile => 'ckysec.txt',
lifeTime => 1440, idleTime => 60, renewRate => 5,
minSessQOP => 128, minAuthQOP => 128,
authRealm => 'Acme',
cookieDomain => { 128 => 'noam.acme.org' },
authenURL => 'https://stu.transacme.com/chain',
defaultURL => 'https://noam.acme.org/protected',
renewURL => 'https://noam.acme.org/renew',
timeoutURL => 'https://noam.acme.org/signout/timeout.html'
);
Like any other subclass of Apache::SecSess::Cookie, URL.pm will
issue cookies based on the presentation of some identifying information,
and authenURL defines where to go to get that information. The difference
is that it now points to a new DNS domain: stu.transacme.com.
That 'remote login' is protected by
<Location /chain>
PerlAuthenHandler $Acme::chain->issue
...
</Location>
i.e., the issue() method of the object $Acme::chain which is instantiated
as
$Acme::chain = Apache::SecSess::URL::Cookie->new(
dbo => Apache::SecSess::DBI->new(...),
secretFile => 'ckysec.txt',
lifeTime => 1440, idleTime => 60, renewRate => 5,
sessQOP => 128, authQOP => 128,
minSessQOP => 128, minAuthQOP => 128,
authRealm => 'Acme',
authenURL => 'https://stu.transacme.com/authen',
chainURLS => [
'https://milt.sec.acme.com/authen',
'https://noam.acme.org/authen'
],
issueURL => 'https://stu.transacme.com/chain',
defaultURL => 'https://stu.transacme.com/protected',
renewURL => 'https://stu.transacme.com/renew',
timeoutURL => 'https://stu.transacme.com/signout/timeout.html'
);
If no cookies are present, the client will be redirected again to
https://stu.transacme.com/authen or the issue() method of a standard
Cookie-based login:
<Location /authen>
PerlAuthenHandler $Acme::stu->issue
...
</Location>
where $Acme::stu is an instance of, say Apache::SecSess::Cookie::X509,
just as in the previous example.
But if and when cookies are present, $Acme::chain->issue will walk
through the URL's listed in the chainURLS argument eventually getting
to https://noam.acme.org/authen protected by
<Location /authen>
PerlAuthenHandler $Acme::noam->issue
...
</Location>
SecSess/Cookie.pm view on Meta::CPAN
#
# Cookie.pm - Apache::SecSess encrypted cookie implementation
#
# $Id: Cookie.pm,v 1.15 2002/05/22 05:40:33 pliam Exp $
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Apache::SecSess::Cookie
# (c) 2001, 2002 John Pliam
# This is open-source software.
# See file 'COPYING' in original distribution for complete details.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
package Apache::SecSess::Cookie;
use strict;
use Apache::Constants qw(:common :response);
use Apache::SecSess;
use Apache::SecSess::Wrapper;
use vars qw(@ISA $VERSION);
$VERSION = sprintf("%d.%02d", (q$Name: SecSess_Release_0_09 $ =~ /\d+/g));
SecSess/Cookie.pm view on Meta::CPAN
sub getCredentials {
my $self = shift;
my($r) = @_;
my $log = $r->log;
my($realm, $ckyhead, %ckys, @tags, $max);
$log->debug(ref($self), "->getCredentials():");
## extract strongest cookie with appropriate name/tag pair
$realm = $self->authRealm;
$ckyhead = $r->headers_in->get('Cookie');
%ckys = ($ckyhead =~ /${realm}:([^=]+)=([^;]+)/g);
@tags = sort {
my($as, $aa) = split(',', $a);
my($bs, $ba) = split(',', $b);
return ($bs <=> $as) ? ($bs <=> $as) : ($ba <=> $aa);
} (keys %ckys);
$max = $tags[0];
unless (defined($max)) { return 'No cookie found.'; }
$log->debug(sprintf("Found Cookie: %s:%s=%s", $realm, $max, $ckys{$max}));
return $self->{wrapper}->unwraphash($ckys{$max});
}
## validate (usually non-cookie) credentials used to authenicate user
sub verifyIdentity { my $self = shift; return undef }
## issue cookies
sub issueCredentials {
my $self = shift;
my($r) = @_;
my $log = $r->log;
my(@cky, %args, $url);
$log->debug(ref($self), "->issueCredentials():");
## put credentials into headers
for (@cky = $self->setCookies($r)) {
$r->err_headers_out->add('Set-Cookie' => $_);
}
## form target URL and response
%args = $r->args;
$url = $self->unwrap_uri($args{url}) || $self->defaultURL;
$log->debug("redirect url (after cookies) = ", $url, " args{url}: ",
$args{url});
unless ($url) { return 'No place to go (no defaultURL set).'; }
return {
message => sprintf("Issuing cookies for user '%s': ('%s')",
SecSess/Cookie.pm view on Meta::CPAN
## delete cookies
sub deleteCredentials {
my $self = shift;
my($r) = @_;
my $log = $r->log;
my(@ckys);
$log->debug(ref($self), "->deleteCredentials():");
## form delete-me cookies
for (@ckys = $self->deleteCookies) {
# $r->header_out('Set-Cookie' => $_); why if no redirect?
$r->err_headers_out->add('Set-Cookie' => $_);
}
unless (@ckys) { return "No cookies to delete."; }
return {
message => sprintf("Deleting cookies for '%s': Set-Cookie: ('%s')",
$r->user, join("','", @ckys)
)
};
}
## make all HTTP cookie headers
sub setCookies {
my $self = shift;
my($r) = @_;
my($time, $uid, $realm, $ckydom, $dom, $s, $a, @ckys);
$time = time;
$uid = $r->user;
$realm = $self->authRealm;
$ckydom = $self->cookieDomain;
for (keys %$ckydom) {
$dom = $ckydom->{$_};
($s, $a) = split(',');
$a = defined($a) ? $a : $s;
push(@ckys, $self->makeCookie(
"$realm:$s,$a",
{uid => $uid, timestamp => $time, qop => $s, authqop => $a},
{path => '/', domain => $dom, secure => $s}
));
}
return @ckys;
}
sub deleteCookies {
my $self = shift;
my($realm, $ckydom, $epoch, $s, $a, @ckys);
$realm = $self->authRealm;
$ckydom = $self->cookieDomain;
$epoch = 'Thu, 1-Jan-70 00:00:01 GMT';
for (keys %$ckydom) {
($s, $a) = split(',');
$a = defined($a) ? $a : $s;
push(@ckys, $self->makeCookie("$realm:$s,$a", {}, {
path => '/',
domain => $ckydom->{$_},
secure => $s,
expires => $epoch
}));
}
return @ckys;
}
## make a single general HTTP cookie string
sub makeCookie {
my $self = shift;
my($ckyname, $contents, $params) = @_;
my($cookie, $path, $par);
## cookie = value
$cookie = sprintf("%s=%s", $ckyname,
(keys %$contents) ? $self->{wrapper}->wraphash($contents) : ''
);
## exceptional parameters (path and secure)
SecSess/Cookie/BasicAuth.pm view on Meta::CPAN
#
# BasicAuth.pm - Apache::SecSess::Cookie w/ basic auth
#
# $Id: BasicAuth.pm,v 1.6 2002/05/22 05:40:33 pliam Exp $
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Apache::SecSess::Cookie::BasicAuth
# (c) 2001, 2002 John Pliam
# This is open-source software.
# See file 'COPYING' in original distribution for complete details.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
package Apache::SecSess::Cookie::BasicAuth;
use strict;
use Apache::Constants qw(:common :response);
use Apache::SecSess::Cookie;
use vars qw(@ISA $VERSION);
$VERSION = sprintf("%d.%02d", (q$Name: SecSess_Release_0_09 $ =~ /\d+/g));
@ISA = qw(Apache::SecSess::Cookie);
## validate (usually non-cookie) credentials used to authenicate user
sub verifyIdentity {
my $self = shift;
my($r) = @_;
my $log = $r->log;
my($uid, $res, $pw, $msg);
$log->debug(ref($self), "->verifyIdentity():");
SecSess/Cookie/LoginForm.pm view on Meta::CPAN
#
# LoginForm.pm - Apache::SecSess::Cookie w/ a login form
#
# $Id: LoginForm.pm,v 1.7 2002/05/22 05:40:33 pliam Exp $
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Apache::SecSess::Cookie::LoginForm
# (c) 2001, 2002 John Pliam
# This is open-source software.
# See file 'COPYING' in original distribution for complete details.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
package Apache::SecSess::Cookie::LoginForm;
use strict;
use Apache::SecSess::Cookie;
use vars qw(@ISA $VERSION);
$VERSION = sprintf("%d.%02d", (q$Name: SecSess_Release_0_09 $ =~ /\d+/g));
@ISA = qw(Apache::SecSess::Cookie);
## validate (usually non-cookie) credentials used to authenicate user
sub verifyIdentity {
my $self = shift;
my($r) = @_;
my $log = $r->log;
my(%params, $uid, $pw, %args, $url, $form, $msg);
$log->debug(ref($self), "->verifyIdentity():");
SecSess/Cookie/URL.pm view on Meta::CPAN
#
# URL.pm - Apache::SecSess::Cookie w/ Apache::SecSess::URL authentication
#
# $Id: URL.pm,v 1.6 2002/05/22 05:40:33 pliam Exp $
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Apache::SecSess::Cookie::URL
# (c) 2001, 2002 John Pliam
# This is open-source software.
# See file 'COPYING' in original distribution for complete details.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
package Apache::SecSess::Cookie::URL;
use strict;
use Apache::SecSess::Cookie;
use Apache::SecSess::Wrapper;
use vars qw(@ISA $VERSION);
$VERSION = sprintf("%d.%02d", (q$Name: SecSess_Release_0_09 $ =~ /\d+/g));
@ISA = qw(Apache::SecSess::Cookie);
## validate (usually non-cookie) credentials used to authenicate user
sub verifyIdentity {
my $self = shift;
my($r) = @_;
my $log = $r->log;
my(%args, $ctxt, $urlcred);
$log->debug(ref($self), "->verifyIdentity():");
SecSess/Cookie/X509.pm view on Meta::CPAN
#
# X509.pm - Apache::SecSess::Cookie w/ X.509 certificate authentication
#
# $Id: X509.pm,v 1.6 2002/05/22 05:40:33 pliam Exp $
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Apache::SecSess::Cookie::X509
# (c) 2001, 2002 John Pliam
# This is open-source software.
# See file 'COPYING' in original distribution for complete details.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
package Apache::SecSess::Cookie::X509;
use strict;
use Apache::SecSess::Cookie;
use vars qw(@ISA $VERSION);
$VERSION = sprintf("%d.%02d", (q$Name: SecSess_Release_0_09 $ =~ /\d+/g));
@ISA = qw(Apache::SecSess::Cookie);
## validate (usually non-cookie) credentials used to authenicate user
sub verifyIdentity {
my $self = shift;
my($r) = @_;
my $log = $r->log;
my($subr, $email, $uid);
$log->debug(ref($self), "->verifyIdentity():");
SecSess/Cookie/X509PIN.pm view on Meta::CPAN
#
# X509PIN.pm - Apache::SecSess::Cookie w/ X.509 & PIN code
#
# $Id: X509PIN.pm,v 1.6 2002/05/22 05:40:33 pliam Exp $
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Apache::SecSess::Cookie::X509PIN
# (c) 2001, 2002 John Pliam
# This is open-source software.
# See file 'COPYING' in original distribution for complete details.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
package Apache::SecSess::Cookie::X509PIN;
use strict;
use Apache::SecSess::Cookie;
use vars qw(@ISA $VERSION);
$VERSION = sprintf("%d.%02d", (q$Name: SecSess_Release_0_09 $ =~ /\d+/g));
@ISA = qw(Apache::SecSess::Cookie);
## validate (usually non-cookie) credentials used to authenicate user
sub verifyIdentity {
my $self = shift;
my($r) = @_;
my $log = $r->log;
my($subr, $email, $uid, %params, $pin, %args, $url, $form, $msg);
$log->debug(ref($self), "->verifyIdentity():");
SecSess/URL/Cookie.pm view on Meta::CPAN
#
# Cookie.pm - Apache::SecSess::URL auth from Apache::SecSess::Cookie
#
# $Id: Cookie.pm,v 1.4 2002/05/22 05:40:33 pliam Exp $
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Apache::SecSess::URL::Cookie
# (c) 2001, 2002 John Pliam
# This is open-source software.
# See file 'COPYING' in original distribution for complete details.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
package Apache::SecSess::URL::Cookie;
use strict;
use Apache::Constants qw(:common :response);
use Apache::SecSess;
use Apache::SecSess::URL;
use Apache::SecSess::Wrapper;
use vars qw(@ISA $VERSION);
$VERSION = sprintf("%d.%02d", (q$Name: SecSess_Release_0_09 $ =~ /\d+/g));
SecSess/URL/Cookie.pm view on Meta::CPAN
sub verifyIdentity {
my $self = shift;
my($r) = @_;
my $log = $r->log;
my($realm, $ckyhead, %ckys, @tags, $max, $url, $ckycred);
$log->debug(ref($self), "->verifyIdentity():");
## extract strongest cookie with appropriate name/tag pair
$realm = $self->authRealm;
$ckyhead = $r->headers_in->get('Cookie');
%ckys = ($ckyhead =~ /${realm}:([^=]+)=([^;]+)/g);
@tags = sort {
my($as, $aa) = split(',', $a);
my($bs, $ba) = split(',', $b);
return ($bs <=> $as) ? ($bs <=> $as) : ($ba <=> $aa);
} (keys %ckys);
$max = $tags[0];
## no cookie found, must redirect to obtain
unless (defined($max)) {
SecSess/URL/Cookie.pm view on Meta::CPAN
$self->authenURL,
$self->requested_uri($r)
);
return {
message => "No cookie found, redirecting to '$url'",
uri => $url
};
}
## cookie found, but must be verified
$log->debug(sprintf("Found Cookie: %s:%s=%s", $realm, $max, $ckys{$max}));
$ckycred = $self->{wrapper}->unwraphash($ckys{$max});
return $self->validateCredentials($r, $ckycred);
}
1;
__END__
What are you looking at?
demo/ht/menu.comp view on Meta::CPAN
</td></tr>
</table>
<!-- end of common menu main links -->
<%init>
## default menu items
unless (defined($menuitems)) {
$menuitems = [
{head => 'Single Host Demos:'},
{text => 'adam (Cookie::BasicAuth)',
href => 'http://adam.acme.com/protected'},
{text => 'lysander (Cookie::LoginForm)',
href => 'http://lysander.acme.com/protected'},
{text => 'tom (Cookie::X509)',
href => 'https://tom.acme.com/protected'},
{text => 'john (Cookie::X509PIN)',
href => 'https://john.sec.acme.com/protected'},
{head => 'Multi-Host Demo:'},
{text => 'milt (Cookie::URL)',
href => 'https://milt.sec.acme.com/protected'},
{text => 'noam (Cookie::URL)',
href => 'https://noam.acme.org/protected'},
{text => 'stu (X509PIN)',
href => 'https://stu.transacme.com/protected'},
{head => 'Miscellaneous:'},
{text => 'Get Cert', href => 'http://adam.acme.com/acme-ca.crt'},
{text => 'Sign Out', href => '/signout'}
];
}
</%init>
demo/httpdconf/startup.pl view on Meta::CPAN
#!/usr/bin/perl
# startup.pl - Apache perl startup file
#
# $Id: startup.pl,v 1.15 2002/05/19 05:15:33 pliam Exp $
#
## must provide basic db hooks and secure objects at startup
use Apache::SecSess::DBI;
use Apache::SecSess::Cookie::BasicAuth;
use Apache::SecSess::Cookie::LoginForm;
use Apache::SecSess::Cookie::X509;
use Apache::SecSess::Cookie::X509PIN;
use Apache::SecSess::Cookie::URL;
use Apache::SecSess::URL::Cookie;
## instantiate session security hander objects
## basic authentication
$Acme::adam = Apache::SecSess::Cookie::BasicAuth->new(
dbo => Apache::SecSess::DBI->new(
dbifile => '/usr/local/apache/conf/private/dbilogin.txt'
),
secretFile => '/usr/local/apache/conf/private/ckysec.txt',
# lifeTime => 1440, idleTime => 60, renewRate => 5,
lifeTime => 5, idleTime => 2, renewRate => 1,
minSessQOP => 0, minAuthQOP => 40,
authRealm => 'Acme',
cookieDomain => {'0,40' => 'adam.acme.com'},
authenURL => 'https://adam.acme.com/authen',
defaultURL => 'http://adam.acme.com/protected',
renewURL => 'http://adam.acme.com/renew',
timeoutURL => 'http://adam.acme.com/signout/timeout.html'
);
## login form
$Acme::lysander = Apache::SecSess::Cookie::LoginForm->new(
dbo => Apache::SecSess::DBI->new(
dbifile => '/usr/local/apache/conf/private/dbilogin.txt'
),
secretFile => '/usr/local/apache/conf/private/ckysec.txt',
lifeTime => 1440, idleTime => 60, renewRate => 5,
minSessQOP => 0, minAuthQOP => 40,
authRealm => 'Acme',
cookieDomain => {'0,40' => 'lysander.acme.com'},
authenURL => 'https://lysander.acme.com/authen',
defaultURL => 'http://lysander.acme.com/protected',
renewURL => 'http://lysander.acme.com/renew',
timeoutURL => 'http://lysander.acme.com/signout/timeout.html'
);
## X.509 certificate authentication, issuing multiple cookies
$Acme::multi = Apache::SecSess::Cookie::X509->new(
dbo => Apache::SecSess::DBI->new(
dbifile => '/usr/local/apache/conf/private/dbilogin.txt'
),
secretFile => '/usr/local/apache/conf/private/ckysec.txt',
lifeTime => 1440, idleTime => 60, renewRate => 5,
minSessQOP => 128, minAuthQOP => 128,
authRealm => 'Acme',
cookieDomain => {
0 => '.acme.com',
40 => '.acme.com',
demo/httpdconf/startup.pl view on Meta::CPAN
},
authenURL => 'https://tom.acme.com/authen',
defaultURL => 'https://tom.acme.com/protected',
renewURL => 'https://tom.acme.com/renew',
timeoutURL => 'https://tom.acme.com/signout/timeout.html',
adminURL => 'https://tom.acme.com/changeid',
errorURL => 'http://tom.acme.com/error.html'
);
## Two-factor auth (X.509 & PIN) issuing multiple cookies w/ secure wildcard
$Acme::twofact = Apache::SecSess::Cookie::X509PIN->new(
dbo => Apache::SecSess::DBI->new(
dbifile => '/usr/local/apache/conf/private/dbilogin.txt'
),
secretFile => '/usr/local/apache/conf/private/ckysec.txt',
lifeTime => 1440, idleTime => 60, renewRate => 5,
minSessQOP => 128, minAuthQOP => 128,
authRealm => 'Acme',
cookieDomain => {
0 => '.acme.com',
40 => '.acme.com', # insecure wildcard domain
demo/httpdconf/startup.pl view on Meta::CPAN
},
authenURL => 'https://john.sec.acme.com/authen',
defaultURL => 'https://john.sec.acme.com/protected',
renewURL => 'https://john.sec.acme.com/renew',
timeoutURL => 'https://john.sec.acme.com/signout/timeout.html',
adminURL => 'https://john.sec.acme.com/changeid',
errorURL => 'http://john.sec.acme.com/error.html'
);
#
# multi-host Cookie/URL chaining
#
## stu.transacme.com standard cookies (strong auth: X.509 & PIN)
$Acme::stu = Apache::SecSess::Cookie::X509PIN->new(
dbo => Apache::SecSess::DBI->new(
dbifile => '/usr/local/apache/conf/private/dbilogin.txt'
),
secretFile => '/usr/local/apache/conf/private/ckysec.txt',
lifeTime => 1440, idleTime => 60, renewRate => 5,
minSessQOP => 128, minAuthQOP => 128,
authRealm => 'Acme',
cookieDomain => { 128 => 'stu.transacme.com' },
authenURL => 'https://stu.transacme.com/authen',
defaultURL => 'https://stu.transacme.com/chain',
renewURL => 'https://stu.transacme.com/renew',
timeoutURL => 'https://stu.transacme.com/signout/timeout.html',
adminURL => 'https://stu.transacme.com/changeid',
errorURL => 'http://stu.transacme.com/error.html'
);
## stu.transacme.com issue mangled-URL credentials based on stu cookies
$Acme::chain = Apache::SecSess::URL::Cookie->new(
dbo => Apache::SecSess::DBI->new(
dbifile => '/usr/local/apache/conf/private/dbilogin.txt'
),
secretFile => '/usr/local/apache/conf/private/ckysec.txt',
lifeTime => 1440, idleTime => 60, renewRate => 5,
sessQOP => 128, authQOP => 128,
minSessQOP => 128, minAuthQOP => 128,
authRealm => 'Acme',
authenURL => 'https://stu.transacme.com/authen',
chainURLS => [
demo/httpdconf/startup.pl view on Meta::CPAN
],
issueURL => 'https://stu.transacme.com/chain',
defaultURL => 'https://stu.transacme.com/protected',
renewURL => 'https://stu.transacme.com/renew',
timeoutURL => 'https://stu.transacme.com/signout/timeout.html',
adminURL => 'https://stu.transacme.com/changeid',
errorURL => 'http://stu.transacme.com/error.html'
);
## noam.acme.org cookies based on mangled-URL
$Acme::noam = Apache::SecSess::Cookie::URL->new(
dbo => Apache::SecSess::DBI->new(
dbifile => '/usr/local/apache/conf/private/dbilogin.txt'
),
secretFile => '/usr/local/apache/conf/private/ckysec.txt',
lifeTime => 1440, idleTime => 60, renewRate => 5,
minSessQOP => 128, minAuthQOP => 128,
authRealm => 'Acme',
cookieDomain => { 128 => 'noam.acme.org' },
authenURL => 'https://stu.transacme.com/chain',
defaultURL => 'https://noam.acme.org/protected',
renewURL => 'https://noam.acme.org/renew',
timeoutURL => 'https://noam.acme.org/signout/timeout.html',
adminURL => 'https://noam.acme.org/changeid',
errorURL => 'http://noam.acme.org/error.html'
);
## milt.sec.acme.com multi-cookies based on mangled-URL
$Acme::milt = Apache::SecSess::Cookie::URL->new(
dbo => Apache::SecSess::DBI->new(
dbifile => '/usr/local/apache/conf/private/dbilogin.txt'
),
secretFile => '/usr/local/apache/conf/private/ckysec.txt',
lifeTime => 1440, idleTime => 60, renewRate => 5,
minSessQOP => 128, minAuthQOP => 128,
authRealm => 'Acme',
cookieDomain => {
0 => '.acme.com',
40 => '.acme.com', # insecure wildcard domain
rfc/rfc2109.txt view on Meta::CPAN
This document specifies an Internet standards track protocol for the
Internet community, and requests discussion and suggestions for
improvements. Please refer to the current edition of the "Internet
Official Protocol Standards" (STD 1) for the standardization state
and status of this protocol. Distribution of this memo is unlimited.
1. ABSTRACT
This document specifies a way to create a stateful session with HTTP
requests and responses. It describes two new headers, Cookie and
Set-Cookie, which carry state information between participating
origin servers and user agents. The method described here differs
from Netscape's Cookie proposal, but it can interoperate with
HTTP/1.0 user agents that use Netscape's method. (See the HISTORICAL
section.)
2. TERMINOLOGY
The terms user agent, client, server, proxy, and origin server have
the same meaning as in the HTTP/1.0 specification.
Fully-qualified host name (FQHN) means either the fully-qualified
domain name (FQDN) of a host (i.e., a completely specified domain
rfc/rfc2109.txt view on Meta::CPAN
to the user agent, and for the user agent to return the state
information to the origin server. The goal is to have a minimal
impact on HTTP and user agents. Only origin servers that need to
maintain sessions would suffer any significant impact, and that
impact can largely be confined to Common Gateway Interface (CGI)
programs, unless the server provides more sophisticated state
management support. (See Implementation Considerations, below.)
4.1 Syntax: General
The two state management headers, Set-Cookie and Cookie, have common
syntactic properties involving attribute-value pairs. The following
grammar uses the notation, and tokens DIGIT (decimal digits) and
token (informally, a sequence of non-special, non-white space
characters) from the HTTP/1.1 specification [RFC 2068] to describe
their syntax.
av-pairs = av-pair *(";" av-pair)
av-pair = attr ["=" value] ; optional value
attr = token
value = word
rfc/rfc2109.txt view on Meta::CPAN
4.2 Origin Server Role
4.2.1 General
The origin server initiates a session, if it so desires. (Note that
"session" here does not refer to a persistent network connection but
to a logical session created from HTTP requests and responses. The
presence or absence of a persistent connection should have no effect
on the use of cookie-derived sessions). To initiate a session, the
origin server returns an extra response header to the client, Set-
Cookie. (The details follow later.)
A user agent returns a Cookie request header (see below) to the
origin server if it chooses to continue a session. The origin server
may ignore it or use it to determine the current state of the
Kristol & Montulli Standards Track [Page 3]
RFC 2109 HTTP State Management Mechanism February 1997
session. It may send back to the client a Set-Cookie response header
with the same or different information, or it may send no Set-Cookie
header at all. The origin server effectively ends a session by
sending the client a Set-Cookie header with Max-Age=0.
Servers may return a Set-Cookie response headers with any response.
User agents should send Cookie request headers, subject to other
rules detailed below, with every request.
An origin server may include multiple Set-Cookie headers in a
response. Note that an intervening gateway could fold multiple such
headers into a single header.
4.2.2 Set-Cookie Syntax
The syntax for the Set-Cookie response header is
set-cookie = "Set-Cookie:" cookies
cookies = 1#cookie
cookie = NAME "=" VALUE *(";" cookie-av)
NAME = attr
VALUE = value
cookie-av = "Comment" "=" value
| "Domain" "=" value
| "Max-Age" "=" value
| "Path" "=" value
| "Secure"
| "Version" "=" 1*DIGIT
Informally, the Set-Cookie response header comprises the token Set-
Cookie:, followed by a comma-separated list of one or more cookies.
Each cookie begins with a NAME=VALUE pair, followed by zero or more
semi-colon-separated attribute-value pairs. The syntax for
attribute-value pairs was shown earlier. The specific attributes and
the semantics of their values follows. The NAME=VALUE attribute-
value pair must come first in each cookie. The others, if present,
can occur in any order. If an attribute appears more than once in a
cookie, the behavior is undefined.
NAME=VALUE
Required. The name of the state information ("cookie") is NAME,
rfc/rfc2109.txt view on Meta::CPAN
Kristol & Montulli Standards Track [Page 4]
RFC 2109 HTTP State Management Mechanism February 1997
The VALUE is opaque to the user agent and may be anything the
origin server chooses to send, possibly in a server-selected
printable ASCII encoding. "Opaque" implies that the content is of
interest and relevance only to the origin server. The content
may, in fact, be readable by anyone that examines the Set-Cookie
header.
Comment=comment
Optional. Because cookies can contain private information about a
user, the Cookie attribute allows an origin server to document its
intended use of a cookie. The user can inspect the information to
decide whether to initiate or continue a session with this cookie.
Domain=domain
Optional. The Domain attribute specifies the domain for which the
cookie is valid. An explicitly specified domain must always start
with a dot.
Max-Age=delta-seconds
Optional. The Max-Age attribute defines the lifetime of the
rfc/rfc2109.txt view on Meta::CPAN
Kristol & Montulli Standards Track [Page 5]
RFC 2109 HTTP State Management Mechanism February 1997
4.2.3 Controlling Caching
An origin server must be cognizant of the effect of possible caching
of both the returned resource and the Set-Cookie header. Caching
"public" documents is desirable. For example, if the origin server
wants to use a public document such as a "front door" page as a
sentinel to indicate the beginning of a session for which a Set-
Cookie response header must be generated, the page should be stored
in caches "pre-expired" so that the origin server will see further
requests. "Private documents", for example those that contain
information strictly private to a session, should not be cached in
shared caches.
If the cookie is intended for use by a single user, the Set-cookie
header should not be cached. A Set-cookie header that is intended to
be shared by multiple users may be cached.
The origin server should send the following additional HTTP/1.1
response headers, depending on circumstances:
* To suppress caching of the Set-Cookie header: Cache-control: no-
cache="set-cookie".
and one of the following:
* To suppress caching of a private document in shared caches: Cache-
control: private.
* To allow caching of a document and require that it be validated
before returning it to the client: Cache-control: must-revalidate.
* To allow caching of a document, but to require that proxy caches
(not user agent caches) validate it before returning it to the
client: Cache-control: proxy-revalidate.
* To allow caching of a document and request that it be validated
before returning it to the client (by "pre-expiring" it):
Cache-control: max-age=0. Not all caches will revalidate the
document in every case.
HTTP/1.1 servers must send Expires: old-date (where old-date is a
date long in the past) on responses containing Set-Cookie response
headers unless they know for certain (by out of band means) that
there are no downsteam HTTP/1.0 proxies. HTTP/1.1 servers may send
other Cache-Control directives that permit caching by HTTP/1.1
proxies in addition to the Expires: old-date directive; the Cache-
Control directive will override the Expires: old-date for HTTP/1.1
proxies.
Kristol & Montulli Standards Track [Page 6]
RFC 2109 HTTP State Management Mechanism February 1997
4.3 User Agent Role
4.3.1 Interpreting Set-Cookie
The user agent keeps separate track of state information that arrives
via Set-Cookie response headers from each origin server (as
distinguished by name or IP address and port). The user agent
applies these defaults for optional attributes that are missing:
VersionDefaults to "old cookie" behavior as originally specified by
Netscape. See the HISTORICAL section.
Domain Defaults to the request-host. (Note that there is no dot at
the beginning of request-host.)
Max-AgeThe default behavior is to discard the cookie when the user
agent exits.
Path Defaults to the path of the request URL that generated the
Set-Cookie response, up to, but not including, the
right-most /.
Secure If absent, the user agent may send the cookie over an
insecure channel.
4.3.2 Rejecting Cookies
To prevent possible security or privacy violations, a user agent
rejects a cookie (shall not store its information) if any of the
following is true:
* The value for the Path attribute is not a prefix of the request-
URI.
* The value for the Domain attribute contains no embedded dots or
does not start with a dot.
* The value for the request-host does not domain-match the Domain
attribute.
* The request-host is a FQDN (not IP address) and has the form HD,
where D is the value of the Domain attribute, and H is a string
that contains one or more dots.
Examples:
* A Set-Cookie from request-host y.x.foo.com for Domain=.foo.com
would be rejected, because H is y.x and contains a dot.
Kristol & Montulli Standards Track [Page 7]
RFC 2109 HTTP State Management Mechanism February 1997
* A Set-Cookie from request-host x.foo.com for Domain=.foo.com would
be accepted.
* A Set-Cookie with Domain=.com or Domain=.com., will always be
rejected, because there is no embedded dot.
* A Set-Cookie with Domain=ajax.com will be rejected because the
value for Domain does not begin with a dot.
4.3.3 Cookie Management
If a user agent receives a Set-Cookie response header whose NAME is
the same as a pre-existing cookie, and whose Domain and Path
attribute values exactly (string) match those of a pre-existing
cookie, the new cookie supersedes the old. However, if the Set-
Cookie has a value for Max-Age of zero, the (old and new) cookie is
discarded. Otherwise cookies accumulate until they expire (resources
permitting), at which time they are discarded.
Because user agents have finite space in which to store cookies, they
may also discard older cookies to make space for newer ones, using,
for example, a least-recently-used algorithm, along with constraints
on the maximum number of cookies that each origin server may set.
If a Set-Cookie response header includes a Comment attribute, the
user agent should store that information in a human-readable form
with the cookie and should display the comment text as part of a
cookie inspection user interface.
User agents should allow the user to control cookie destruction. An
infrequently-used cookie may function as a "preferences file" for
network applications, and a user may wish to keep it even if it is
the least-recently-used cookie. One possible implementation would be
an interface that allows the permanent storage of a cookie through a
checkbox (or, conversely, its immediate destruction).
Privacy considerations dictate that the user have considerable
control over cookie management. The PRIVACY section contains more
information.
4.3.4 Sending Cookies to the Origin Server
When it sends a request to an origin server, the user agent sends a
Cookie request header to the origin server if it has cookies that are
applicable to the request, based on
* the request-host;
Kristol & Montulli Standards Track [Page 8]
RFC 2109 HTTP State Management Mechanism February 1997
* the request-URI;
* the cookie's age.
The syntax for the header is:
cookie = "Cookie:" cookie-version
1*((";" | ",") cookie-value)
cookie-value = NAME "=" VALUE [";" path] [";" domain]
cookie-version = "$Version" "=" value
NAME = attr
VALUE = value
path = "$Path" "=" value
domain = "$Domain" "=" value
The value of the cookie-version attribute must be the value from the
Version attribute, if any, of the corresponding Set-Cookie response
header. Otherwise the value for cookie-version is 0. The value for
the path attribute must be the value from the Path attribute, if any,
of the corresponding Set-Cookie response header. Otherwise the
attribute should be omitted from the Cookie request header. The
value for the domain attribute must be the value from the Domain
attribute, if any, of the corresponding Set-Cookie response header.
Otherwise the attribute should be omitted from the Cookie request
header.
Note that there is no Comment attribute in the Cookie request header
corresponding to the one in the Set-Cookie response header. The user
agent does not return the comment information to the origin server.
The following rules apply to choosing applicable cookie-values from
among all the cookies the user agent has.
Domain Selection
The origin server's fully-qualified host name must domain-match
the Domain attribute of the cookie.
Path Selection
The Path attribute of the cookie must match a prefix of the
request-URI.
Max-Age Selection
Cookies that have expired should have been discarded and thus
are not forwarded to an origin server.
Kristol & Montulli Standards Track [Page 9]
RFC 2109 HTTP State Management Mechanism February 1997
If multiple cookies satisfy the criteria above, they are ordered in
the Cookie header such that those with more specific Path attributes
precede those with less specific. Ordering with respect to other
attributes (e.g., Domain) is unspecified.
Note: For backward compatibility, the separator in the Cookie header
is semi-colon (;) everywhere. A server should also accept comma (,)
as the separator between cookie-values for future compatibility.
4.3.5 Sending Cookies in Unverifiable Transactions
Users must have control over sessions in order to ensure privacy.
(See PRIVACY section below.) To simplify implementation and to
prevent an additional layer of complexity where adequate safeguards
exist, however, this document distinguishes between transactions that
are verifiable and those that are unverifiable. A transaction is
verifiable if the user has the option to review the request-URI prior
to its use in the transaction. A transaction is unverifiable if the
user does not have that option. Unverifiable transactions typically
arise when a user agent automatically requests inlined or embedded
rfc/rfc2109.txt view on Meta::CPAN
button.) However, even this would not make all links verifiable; for
example, links to automatically loaded images would not normally be
subject to "mouse pointer" verification.
Many user agents also provide the option for a user to view the HTML
source of a document, or to save the source to an external file where
it can be viewed by another application. While such an option does
provide a crude review mechanism, some users might not consider it
acceptable for this purpose.
4.4 How an Origin Server Interprets the Cookie Header
A user agent returns much of the information in the Set-Cookie header
to the origin server when the Path attribute matches that of a new
request. When it receives a Cookie header, the origin server should
treat cookies with NAMEs whose prefix is $ specially, as an attribute
for the adjacent cookie. The value for such a NAME is to be
interpreted as applying to the lexically (left-to-right) most recent
cookie whose name does not have the $ prefix. If there is no
previous cookie, the value applies to the cookie mechanism as a
whole. For example, consider the cookie
Cookie: $Version="1"; Customer="WILE_E_COYOTE";
$Path="/acme"
$Version applies to the cookie mechanism as a whole (and gives the
version number for the cookie mechanism). $Path is an attribute
whose value (/acme) defines the Path attribute that was used when the
Customer cookie was defined in a Set-Cookie response header.
4.5 Caching Proxy Role
One reason for separating state information from both a URL and
document content is to facilitate the scaling that caching permits.
To support cookies, a caching proxy must obey these rules already in
the HTTP specification:
* Honor requests from the cache, if possible, based on cache validity
rules.
* Pass along a Cookie request header in any request that the proxy
must make of another server.
* Return the response to the client. Include any Set-Cookie response
header.
Kristol & Montulli Standards Track [Page 11]
RFC 2109 HTTP State Management Mechanism February 1997
* Cache the received response subject to the control of the usual
headers, such as Expires, Cache-control: no-cache, and Cache-
control: private,
* Cache the Set-Cookie subject to the control of the usual header,
Cache-control: no-cache="set-cookie". (The Set-Cookie header
should usually not be cached.)
Proxies must not introduce Set-Cookie (Cookie) headers of their own
in proxy responses (requests).
5. EXAMPLES
5.1 Example 1
Most detail of request and response headers has been omitted. Assume
the user agent has no stored cookies.
1. User Agent -> Server
POST /acme/login HTTP/1.1
[form data]
User identifies self via a form.
2. Server -> User Agent
HTTP/1.1 200 OK
Set-Cookie: Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"
Cookie reflects user's identity.
3. User Agent -> Server
POST /acme/pickitem HTTP/1.1
Cookie: $Version="1"; Customer="WILE_E_COYOTE"; $Path="/acme"
[form data]
User selects an item for "shopping basket."
4. Server -> User Agent
HTTP/1.1 200 OK
Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";
Path="/acme"
Shopping basket contains an item.
Kristol & Montulli Standards Track [Page 12]
RFC 2109 HTTP State Management Mechanism February 1997
5. User Agent -> Server
POST /acme/shipping HTTP/1.1
Cookie: $Version="1";
Customer="WILE_E_COYOTE"; $Path="/acme";
Part_Number="Rocket_Launcher_0001"; $Path="/acme"
[form data]
User selects shipping method from form.
6. Server -> User Agent
HTTP/1.1 200 OK
Set-Cookie: Shipping="FedEx"; Version="1"; Path="/acme"
New cookie reflects shipping method.
7. User Agent -> Server
POST /acme/process HTTP/1.1
Cookie: $Version="1";
Customer="WILE_E_COYOTE"; $Path="/acme";
Part_Number="Rocket_Launcher_0001"; $Path="/acme";
Shipping="FedEx"; $Path="/acme"
[form data]
User chooses to process order.
8. Server -> User Agent
HTTP/1.1 200 OK
rfc/rfc2109.txt view on Meta::CPAN
Imagine the user agent has received, in response to earlier requests,
the response headers
Kristol & Montulli Standards Track [Page 13]
RFC 2109 HTTP State Management Mechanism February 1997
Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";
Path="/acme"
and
Set-Cookie: Part_Number="Riding_Rocket_0023"; Version="1";
Path="/acme/ammo"
A subsequent request by the user agent to the (same) server for URLs
of the form /acme/ammo/... would include the following request
header:
Cookie: $Version="1";
Part_Number="Riding_Rocket_0023"; $Path="/acme/ammo";
Part_Number="Rocket_Launcher_0001"; $Path="/acme"
Note that the NAME=VALUE pair for the cookie with the more specific
Path attribute, /acme/ammo, comes before the one with the less
specific Path attribute, /acme. Further note that the same cookie
name appears more than once.
A subsequent request by the user agent to the (same) server for a URL
of the form /acme/parts/ would include the following request header:
Cookie: $Version="1"; Part_Number="Rocket_Launcher_0001"; $Path="/acme"
Here, the second cookie's Path attribute /acme/ammo is not a prefix
of the request URL, /acme/parts/, so the cookie does not get
forwarded to the server.
6. IMPLEMENTATION CONSIDERATIONS
Here we speculate on likely or desirable details for an origin server
that implements state management.
6.1 Set-Cookie Content
An origin server's content should probably be divided into disjoint
application areas, some of which require the use of state
information. The application areas can be distinguished by their
request URLs. The Set-Cookie header can incorporate information
about the application areas by setting the Path attribute for each
one.
The session information can obviously be clear or encoded text that
describes state. However, if it grows too large, it can become
unwieldy. Therefore, an implementor might choose for the session
information to be a key to a server-side resource. Of course, using
rfc/rfc2109.txt view on Meta::CPAN
size of cookies that they can store. In general, user agents' cookie
support should have no fixed limits. They should strive to store as
many frequently-used cookies as possible. Furthermore, general-use
user agents should provide each of the following minimum capabilities
individually, although not necessarily simultaneously:
* at least 300 cookies
* at least 4096 bytes per cookie (as measured by the size of the
characters that comprise the cookie non-terminal in the syntax
description of the Set-Cookie header)
* at least 20 cookies per unique host or domain name
User agents created for specific purposes or for limited-capacity
devices should provide at least 20 cookies of 4096 bytes, to ensure
that the user can interact with a session-based origin server.
The information in a Set-Cookie response header must be retained in
its entirety. If for some reason there is inadequate space to store
the cookie, it must be discarded, not truncated.
Applications should use as few and as small cookies as possible, and
they should cope gracefully with the loss of a cookie.
rfc/rfc2109.txt view on Meta::CPAN
cookie information. Otherwise a malicious server could attempt to
flood a user agent with many cookies, or large cookies, on successive
responses, which would force out cookies the user agent had received
from other servers. However, the minima specified above should still
be supported.
7. PRIVACY
7.1 User Agent Control
An origin server could create a Set-Cookie header to track the path
of a user through the server. Users may object to this behavior as
an intrusive accumulation of information, even if their identity is
not evident. (Identity might become evident if a user subsequently
fills out a form that contains identifying information.) This state
management specification therefore requires that a user agent give
the user control over such a possible intrusion, although the
interface through which the user is given this control is left
unspecified. However, the control mechanisms provided shall at least
allow the user
rfc/rfc2109.txt view on Meta::CPAN
* to display a visual indication that a stateful session is in
progress.
* to let the user decide which cookies, if any, should be saved
when the user concludes a window or user agent session.
* to let the user examine the contents of a cookie at any time.
A user agent usually begins execution with no remembered state
information. It should be possible to configure a user agent never
to send Cookie headers, in which case it can never sustain state with
Kristol & Montulli Standards Track [Page 16]
RFC 2109 HTTP State Management Mechanism February 1997
an origin server. (The user agent would then behave like one that is
unaware of how to handle Set-Cookie response headers.)
When the user agent terminates execution, it should let the user
discard all state information. Alternatively, the user agent may ask
the user whether state information should be retained; the default
should be "no". If the user chooses to retain state information, it
would be restored the next time the user agent runs.
NOTE: User agents should probably be cautious about using files to
store cookies long-term. If a user runs more than one instance of
the user agent, the cookies could be commingled or otherwise messed
rfc/rfc2109.txt view on Meta::CPAN
Domain. We consider it acceptable for hosts host1.foo.com and
host2.foo.com to share cookies, but not a.com and b.com.
Similarly, a server can only set a Path for cookies that are related
to the request-URI.
8. SECURITY CONSIDERATIONS
8.1 Clear Text
The information in the Set-Cookie and Cookie headers is unprotected.
Two consequences are:
1. Any sensitive information that is conveyed in them is exposed
to intruders.
2. A malicious intermediary could alter the headers as they travel
in either direction, with unpredictable results.
These facts imply that information of a personal and/or financial
nature should only be sent over a secure channel. For less sensitive
information, or when the content of the header is a database key, an
origin server should be vigilant to prevent a bad Cookie value from
causing failures.
Kristol & Montulli Standards Track [Page 17]
RFC 2109 HTTP State Management Mechanism February 1997
8.2 Cookie Spoofing
Proper application design can avoid spoofing attacks from related
domains. Consider:
1. User agent makes request to victim.cracker.edu, gets back
cookie session_id="1234" and sets the default domain
victim.cracker.edu.
2. User agent makes request to spoof.cracker.edu, gets back
cookie session-id="1111", with Domain=".cracker.edu".
3. User agent makes request to victim.cracker.edu again, and
passes
Cookie: $Version="1";
session_id="1234";
session_id="1111"; $Domain=".cracker.edu"
The server at victim.cracker.edu should detect that the second
cookie was not one it originated by noticing that the Domain
attribute is not for itself and ignore it.
8.3 Unexpected Cookie Sharing
A user agent should make every attempt to prevent the sharing of
session information between hosts that are in different domains.
Embedded or inlined objects may cause particularly severe privacy
problems if they can be used to share cookies between disparate
hosts. For example, a malicious server could embed cookie
information for host a.com in a URI for a CGI on host b.com. User
agent implementors are strongly encouraged to prevent this sort of
exchange whenever possible.
9. OTHER, SIMILAR, PROPOSALS
Three other proposals have been made to accomplish similar goals.
This specification is an amalgam of Kristol's State-Info proposal and
Netscape's Cookie proposal.
Brian Behlendorf proposed a Session-ID header that would be user-
agent-initiated and could be used by an origin server to track
"clicktrails". It would not carry any origin-server-defined state,
however. Phillip Hallam-Baker has proposed another client-defined
session ID mechanism for similar purposes.
rfc/rfc2109.txt view on Meta::CPAN
Kristol & Montulli Standards Track [Page 18]
RFC 2109 HTTP State Management Mechanism February 1997
While both session IDs and cookies can provide a way to sustain
stateful sessions, their intended purpose is different, and,
consequently, the privacy requirements for them are different. A
user initiates session IDs to allow servers to track progress through
them, or to distinguish multiple users on a shared machine. Cookies
are server-initiated, so the cookie mechanism described here gives
users control over something that would otherwise take place without
the users' awareness. Furthermore, cookies convey rich, server-
selected information, whereas session IDs comprise user-selected,
simple information.
10. HISTORICAL
10.1 Compatibility With Netscape's Implementation
HTTP/1.0 clients and servers may use Set-Cookie and Cookie headers
that reflect Netscape's original cookie proposal. These notes cover
inter-operation between "old" and "new" cookies.
10.1.1 Extended Cookie Header
This proposal adds attribute-value pairs to the Cookie request header
in a compatible way. An "old" client that receives a "new" cookie
will ignore attributes it does not understand; it returns what it
does understand to the origin server. A "new" client always sends
cookies in the new form.
An "old" server that receives a "new" cookie will see what it thinks
are many cookies with names that begin with a $, and it will ignore
them. (The "old" server expects these cookies to be separated by
semi-colon, not comma.) A "new" server can detect cookies that have
passed through an "old" client, because they lack a $Version
rfc/rfc2109.txt view on Meta::CPAN
RFC 2109 HTTP State Management Mechanism February 1997
10.1.3 Punctuation
In Netscape's original proposal, the values in attribute-value pairs
did not accept "-quoted strings. Origin servers should be cautious
about sending values that require quotes unless they know the
receiving user agent understands them (i.e., "new" cookies). A
("new") user agent should only use quotes around values in Cookie
headers when the cookie's version(s) is (are) all compliant with this
specification or later.
In Netscape's original proposal, no whitespace was permitted around
the = that separates attribute-value pairs. Therefore such
whitespace should be used with caution in new implementations.
10.2 Caching and HTTP/1.0
Some caches, such as those conforming to HTTP/1.0, will inevitably
cache the Set-Cookie header, because there was no mechanism to
suppress caching of headers prior to HTTP/1.1. This caching can lead
to security problems. Documents transmitted by an origin server
along with Set-Cookie headers will usually either be uncachable, or
will be "pre-expired". As long as caches obey instructions not to
cache documents (following Expires: <a date in the past> or Pragma:
no-cache (HTTP/1.0), or Cache-control: no-cache (HTTP/1.1))
uncachable documents present no problem. However, pre-expired
documents may be stored in caches. They require validation (a
conditional GET) on each new request, but some cache operators loosen
the rules for their caches, and sometimes serve expired documents
without first validating them. This combination of factors can lead
to cookies meant for one user later being sent to another user. The
Set-Cookie header is stored in the cache, and, although the document
is stale (expired), the cache returns the document in response to
later requests, including cached headers.
11. ACKNOWLEDGEMENTS
This document really represents the collective efforts of the
following people, in addition to the authors: Roy Fielding, Marc
Hedlund, Ted Hardie, Koen Holtman, Shel Kaphan, Rohit Khare.
rfc/rfc2965.txt view on Meta::CPAN
The IESG notes that this mechanism makes use of the .local top-level
domain (TLD) internally when handling host names that don't contain
any dots, and that this mechanism might not work in the expected way
should an actual .local TLD ever be registered.
Abstract
This document specifies a way to create a stateful session with
Hypertext Transfer Protocol (HTTP) requests and responses. It
describes three new headers, Cookie, Cookie2, and Set-Cookie2, which
carry state information between participating origin servers and user
agents. The method described here differs from Netscape's Cookie
proposal [Netscape], but it can interoperate with HTTP/1.0 user
agents that use Netscape's method. (See the HISTORICAL section.)
This document reflects implementation experience with RFC 2109 and
obsoletes it.
1. TERMINOLOGY
The terms user agent, client, server, proxy, origin server, and
http_URL have the same meaning as in the HTTP/1.1 specification
rfc/rfc2965.txt view on Meta::CPAN
The term effective host name is related to host name. If a host name
contains no dots, the effective host name is that name with the
string .local appended to it. Otherwise the effective host name is
the same as the host name. Note that all effective host names
contain at least one dot.
The term request-port refers to the port portion of the absoluteURI
(http_URL) of the HTTP request line. If the absoluteURI has no
explicit port, the request-port is the HTTP default, 80. The
request-port of a cookie is the request-port of the request in which
a Set-Cookie2 response header was returned to the user agent.
Host names can be specified either as an IP address or a HDN string.
Sometimes we compare one host name with another. (Such comparisons
SHALL be case-insensitive.) Host A's name domain-matches host B's if
* their host name strings string-compare equal; or
* A is a HDN string and has the form NB, where N is a non-empty
name string, B has the form .B', and B' is a HDN string. (So,
x.y.com domain-matches .Y.com but not Y.com.)
rfc/rfc2965.txt view on Meta::CPAN
3. DESCRIPTION
We describe here a way for an origin server to send state information
to the user agent, and for the user agent to return the state
information to the origin server. The goal is to have a minimal
impact on HTTP and user agents.
3.1 Syntax: General
The two state management headers, Set-Cookie2 and Cookie, have common
syntactic properties involving attribute-value pairs. The following
grammar uses the notation, and tokens DIGIT (decimal digits), token
Kristol & Montulli Standards Track [Page 3]
RFC 2965 HTTP State Management Mechanism October 2000
rfc/rfc2965.txt view on Meta::CPAN
permitted between tokens. Note that while the above syntax
description shows value as optional, most attrs require them.
NOTE: The syntax above allows whitespace between the attribute and
the = sign.
3.2 Origin Server Role
3.2.1 General The origin server initiates a session, if it so
desires. To do so, it returns an extra response header to the
client, Set-Cookie2. (The details follow later.)
A user agent returns a Cookie request header (see below) to the
origin server if it chooses to continue a session. The origin server
MAY ignore it or use it to determine the current state of the
session. It MAY send back to the client a Set-Cookie2 response
header with the same or different information, or it MAY send no
Set-Cookie2 header at all. The origin server effectively ends a
session by sending the client a Set-Cookie2 header with Max-Age=0.
Servers MAY return Set-Cookie2 response headers with any response.
User agents SHOULD send Cookie request headers, subject to other
rules detailed below, with every request.
An origin server MAY include multiple Set-Cookie2 headers in a
response. Note that an intervening gateway could fold multiple such
headers into a single header.
rfc/rfc2965.txt view on Meta::CPAN
Kristol & Montulli Standards Track [Page 4]
RFC 2965 HTTP State Management Mechanism October 2000
3.2.2 Set-Cookie2 Syntax The syntax for the Set-Cookie2 response
header is
set-cookie = "Set-Cookie2:" cookies
cookies = 1#cookie
cookie = NAME "=" VALUE *(";" set-cookie-av)
NAME = attr
VALUE = value
set-cookie-av = "Comment" "=" value
| "CommentURL" "=" <"> http_URL <">
| "Discard"
| "Domain" "=" value
| "Max-Age" "=" value
| "Path" "=" value
| "Port" [ "=" <"> portlist <"> ]
| "Secure"
| "Version" "=" 1*DIGIT
portlist = 1#portnum
portnum = 1*DIGIT
Informally, the Set-Cookie2 response header comprises the token Set-
Cookie2:, followed by a comma-separated list of one or more cookies.
Each cookie begins with a NAME=VALUE pair, followed by zero or more
semi-colon-separated attribute-value pairs. The syntax for
attribute-value pairs was shown earlier. The specific attributes and
the semantics of their values follows. The NAME=VALUE attribute-
value pair MUST come first in each cookie. The others, if present,
can occur in any order. If an attribute appears more than once in a
cookie, the client SHALL use only the value associated with the first
appearance of the attribute; a client MUST ignore values after the
first.
The NAME of a cookie MAY be the same as one of the attributes in this
specification. However, because the cookie's NAME must come first in
a Set-Cookie2 response header, the NAME and its VALUE cannot be
confused with an attribute-value pair.
NAME=VALUE
REQUIRED. The name of the state information ("cookie") is NAME,
and its value is VALUE. NAMEs that begin with $ are reserved and
MUST NOT be used by applications.
The VALUE is opaque to the user agent and may be anything the
origin server chooses to send, possibly in a server-selected
printable ASCII encoding. "Opaque" implies that the content is of
interest and relevance only to the origin server. The content
may, in fact, be readable by anyone that examines the Set-Cookie2
header.
Kristol & Montulli Standards Track [Page 5]
RFC 2965 HTTP State Management Mechanism October 2000
Comment=value
rfc/rfc2965.txt view on Meta::CPAN
greater than delta-seconds seconds, the client SHOULD discard the
cookie. A value of zero means the cookie SHOULD be discarded
immediately.
Path=value
OPTIONAL. The value of the Path attribute specifies the subset of
URLs on the origin server to which this cookie applies.
Port[="portlist"]
OPTIONAL. The Port attribute restricts the port to which a cookie
may be returned in a Cookie request header. Note that the syntax
REQUIREs quotes around the OPTIONAL portlist even if there is only
one portnum in portlist.
rfc/rfc2965.txt view on Meta::CPAN
from the server.
Version=value
REQUIRED. The value of the Version attribute, a decimal integer,
identifies the version of the state management specification to
which the cookie conforms. For this specification, Version=1
applies.
3.2.3 Controlling Caching An origin server must be cognizant of the
effect of possible caching of both the returned resource and the
Set-Cookie2 header. Caching "public" documents is desirable. For
example, if the origin server wants to use a public document such as
a "front door" page as a sentinel to indicate the beginning of a
session for which a Set-Cookie2 response header must be generated,
the page SHOULD be stored in caches "pre-expired" so that the origin
server will see further requests. "Private documents", for example
those that contain information strictly private to a session, SHOULD
NOT be cached in shared caches.
If the cookie is intended for use by a single user, the Set-Cookie2
header SHOULD NOT be cached. A Set-Cookie2 header that is intended
to be shared by multiple users MAY be cached.
The origin server SHOULD send the following additional HTTP/1.1
response headers, depending on circumstances:
* To suppress caching of the Set-Cookie2 header:
Cache-control: no-cache="set-cookie2"
and one of the following:
* To suppress caching of a private document in shared caches:
Cache-control: private
rfc/rfc2965.txt view on Meta::CPAN
Cache-Control: proxy-revalidate, max-age=0
* To allow caching of a document and request that it be validated
before returning it to the client (by "pre-expiring" it):
Cache-control: max-age=0
Not all caches will revalidate the document in every case.
HTTP/1.1 servers MUST send Expires: old-date (where old-date is a
date long in the past) on responses containing Set-Cookie2 response
headers unless they know for certain (by out of band means) that
there are no HTTP/1.0 proxies in the response chain. HTTP/1.1
servers MAY send other Cache-Control directives that permit caching
by HTTP/1.1 proxies in addition to the Expires: old-date directive;
the Cache-Control directive will override the Expires: old-date for
HTTP/1.1 proxies.
3.3 User Agent Role
3.3.1 Interpreting Set-Cookie2 The user agent keeps separate track
of state information that arrives via Set-Cookie2 response headers
from each origin server (as distinguished by name or IP address and
port). The user agent MUST ignore attribute-value pairs whose
attribute it does not recognize. The user agent applies these
defaults for optional attributes that are missing:
Discard The default behavior is dictated by the presence or absence
of a Max-Age attribute.
Domain Defaults to the effective request-host. (Note that because
there is no dot at the beginning of effective request-host,
the default Domain can only domain-match itself.)
Max-Age The default behavior is to discard the cookie when the user
agent exits.
Path Defaults to the path of the request URL that generated the
Set-Cookie2 response, up to and including the right-most /.
Kristol & Montulli Standards Track [Page 8]
RFC 2965 HTTP State Management Mechanism October 2000
Port The default behavior is that a cookie MAY be returned to any
request-port.
Secure If absent, the user agent MAY send the cookie over an
insecure channel.
3.3.2 Rejecting Cookies To prevent possible security or privacy
violations, a user agent rejects a cookie according to rules below.
The goal of the rules is to try to limit the set of servers for which
a cookie is valid, based on the values of the Path, Domain, and Port
attributes and the request-URI, request-host and request-port.
A user agent rejects (SHALL NOT store its information) if the Version
attribute is missing. Moreover, a user agent rejects (SHALL NOT
store its information) if any of the following is true of the
attributes explicitly present in the Set-Cookie2 response header:
* The value for the Path attribute is not a prefix of the
request-URI.
* The value for the Domain attribute contains no embedded dots,
and the value is not .local.
* The effective host name that derives from the request-host does
not domain-match the Domain attribute.
* The request-host is a HDN (not IP address) and has the form HD,
where D is the value of the Domain attribute, and H is a string
that contains one or more dots.
* The Port attribute has a "port-list", and the request-port was
not in the list.
Examples:
* A Set-Cookie2 from request-host y.x.foo.com for Domain=.foo.com
would be rejected, because H is y.x and contains a dot.
* A Set-Cookie2 from request-host x.foo.com for Domain=.foo.com
would be accepted.
* A Set-Cookie2 with Domain=.com or Domain=.com., will always be
rejected, because there is no embedded dot.
* A Set-Cookie2 with Domain=ajax.com will be accepted, and the
value for Domain will be taken to be .ajax.com, because a dot
gets prepended to the value.
Kristol & Montulli Standards Track [Page 9]
RFC 2965 HTTP State Management Mechanism October 2000
* A Set-Cookie2 with Port="80,8000" will be accepted if the
request was made to port 80 or 8000 and will be rejected
otherwise.
* A Set-Cookie2 from request-host example for Domain=.local will
be accepted, because the effective host name for the request-
host is example.local, and example.local domain-matches .local.
3.3.3 Cookie Management If a user agent receives a Set-Cookie2
response header whose NAME is the same as that of a cookie it has
previously stored, the new cookie supersedes the old when: the old
and new Domain attribute values compare equal, using a case-
insensitive string-compare; and, the old and new Path attribute
values string-compare equal (case-sensitive). However, if the Set-
Cookie2 has a value for Max-Age of zero, the (old and new) cookie is
discarded. Otherwise a cookie persists (resources permitting) until
whichever happens first, then gets discarded: its Max-Age lifetime is
exceeded; or, if the Discard attribute is set, the user agent
terminates the session.
Because user agents have finite space in which to store cookies, they
MAY also discard older cookies to make space for newer ones, using,
for example, a least-recently-used algorithm, along with constraints
on the maximum number of cookies that each origin server may set.
If a Set-Cookie2 response header includes a Comment attribute, the
user agent SHOULD store that information in a human-readable form
with the cookie and SHOULD display the comment text as part of a
cookie inspection user interface.
If a Set-Cookie2 response header includes a CommentURL attribute, the
user agent SHOULD store that information in a human-readable form
with the cookie, or, preferably, SHOULD allow the user to follow the
http_URL link as part of a cookie inspection user interface.
The cookie inspection user interface may include a facility whereby a
user can decide, at the time the user agent receives the Set-Cookie2
response header, whether or not to accept the cookie. A potentially
confusing situation could arise if the following sequence occurs:
* the user agent receives a cookie that contains a CommentURL
attribute;
* the user agent's cookie inspection interface is configured so
that it presents a dialog to the user before the user agent
accepts the cookie;
rfc/rfc2965.txt view on Meta::CPAN
function as a "preferences file" for network applications, and a user
may wish to keep it even if it is the least-recently-used cookie. One
possible implementation would be an interface that allows the
permanent storage of a cookie through a checkbox (or, conversely, its
immediate destruction).
Privacy considerations dictate that the user have considerable
control over cookie management. The PRIVACY section contains more
information.
3.3.4 Sending Cookies to the Origin Server When it sends a request
to an origin server, the user agent includes a Cookie request header
if it has stored cookies that are applicable to the request, based on
* the request-host and request-port;
* the request-URI;
* the cookie's age.
The syntax for the header is:
cookie = "Cookie:" cookie-version 1*((";" | ",") cookie-value)
cookie-value = NAME "=" VALUE [";" path] [";" domain] [";" port]
cookie-version = "$Version" "=" value
NAME = attr
VALUE = value
path = "$Path" "=" value
domain = "$Domain" "=" value
port = "$Port" [ "=" <"> value <"> ]
The value of the cookie-version attribute MUST be the value from the
Version attribute of the corresponding Set-Cookie2 response header.
Otherwise the value for cookie-version is 0. The value for the path
Kristol & Montulli Standards Track [Page 11]
RFC 2965 HTTP State Management Mechanism October 2000
attribute MUST be the value from the Path attribute, if one was
present, of the corresponding Set-Cookie2 response header. Otherwise
the attribute SHOULD be omitted from the Cookie request header. The
value for the domain attribute MUST be the value from the Domain
attribute, if one was present, of the corresponding Set-Cookie2
response header. Otherwise the attribute SHOULD be omitted from the
Cookie request header.
The port attribute of the Cookie request header MUST mirror the Port
attribute, if one was present, in the corresponding Set-Cookie2
response header. That is, the port attribute MUST be present if the
Port attribute was present in the Set-Cookie2 header, and it MUST
have the same value, if any. Otherwise, if the Port attribute was
absent from the Set-Cookie2 header, the attribute likewise MUST be
omitted from the Cookie request header.
Note that there is neither a Comment nor a CommentURL attribute in
the Cookie request header corresponding to the ones in the Set-
Cookie2 response header. The user agent does not return the comment
information to the origin server.
The user agent applies the following rules to choose applicable
cookie-values to send in Cookie request headers from among all the
cookies it has received.
Domain Selection
The origin server's effective host name MUST domain-match the
Domain attribute of the cookie.
Port Selection
There are three possible behaviors, depending on the Port
attribute in the Set-Cookie2 response header:
1. By default (no Port attribute), the cookie MAY be sent to any
port.
2. If the attribute is present but has no value (e.g., Port), the
cookie MUST only be sent to the request-port it was received
from.
3. If the attribute has a port-list, the cookie MUST only be
returned if the new request-port is one of those listed in
rfc/rfc2965.txt view on Meta::CPAN
Kristol & Montulli Standards Track [Page 12]
RFC 2965 HTTP State Management Mechanism October 2000
Max-Age Selection
Cookies that have expired should have been discarded and thus are
not forwarded to an origin server.
If multiple cookies satisfy the criteria above, they are ordered in
the Cookie header such that those with more specific Path attributes
precede those with less specific. Ordering with respect to other
attributes (e.g., Domain) is unspecified.
Note: For backward compatibility, the separator in the Cookie header
is semi-colon (;) everywhere. A server SHOULD also accept comma (,)
as the separator between cookie-values for future compatibility.
3.3.5 Identifying What Version is Understood: Cookie2 The Cookie2
request header facilitates interoperation between clients and servers
that understand different versions of the cookie specification. When
the client sends one or more cookies to an origin server, if at least
one of those cookies contains a $Version attribute whose value is
different from the version that the client understands, then the
client MUST also send a Cookie2 request header, the syntax for which
is
cookie2 = "Cookie2:" cookie-version
Here the value for cookie-version is the highest version of cookie
specification (currently 1) that the client understands. The client
needs to send at most one such request header per request.
3.3.6 Sending Cookies in Unverifiable Transactions Users MUST have
control over sessions in order to ensure privacy. (See PRIVACY
section below.) To simplify implementation and to prevent an
additional layer of complexity where adequate safeguards exist,
however, this document distinguishes between transactions that are
verifiable and those that are unverifiable. A transaction is
verifiable if the user, or a user-designated agent, has the option to
review the request-URI prior to its use in the transaction. A
transaction is unverifiable if the user does not have that option.
Unverifiable transactions typically arise when a user agent
automatically requests inlined or embedded entities or when it
rfc/rfc2965.txt view on Meta::CPAN
button.) However, even this would not make all links verifiable; for
example, links to automatically loaded images would not normally be
subject to "mouse pointer" verification.
Many user agents also provide the option for a user to view the HTML
source of a document, or to save the source to an external file where
it can be viewed by another application. While such an option does
provide a crude review mechanism, some users might not consider it
acceptable for this purpose.
3.4 How an Origin Server Interprets the Cookie Header
A user agent returns much of the information in the Set-Cookie2
header to the origin server when the request-URI path-matches the
Path attribute of the cookie. When it receives a Cookie header, the
origin server SHOULD treat cookies with NAMEs whose prefix is $
specially, as an attribute for the cookie.
rfc/rfc2965.txt view on Meta::CPAN
3.5 Caching Proxy Role
One reason for separating state information from both a URL and
document content is to facilitate the scaling that caching permits.
To support cookies, a caching proxy MUST obey these rules already in
the HTTP specification:
* Honor requests from the cache, if possible, based on cache
validity rules.
* Pass along a Cookie request header in any request that the
proxy must make of another server.
* Return the response to the client. Include any Set-Cookie2
response header.
* Cache the received response subject to the control of the usual
headers, such as Expires,
Cache-control: no-cache
and
Cache-control: private
* Cache the Set-Cookie2 subject to the control of the usual
header,
Cache-control: no-cache="set-cookie2"
(The Set-Cookie2 header should usually not be cached.)
Proxies MUST NOT introduce Set-Cookie2 (Cookie) headers of their own
in proxy responses (requests).
4. EXAMPLES
4.1 Example 1
Most detail of request and response headers has been omitted. Assume
the user agent has no stored cookies.
1. User Agent -> Server
rfc/rfc2965.txt view on Meta::CPAN
Kristol & Montulli Standards Track [Page 15]
RFC 2965 HTTP State Management Mechanism October 2000
2. Server -> User Agent
HTTP/1.1 200 OK
Set-Cookie2: Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"
Cookie reflects user's identity.
3. User Agent -> Server
POST /acme/pickitem HTTP/1.1
Cookie: $Version="1"; Customer="WILE_E_COYOTE"; $Path="/acme"
[form data]
User selects an item for "shopping basket".
4. Server -> User Agent
HTTP/1.1 200 OK
Set-Cookie2: Part_Number="Rocket_Launcher_0001"; Version="1";
Path="/acme"
Shopping basket contains an item.
5. User Agent -> Server
POST /acme/shipping HTTP/1.1
Cookie: $Version="1";
Customer="WILE_E_COYOTE"; $Path="/acme";
Part_Number="Rocket_Launcher_0001"; $Path="/acme"
[form data]
User selects shipping method from form.
6. Server -> User Agent
HTTP/1.1 200 OK
Set-Cookie2: Shipping="FedEx"; Version="1"; Path="/acme"
New cookie reflects shipping method.
7. User Agent -> Server
POST /acme/process HTTP/1.1
Cookie: $Version="1";
Customer="WILE_E_COYOTE"; $Path="/acme";
Part_Number="Rocket_Launcher_0001"; $Path="/acme";
Shipping="FedEx"; $Path="/acme"
[form data]
Kristol & Montulli Standards Track [Page 16]
RFC 2965 HTTP State Management Mechanism October 2000
rfc/rfc2965.txt view on Meta::CPAN
4.2 Example 2
This example illustrates the effect of the Path attribute. All
detail of request and response headers has been omitted. Assume the
user agent has no stored cookies.
Imagine the user agent has received, in response to earlier requests,
the response headers
Set-Cookie2: Part_Number="Rocket_Launcher_0001"; Version="1";
Path="/acme"
and
Set-Cookie2: Part_Number="Riding_Rocket_0023"; Version="1";
Path="/acme/ammo"
A subsequent request by the user agent to the (same) server for URLs
of the form /acme/ammo/... would include the following request
header:
Cookie: $Version="1";
Part_Number="Riding_Rocket_0023"; $Path="/acme/ammo";
Part_Number="Rocket_Launcher_0001"; $Path="/acme"
Note that the NAME=VALUE pair for the cookie with the more specific
Path attribute, /acme/ammo, comes before the one with the less
specific Path attribute, /acme. Further note that the same cookie
name appears more than once.
A subsequent request by the user agent to the (same) server for a URL
of the form /acme/parts/ would include the following request header:
Kristol & Montulli Standards Track [Page 17]
RFC 2965 HTTP State Management Mechanism October 2000
Cookie: $Version="1"; Part_Number="Rocket_Launcher_0001";
$Path="/acme"
Here, the second cookie's Path attribute /acme/ammo is not a prefix
of the request URL, /acme/parts/, so the cookie does not get
forwarded to the server.
5. IMPLEMENTATION CONSIDERATIONS
Here we provide guidance on likely or desirable details for an origin
server that implements state management.
5.1 Set-Cookie2 Content
An origin server's content should probably be divided into disjoint
application areas, some of which require the use of state
information. The application areas can be distinguished by their
request URLs. The Set-Cookie2 header can incorporate information
about the application areas by setting the Path attribute for each
one.
The session information can obviously be clear or encoded text that
describes state. However, if it grows too large, it can become
unwieldy. Therefore, an implementor might choose for the session
information to be a key to a server-side resource. Of course, using
a database creates some problems that this state management
specification was meant to avoid, namely:
rfc/rfc2965.txt view on Meta::CPAN
size of cookies that they can store. In general, user agents' cookie
support should have no fixed limits. They should strive to store as
many frequently-used cookies as possible. Furthermore, general-use
user agents SHOULD provide each of the following minimum capabilities
individually, although not necessarily simultaneously:
* at least 300 cookies
* at least 4096 bytes per cookie (as measured by the characters
that comprise the cookie non-terminal in the syntax description
of the Set-Cookie2 header, and as received in the Set-Cookie2
header)
* at least 20 cookies per unique host or domain name
User agents created for specific purposes or for limited-capacity
devices SHOULD provide at least 20 cookies of 4096 bytes, to ensure
that the user can interact with a session-based origin server.
The information in a Set-Cookie2 response header MUST be retained in
its entirety. If for some reason there is inadequate space to store
the cookie, it MUST be discarded, not truncated.
Applications should use as few and as small cookies as possible, and
they should cope gracefully with the loss of a cookie.
5.3.1 Denial of Service Attacks User agents MAY choose to set an
upper bound on the number of cookies to be stored from a given host
or domain name or on the size of the cookie information. Otherwise a
malicious server could attempt to flood a user agent with many
rfc/rfc2965.txt view on Meta::CPAN
Kristol & Montulli Standards Track [Page 19]
RFC 2965 HTTP State Management Mechanism October 2000
6.1 User Agent Control
An origin server could create a Set-Cookie2 header to track the path
of a user through the server. Users may object to this behavior as
an intrusive accumulation of information, even if their identity is
not evident. (Identity might become evident, for example, if a user
subsequently fills out a form that contains identifying information.)
This state management specification therefore requires that a user
agent give the user control over such a possible intrusion, although
the interface through which the user is given this control is left
unspecified. However, the control mechanisms provided SHALL at least
allow the user
rfc/rfc2965.txt view on Meta::CPAN
progress.
* to let the user decide which cookies, if any, should be saved
when the user concludes a window or user agent session.
* to let the user examine and delete the contents of a cookie at
any time.
A user agent usually begins execution with no remembered state
information. It SHOULD be possible to configure a user agent never
to send Cookie headers, in which case it can never sustain state with
an origin server. (The user agent would then behave like one that is
unaware of how to handle Set-Cookie2 response headers.)
When the user agent terminates execution, it SHOULD let the user
discard all state information. Alternatively, the user agent MAY ask
the user whether state information should be retained; the default
should be "no". If the user chooses to retain state information, it
would be restored the next time the user agent runs.
rfc/rfc2965.txt view on Meta::CPAN
6.2 Origin Server Role
An origin server SHOULD promote informed consent by adding CommentURL
or Comment information to the cookies it sends. CommentURL is
preferred because of the opportunity to provide richer information in
a multiplicity of languages.
6.3 Clear Text
The information in the Set-Cookie2 and Cookie headers is unprotected.
As a consequence:
1. Any sensitive information that is conveyed in them is exposed
to intruders.
2. A malicious intermediary could alter the headers as they travel
in either direction, with unpredictable results.
These facts imply that information of a personal and/or financial
nature should only be sent over a secure channel. For less sensitive
information, or when the content of the header is a database key, an
origin server should be vigilant to prevent a bad Cookie value from
causing failures.
A user agent in a shared user environment poses a further risk.
Using a cookie inspection interface, User B could examine the
contents of cookies that were saved when User A used the machine.
7. SECURITY CONSIDERATIONS
7.1 Protocol Design
rfc/rfc2965.txt view on Meta::CPAN
to the request-URI.
Kristol & Montulli Standards Track [Page 21]
RFC 2965 HTTP State Management Mechanism October 2000
7.2 Cookie Spoofing
Proper application design can avoid spoofing attacks from related
domains. Consider:
1. User agent makes request to victim.cracker.edu, gets back
cookie session_id="1234" and sets the default domain
victim.cracker.edu.
2. User agent makes request to spoof.cracker.edu, gets back cookie
session-id="1111", with Domain=".cracker.edu".
3. User agent makes request to victim.cracker.edu again, and
passes
Cookie: $Version="1"; session_id="1234",
$Version="1"; session_id="1111"; $Domain=".cracker.edu"
The server at victim.cracker.edu should detect that the second
cookie was not one it originated by noticing that the Domain
attribute is not for itself and ignore it.
7.3 Unexpected Cookie Sharing
A user agent SHOULD make every attempt to prevent the sharing of
session information between hosts that are in different domains.
Embedded or inlined objects may cause particularly severe privacy
problems if they can be used to share cookies between disparate
hosts. For example, a malicious server could embed cookie
information for host a.com in a URI for a CGI on host b.com. User
agent implementors are strongly encouraged to prevent this sort of
exchange whenever possible.
7.4 Cookies For Account Information
While it is common practice to use them this way, cookies are not
designed or intended to be used to hold authentication information,
such as account names and passwords. Unless such cookies are
exchanged over an encrypted path, the account information they
contain is highly vulnerable to perusal and theft.
8. OTHER, SIMILAR, PROPOSALS
Apart from RFC 2109, three other proposals have been made to
accomplish similar goals. This specification began as an amalgam of
Kristol's State-Info proposal [DMK95] and Netscape's Cookie proposal
[Netscape].
Kristol & Montulli Standards Track [Page 22]
RFC 2965 HTTP State Management Mechanism October 2000
Brian Behlendorf proposed a Session-ID header that would be user-
agent-initiated and could be used by an origin server to track
"clicktrails". It would not carry any origin-server-defined state,
however. Phillip Hallam-Baker has proposed another client-defined
session ID mechanism for similar purposes.
While both session IDs and cookies can provide a way to sustain
stateful sessions, their intended purpose is different, and,
consequently, the privacy requirements for them are different. A
user initiates session IDs to allow servers to track progress through
them, or to distinguish multiple users on a shared machine. Cookies
are server-initiated, so the cookie mechanism described here gives
users control over something that would otherwise take place without
the users' awareness. Furthermore, cookies convey rich, server-
selected information, whereas session IDs comprise user-selected,
simple information.
9. HISTORICAL
9.1 Compatibility with Existing Implementations
Existing cookie implementations, based on the Netscape specification,
use the Set-Cookie (not Set-Cookie2) header. User agents that
receive in the same response both a Set-Cookie and Set-Cookie2
response header for the same cookie MUST discard the Set-Cookie
information and use only the Set-Cookie2 information. Furthermore, a
user agent MUST assume, if it received a Set-Cookie2 response header,
that the sending server complies with this document and will
understand Cookie request headers that also follow this
specification.
New cookies MUST replace both equivalent old- and new-style cookies.
That is, if a user agent that follows both this specification and
Netscape's original specification receives a Set-Cookie2 response
header, and the NAME and the Domain and Path attributes match (per
the Cookie Management section) a Netscape-style cookie, the
Netscape-style cookie MUST be discarded, and the user agent MUST
retain only the cookie adhering to this specification.
Older user agents that do not understand this specification, but that
do understand Netscape's original specification, will not recognize
the Set-Cookie2 response header and will receive and send cookies
according to the older specification.
Kristol & Montulli Standards Track [Page 23]
RFC 2965 HTTP State Management Mechanism October 2000
A user agent that supports both this specification and Netscape-style
cookies SHOULD send a Cookie request header that follows the older
Netscape specification if it received the cookie in a Set-Cookie
response header and not in a Set-Cookie2 response header. However,
it SHOULD send the following request header as well:
Cookie2: $Version="1"
The Cookie2 header advises the server that the user agent understands
new-style cookies. If the server understands new-style cookies, as
well, it SHOULD continue the stateful session by sending a Set-
Cookie2 response header, rather than Set-Cookie. A server that does
not understand new-style cookies will simply ignore the Cookie2
request header.
9.2 Caching and HTTP/1.0
Some caches, such as those conforming to HTTP/1.0, will inevitably
cache the Set-Cookie2 and Set-Cookie headers, because there was no
mechanism to suppress caching of headers prior to HTTP/1.1. This
caching can lead to security problems. Documents transmitted by an
origin server along with Set-Cookie2 and Set-Cookie headers usually
either will be uncachable, or will be "pre-expired". As long as
caches obey instructions not to cache documents (following Expires:
<a date in the past> or Pragma: no-cache (HTTP/1.0), or Cache-
control: no-cache (HTTP/1.1)) uncachable documents present no
problem. However, pre-expired documents may be stored in caches.
They require validation (a conditional GET) on each new request, but
some cache operators loosen the rules for their caches, and sometimes
serve expired documents without first validating them. This
combination of factors can lead to cookies meant for one user later
being sent to another user. The Set-Cookie2 and Set-Cookie headers
are stored in the cache, and, although the document is stale
(expired), the cache returns the document in response to later
requests, including cached headers.
10. ACKNOWLEDGEMENTS
This document really represents the collective efforts of the HTTP
Working Group of the IETF and, particularly, the following people, in
addition to the authors: Roy Fielding, Yaron Goland, Marc Hedlund,
Ted Hardie, Koen Holtman, Shel Kaphan, Rohit Khare, Foteos Macrides,
rfc/rfc2965.txt view on Meta::CPAN
Mountain View, CA 94301
EMail: lou@montulli.org
12. REFERENCES
[DMK95] Kristol, D.M., "Proposed HTTP State-Info Mechanism",
available at <http://portal.research.bell-
labs.com/~dmk/state-info.html>, September, 1995.
[Netscape] "Persistent Client State -- HTTP Cookies", available at
<http://www.netscape.com/newsref/std/cookie_spec.html>,
undated.
[RFC2109] Kristol, D. and L. Montulli, "HTTP State Management
Mechanism", RFC 2109, February 1997.
[RFC2119] Bradner, S., "Key words for use in RFCs to Indicate
Requirement Levels", BCP 14, RFC 2119, March 1997.
[RFC2279] Yergeau, F., "UTF-8, a transformation format of Unicode
#########################
# change 'tests => 1' to 'tests => last_test_to_print';
use Test;
BEGIN { plan tests => 1 };
use SecSess;
use SecSess::DBI;
use SecSess::Wrapper;
use SecSess::Cookie;
use SecSess::URL;
use SecSess::Cookie::BasicAuth;
use SecSess::Cookie::LoginForm;
use SecSess::Cookie::X509;
use SecSess::Cookie::X509PIN;
use SecSess::Cookie::URL;
use SecSess::URL::Cookie;
ok(1); # If we made it this far, we're ok.
#########################
# Insert your test code below, the Test module is use()ed here so read
# its man page ( perldoc Test ) for help writing this test script.