CGI::A...tegrity(3pm)

πŸ“¦
version 0.06 Β· 4 versions
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

πŸŽ€ CGI::A...tegrity(3pm) πŸŽ€

okay bestie, so this is the man page for CGI::Application::Plugin::LinkIntegrity (the manual itself goes by CGI::A...tegrity(3pm) β€” user contributed perl docs, you know how it is πŸ’…).


✨ NAME ✨

CGI::Application::Plugin::LinkIntegrity β€” Make tamper-resistent links in CGI::Application

🌸 VERSION 🌸

Version 0.06

πŸ¦‹ SYNOPSIS πŸ¦‹

So like, in your application:

use base 'CGI::Application';
use CGI::Application::Plugin::LinkIntegrity;

sub setup {
    my $self = shift;
    $self->link_integrity_config(
        secret => 'some secret string known only to you and me',
    );
}

sub account_info {
    my $self = shift;

    my $account_id = get_user_account_id();

    my $template = $self->load_tmpl('account.html');

    $template->param(
        'balance'    => $self->link("/account.cgi?rm=balance&acct_id=$account_id");
        'transfer'   => $self->link("/account.cgi?rm=transfer&acct_id=$account_id");
        'withdrawal' => $self->link("/account.cgi?rm=withdrawl&acct_id=$account_id");
    );
}

And then in your template:

<h1>Welcome to The Faceless Banking Corp.</h1>
<h3>Actions:</h3>
<br /><a href="<TMPL_VAR NAME="balance">">Show Balance</a>
<br /><a href="<TMPL_VAR NAME="transfer">">Make a Transfer</a>
<br /><a href="<TMPL_VAR NAME="withdrawal">">Get Cash</a>

Which sends this HTML to the browser, no cap:

<h1>Welcome to The Faceless Banking Corp.</h1>
<h3>Actions:</h3>
<br /><a href="/account.cgi?rm=balance&acct_id=73&_checksum=1d7c4b82d075785de04fa6b98b572691">Show Balance</a>
<br /><a href="/account.cgi?rm=transfer&acct_id=73&_checksum=d41d8cd98f00b204e9800998ecf8427e">Make a Transfer</a>
<br /><a href="/account.cgi?rm=withdrawl&acct_id=73&_checksum=3c5ad17bdeef3c4281abd39c6386cfd6">Get Cash</a>

The URLs created are now tamper-resistent. If the user changes "acct_id" from 73 to 74, the "_checksum" will not match, and the system will treat it as an intrusion attempt. 🚨 periodt.

If you use "Template::Toolkit|Template" or "HTML::Template::Plugin::Dot", you can pass the "CGI::Application" $self object into the template and call "link" and "self_link" directly from the template. In your app:

$template->param(
    'app'     => $self,
    'name'    => 'gordon',
    'email'   => 'gordon@example.com',
);

And in your template you can use:

# Template::Toolkit syntax
<a href="[% app.self_link('name', name, 'email', email %]">...</a>

# HTML::Template::Plugin::Dot syntax
<a href="<TMPL_VAR NAME="app.self_link('name', name, 'email', email">">...</a>

# Petal syntax
<a href="http://www.example.com"
   tal:attributes="href app/self_link('name', name, 'email', email)">...</a>
Note that in the parameters of the call to << link >>, items enclosed in quotes are treated as literal parameters and barewords are treated as template params. So 'email' is the literal string, and "email" is the template parameter named email (in this case 'gordon@example.com'). πŸ‘‘

πŸ’œ DESCRIPTION πŸ’œ

"CGI::Application::Plugin::LinkIntegrity" lets you create tamper-resistent links within your CGI::Application project. When you create an URL with "link", a "_checksum" is added to the URL:

my $link = $self->link("/account.cgi?rm=balance&acct_id=73");
print $link; # /account.cgi?rm=balance&acct_id=73&_checksum=1d7c4b82d075785de04fa6b98b572691

The checksum is a (cryptographic) hash of the URL, plus a secret string known only to the server. πŸ”βœ¨

If the user attempts to change part of the URL (e.g. a query string parameter, or the PATH_INFO), then the checksum will not match. The run mode will be changed to "link_tampered", and the "invalid_checksum" hook will be called.

You can define the "link_tampered" run mode yourself, or you can use the default "link_tampered" run mode built into CGI::Application::Plugin::LinkIntegrity.

You can disable link checking during development by passing a true value to the "disable" parameter of $self->link_integrity_config. πŸ™ˆ

πŸ’– METHODS πŸ’–

Ok bestie, this is the one where you set up the CGI::Application::Plugin::LinkIntegrity. Usually it just makes sense to do this in the setup method of your app's base class:

use CGI::Application::Plugin::LinkIntegrity;
use base 'CGI::Application';
package My::Project;

sub setup {
    my $self = shift;

    $self->run_modes(['bad_user_no_biscuit']);
    $self->link_integrity_config(
        secret                 => 'some secret string known only to you and me',
        link_tampered_run_mode => 'bad_user_no_biscuit',
        digest_module          => 'Digest::MD5',
        disable                => 1,
    );
}

Or like, you can totally pull this config info out of a config file instead. Say, with CGI::Application::Config::Context:

use CGI::Application::Plugin::LinkIntegrity;
use CGI::Application::Plugin::Config::Context;

use base 'CGI::Application';
package My::Project;

sub setup {
    my $self = shift;

    $self->conf->init(
        file   => 'app.conf',
        driver => 'ConfigGeneral',
    );

    my $config = $self->conf->context;

    $self->link_integrity_config(
        $config->{'LinkIntegrity'},
        additional_data => sub {
            my $self = shift;
            return $self->session->id;
        },
    );

    my $link_tampered_rm = $config->{'LinkIntegrity'}{'link_tampered_run_mode'} || 'link_tampered';

    $self->run_modes([$link_tampered_rm]);
}

And then in your config file you'd have:

<LinkIntegrity>
    secret                 = some REALLY secret string
    link_tampered_run_mode = bad_user_no_biscuit
    hash_algorithm         = SHA1
    disable                = 1
</LinkIntegrity>

This strategy is lowkey iconic because it lets you turn link checking on and off on the fly just by changing the value of "disable" in the config file. Chef's kiss. πŸ’…

So here's the tea on all the configuration parameters you can use:

secret πŸ”

A string that only your application knows. At a commandline you can generate a secret string with md5:

 $ perl -MDigest::MD5 -le"print Digest::MD5::md5_hex($$, time, rand(42));"

Or you can use Data::UUID:

 $ perl -MData::UUID -le"$ug = new Data::UUID; $uuid = $ug->create; print $ug->to_string($uuid)"
Bestie, listen. If someone knows your secret string, they can generate their own checksums on arbitrary data that will always pass the integrity check in your app. That's a Bad Thing, fr. So don't let other people know your secret string, and don't use the default secret string if you can help it. 🚨

additional_data 🧩

You can pass constant additional data to the checksum generator for every link.

    $self->link_integrity_config(
        secret          => 'really secret',
        additional_data => 'some other secret data',
    )

Like for instance, to stop one user from following a second user's link, you can add a user-specific component to the session, such as the user's session id:

    $self->link_integrity_config(
        secret          => 'really secret',
        additional_data => sub {
            my $self = shift;
            return $self->session->id;
        }
    )

You can pass a string instead of a subroutine. But in the case of the user's session, a subroutine is useful so that you get the value of the user's session at the time when the checksum is generated, not at the time when the link integrity system is configured. Timing matters, periodt. ⏰

checksum_param 🏷️

The name of the checksum parameter, which gets added to the query string and contains the cryptographic checksum of the link. By default, this parameter is named "_checksum".

The run mode to go to when it's been detected that the user has tampered with the link. The default is "link_tampered".

See "The link_tampered Run Mode", below. πŸ‘‡

digest_module πŸ§ͺ

Which digest module to use to create the checksum. Typically this will be either "Digest::MD5" or "Digest::SHA". However any module supported by "Digest::HMAC" will work.

The default "digest_module" is "Digest::MD5".

checksum_generator πŸ› οΈ

If you wanna provide a custom subroutine to make your own checksums, you can define your own subroutine to do it via the "make_checksum" param. Here's an example of one that uses Digest::SHA2:

        $self->link_integrity_config(
            checksum_generator => sub {
                my ($url, $secret) = @_;
                require Digest::SHA2;

                my $ctx = Digest::SHA2->new();
                $ctx->add($url . $secret);

                return $ctx->hexdigest;
            },
        );

disable 🚫

You can disable link checking entirely by setting "disable" to a true value. This can be useful when you're developing or debugging the application and you want the ability to tweak URL params without getting busted. Honestly? Real. πŸ™ˆ


Create a link, and add a checksum to it.

You can add parameters to the link directly in the URL:

    my $link = $self->link('/cgi-bin/app.cgi?var=value&var2=value2');

Or you can add them as a hash of parameters after the URL:

    my $link = $self->link(
        '/cgi-bin/app.cgi',
        'param1'  => 'value',
        'param2' => 'value2',
    );

Make a link to the current application, with optional parameters, and add a checksum to the URL.

    my $link = $self->self_link(
        'param1' => 'value1',
        'param2' => 'value2',
    );

"self_link" preserves the value of the current application's "PATH_INFO". For instance if the current URL is:

    /cgi-bin/app.cgi/some/path?foo=bar # PATH_INFO is 'some/path'

Calling:

    $self->self_link('bar' => 'baz');

Will produce the URL:

    /cgi-bin/app.cgi/some/path?bar=baz

If you want to remove the "PATH_INFO" value or replace it with a new value, use path_link. (that's the next one bestie, keep scrolling ✨)

Calling "path_link" is the same as calling "self_link", except the current value of "PATH_INFO" can be replaced.

    my $link = $self->path_link(
        '/new/path',
        'param1' => 'value1',
        'param2' => 'value2',
    );

For instance if the current URL is:

    /cgi-bin/app.cgi/some/path?foo=bar # PATH_INFO is 'some/path'

Calling:

    $self->path_link('/new/path');

Will produce the URL:

    /cgi-bin/app.cgi/new/path?foo=bar

If you want to remove "PATH_INFO" entirely, call one of the following:

    $self->path_link;
    $self->path_link(undef, 'param1' => 'val1', 'param2 => 'val2' ...);
    $self->path_link('', 'param1' => 'val1', 'param2 => 'val2' ...);

If you want to keep the existing "PATH_INFO" that was passed to the current application, use self_link instead. πŸ’–


🚦 RUN MODES 🚦

Your application gets redirected to this run mode when it's been detected that the user has tampered with the link. You can change the name of this run mode by changing the value of the "link_tampered_runmode" param to "link_integrity_config".

CGI::Application::Plugin::LinkIntegrity provides a default "link_tampered" run mode, which just displays a page with some stern warning text. Very demure, very "we saw what you did". πŸ‘€

You can define your own as follows:

    sub link_tampered {
        my $self = shift;
        my $template = $self->load_template('stern_talking_to');
        return $template->output;
    }

πŸͺ HOOKS πŸͺ

When a link is followed that doesn't match the checksum, the "invalid_checksum" hook is called. You can add a callback to this hook to do some cleanup such as deleting the user's session. For instance:

    sub setup {
        my $self = shift;
        $self->add_callback('invalid_checksum' => \&bad_user);
    }

    sub bad_user {
        my $self = shift;

        # The user has been messing with the URLs, possibly trying to
        # break into the system.  We don't tolerate this behaviour.
        # So we delete the user's session:

        $self->session->delete;
    }

πŸ‘‘ AUTHOR πŸ‘‘

Michael Graham, "<mag-perl@occamstoothbrush.com>"

🌈 ACKNOWLEDGEMENTS 🌈

This module was based on the checksum feature originally built into Richard Dice's CGI::Application::Framework. Giving credit where it's due, we love to see it. 🫢

πŸ’€ BUGS πŸ’€

Please report any bugs or feature requests to "bug-cgi-application-plugin-linkintegrity@rt.cpan.org", or through the web interface at <http://rt.cpan.org>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. So like, you'll literally never be left on read. 😌

Copyright 2005 Michael Graham, All Rights Reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


And that's the whole page bestie!! πŸŽ€ This was perl v5.34.0, dated 2022-06-09, and the page is CGI::A...tegrity(3pm) β€” you read the entire thing, I'm so proud of you, go take a lil nap, you earned it. πŸ’…βœ¨πŸ¦‹

πŸ“¦ where this page comes from