Making Wrong Code Type Wrong

--4OpS+d6oOtUQaRm1
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

JoelOnSoftware wrote an article I recently saw linked on perlmonks:

	http://www.joelonsoftware.com/articles/Wrong.html

The article discusses writing robust software, specifically by
dealing with data separation.

In my interpretation the article introduces a type system. This type
system helps write robust software, but has some limitations:

	* Type information is checked by the programmer
	* Full annotations must be supplied by the programmer
	* Lack of annotation is hard to detect

The system helps you separate data that has not been massaged for
a certain piece of code, from touching that code. The only way to
let that data reach the code is by using a filter that sanitizes it.

Joel uses 'Request("Foo")' to mean something akin to
$q->param("Foo") in CGI.pm land, and Write like 'print' (assuming an
HTML output).

His example shows how cross site scripting can arise, and how to use
the type system to avoid this problem.

The type system is implemented using coding standards: you tag
variable names, much like a tagged union. In his example, the union
type discusses data safety, and has two subtypes: safe and unsafe.

This relates very closely to tainting, but differs in one respect -
it's a static analysis. Tainting does the same thing with no user
annotation, at runtime, under very specific situation.

Perl 6 will need support for this kind of tainting, and I raised it
before, but now I would like to propose something else.

Let's look at Joel's code for a second:

	us =3D UsRequest("name")
	usName =3D us
	recordset("usName") =3D usName=20
	sName =3D SFromUs(recordset("usName"))
	WriteS sName

At the top, the 'us' annotations denote that Request will return an
unsafe value, and 'us' is an unsafe value. Then 'usName' is assigned
to it (in a far away piece of code, btw). The programmer knows that
'usName' cannot be named 'sName' because it's getting it's value
=66rom a variable that is also tagged with 'us'.

Later, the value is stored in a DB. When extracted from the DB, we
know the value is unsafe, because it is tagged as such. Then SFromUS
is like a complex casting operator, that makes something unsafe into
something safe. The naming convention is supposed to help the
programmer *see* when things go wrong.

In Perl 6 ideally this would look like this, IMHO:

	my $str =3D $q.param("name");
	...
	my $name =3D $str;
	$storage.store("name", $name);
	...
	my $name =3D $storage.get("name");
	print encode($name);

because type annotation sucks. Superficially, this code does not
have the property that both Joel and I want it to have - safety, but
I think this can be resolved.

Perl 6 has the notion of roles.

Let's say we were to decorate the param method of the http request
object, asking for a symbolic role to be attached to all the values
it returns.

What we want to get out of it is that in the scope of our code (the
lexical scope, the current class and it's subclasses, the consumers
of this module, etc etc), any retrieval of a param will tag the data
as unsafe, without param even knowing about this.

Then the view is also tagged - no data may enter the Template
namespace with this tag, or even more analy, for the scope that we
use Template, the only data we allow ourselves to put into it, is
something that is explicitly tagged as safe.

The implementation of this system is trivial with Perl 6's tools:
roles and compile time type inferrence allow the user to make a
system that gives the exact same features as Joel's system does by
wrapping interfaces.

However, what I'm more interested in is decorating existing
interfaces, in a limited scope.

The reason we want a limiting scope is that it is not our concern
how other pieces of code use $q.param safely or unsafely, with our
definition of safety or with someone else's definition of it.

What I'd like to be able to do is declare something that applies to
all code in my system (application, module, script, whatever) that
does this:

	my $str =3D $q.param("name");
	...
	my $name =3D $str;
	$storage.store("name", $name);
	...
	my $name =3D $storage.get("name");
	print encode($name);

and enables me to say that

	print $name;

is disallowed using the following rules:

	everything from $q.param is also of the type Unsafe

	everything going into $storage.store needs to get a callback
	triggered if it us unsafe (and more data about it will be stored
	in the DB).

	everything coming out of $storage.get must also trigger a
	callback, that will retag it as necessary.

	everything going into print must be of the type Safe

	the function encode has the type Unsafe -> Safe

Using these 5 rules I can then gain control over much larger bits of
code. The only question left unanswered is how do I say what code,
and what is the syntax for these decorations.

This tagging gets very interesting with his examples later on.
Here's an excert of Joel's article:

	In Excel's source code you see a lot of rw and col and when you see those
	you know that they refer to rows and columns. Yep, they're both integers,
	but it never makes sense to assign between them.

There is a real benefit to be gained here, but the usability of e.g. int
formatting functions should not be hindered by overzealous typing.

--=20
 ()  Yuval Kogman <nothingmuch@woobling.org> 0xEBD27418  perl hacker &
 /\  kung foo master: /me has realultimatepower.net: neeyah!!!!!!!!!!!!


--4OpS+d6oOtUQaRm1
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFDVUE3VCwRwOvSdBgRAr5gAJ9B5vZ8JTGddcWgDRFVYMzzEKf78wCgrTs0
64x/qS8Tz1Ikrq8AnhkAdWU=
=XFAF
-----END PGP SIGNATURE-----

--4OpS+d6oOtUQaRm1--
0
nothingmuch
10/18/2005 6:38:47 PM
perl.perl6.language 6841 articles. 0 followers. Follow

6 Replies
675 Views

Similar Articles

[PageSpeed] 59

Yuval Kogman skribis 2005-10-18 20:38 (+0200):
> 	the function encode has the type Unsafe -> Safe

I read the article before. What occurred to me then did so again now.
What exactly do Unsafe and Safe mean? Safe for *what*?

Something that is safe to put in HTML may be unsafe to put in an rfc822
header, and what may be safe there is likely to be unsafe in a shell
command line.

Instead of Safe and Unsafe, I suggest using safe::html, safe::rfc822,
safe::bash, etcetera instead of Safe, and nothing instead of Unsafe. If
it's not safe::($usage), then it's unsafe. Just like how something that
isn't defined() is undef, without there being any need for an
undefined() test.

One problem still is that once something is encoded, quoted or escaped
it can't always be easily re-encoded. Encoding functions should therefor
check if a variable does safe::(none()) and warn or fail if so.

I used lc class names, because they're empty roles, used only for
decoration and does-testing, and has no methods. I've thought about
suggesting such a convention, and this, I guess, is as good a time as
any.

Another possibility is to use Str types, and coercion for encoding. In
that case I suggest the "lit" operator that provides Str::Literal
context&coercion, which coerces to any other string type without
encoding.


Juerd
-- 
http://convolution.nl/maak_juerd_blij.html
http://convolution.nl/make_juerd_happy.html 
http://convolution.nl/gajigu_juerd_n.html
0
juerd
10/18/2005 7:04:02 PM
--ABYnUdqoGSokwVM+
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Oct 18, 2005 at 21:04:02 +0200, Juerd wrote:
> Yuval Kogman skribis 2005-10-18 20:38 (+0200):
> > 	the function encode has the type Unsafe -> Safe
>=20
> I read the article before. What occurred to me then did so again now.
> What exactly do Unsafe and Safe mean? Safe for *what*?

That was just a naive example - the words "Unsafe" and "Safe" are
user defined, and are chosen on a case by case basis in their app.

> One problem still is that once something is encoded, quoted or escaped
> it can't always be easily re-encoded. Encoding functions should therefor
> check if a variable does safe::(none()) and warn or fail if so.

I don't see how this relates to the OP, or why encoding functions
should implement it like this.

--=20
 ()  Yuval Kogman <nothingmuch@woobling.org> 0xEBD27418  perl hacker &
 /\  kung foo master: /me sneaks up from another MIME part: neeyah!!!!!


--ABYnUdqoGSokwVM+
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFDVUt8VCwRwOvSdBgRAiCUAKCsqXeV8C4/cGJN5v6PlgmNiyAG5ACfbT5F
V8ncXN8j59lXo9lOOnGC2K4=
=ubGV
-----END PGP SIGNATURE-----

--ABYnUdqoGSokwVM+--
0
nothingmuch
10/18/2005 7:22:37 PM
Yuval Kogman skribis 2005-10-18 21:22 (+0200):
> > I read the article before. What occurred to me then did so again now.
> > What exactly do Unsafe and Safe mean? Safe for *what*?
> That was just a naive example - the words "Unsafe" and "Safe" are
> user defined, and are chosen on a case by case basis in their app.

I think there's a lot to be gained by implementing something like this
globally, consistently. CPAN is part of Perl, as far as I'm concerned.

> > One problem still is that once something is encoded, quoted or escaped
> > it can't always be easily re-encoded. Encoding functions should therefor
> > check if a variable does safe::(none()) and warn or fail if so.
> I don't see how this relates to the OP, or why encoding functions
> should implement it like this.

The "should" is not to be taken literally, and applies only to the
described hypothetical universe.


Juerd
-- 
http://convolution.nl/maak_juerd_blij.html
http://convolution.nl/make_juerd_happy.html 
http://convolution.nl/gajigu_juerd_n.html
0
juerd
10/18/2005 7:43:57 PM
[snip]

Let me rephrase to see if I understand you - you like the fact that
boxed types + roles applied to those types + compile-time type
checking/inference allows you to tag a piece of information (int,
char, string, obj, whatever) with arbitrary metadata. Add that to the
fact that you can lexically mark certain function signatures as
checking against said arbitary metadata and you can provide
taint-checking to an arbitrary complexity.

Yeah, that's cool. :-)

Rob
0
rob
10/18/2005 8:50:08 PM
--/NwG7NuG0/W8LcLh
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Oct 18, 2005 at 21:43:57 +0200, Juerd wrote:
> > That was just a naive example - the words "Unsafe" and "Safe" are
> > user defined, and are chosen on a case by case basis in their app.
>=20
> I think there's a lot to be gained by implementing something like this
> globally, consistently. CPAN is part of Perl, as far as I'm concerned.

While I agree that there is something to be gained from
semi-standard roles that allow modules to share compatible
interfaces (for example, imagine that Storable, Data::Dumper both do
the Serializable role, which is an interface spec jointly maintained
by their authors), I think that the power of the paradgim I proposed
is actually in non-shared code - things that apply to your app, and
are hard to reuse except for similar deployments.

The reason for my opinion is while an HTML sanitizer knows that it
takes any arbitrary string, and returns a string that has no
dangerous tags, and will not mess with the structure of the
document, it doesn't know what is the origin or your data, or what
is the destination of it's output.

This amendment to the type system is supposed to help you make sure
your glue code is glueing the right parts together, and while
components are generally reusable, composed components are scarcely
so.

> > I don't see how this relates to the OP, or why encoding functions
> > should implement it like this.
>=20
> The "should" is not to be taken literally, and applies only to the
> described hypothetical universe.

Huh?

--=20
 ()  Yuval Kogman <nothingmuch@woobling.org> 0xEBD27418  perl hacker &
 /\  kung foo master: /me does a karate-chop-flip: neeyah!!!!!!!!!!!!!!


--/NwG7NuG0/W8LcLh
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFDVZfFVCwRwOvSdBgRArGQAJ96UjyacJSPW3Vc7+6hvpw3HWLpJACfeTit
VirtBkmTKDVsCv0+GicADsk=
=X4Un
-----END PGP SIGNATURE-----

--/NwG7NuG0/W8LcLh--
0
nothingmuch
10/19/2005 12:48:05 AM
--aX6oBa4COn3eIhlv
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Wed, Oct 19, 2005 at 02:48:05 +0200, Yuval Kogman wrote:

> the Serializable role, which is an interface spec jointly maintained

Err, I meant the Serializer role... The Serializable role is a role
that takes a delegate that does Serializer, and lets the object that
does it be frozen and thawed.

--=20
 ()  Yuval Kogman <nothingmuch@woobling.org> 0xEBD27418  perl hacker &
 /\  kung foo master: /me tips over a cow: neeyah!!!!!!!!!!!!!!!!!!!!!!


--aX6oBa4COn3eIhlv
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQFDVZmLVCwRwOvSdBgRAhSSAJ45uOqE+ALtAwNbwJLEf+1dwKa4KACfXIBo
Pab1YhBYYEIfx1pVBvmFAEA=
=sEX7
-----END PGP SIGNATURE-----

--aX6oBa4COn3eIhlv--
0
nothingmuch
10/19/2005 12:55:39 AM
Reply:

Similar Artilces:

WRONG WRONG WRONG
Name: ROZ mandelcorn Email: thunderstaratearthlinkdotnet Product: Firefox Summary: WRONG WRONG WRONG Comments: as a long-time user, first of netscape and, mozilla firefox, i must say i DO NOT LIKE THE PLACEMENT of TABS in version 4. nor do i like the whole rearrangement of the upper/navigation portion of firefox. I NEED/WANT MY TABS DIRECTLY ABOVE MY WINDOWS AS IT IS NOW....NOT ON TOP OF THE BROWSER. I WANT MY FILE-EDIT-ETC-MENU on TOP. ETC. AT LEAST GIVE US THE CHOICE AS TO WHICH FORMAT WE WANT....CAN YOU SAY CUSTOMIZATION! I WILL NOT USE 4 IF THIS IS THE WAY IT IS. [just ...

WRONG WRONG WRONG #2
Name: ROZ mandelcorn Email: thunderstaratearthlinkdotnet Product: Firefox Summary: WRONG WRONG WRONG Comments: as a long-time user, first of netscape and, mozilla firefox, i must say i DO NOT LIKE THE PLACEMENT of TABS in version 4. nor do i like the whole rearrangement of the upper/navigation portion of firefox. I NEED/WANT MY TABS DIRECTLY ABOVE MY WINDOWS AS IT IS NOW....NOT ON TOP OF THE BROWSER. I WANT MY FILE-EDIT-ETC-MENU on TOP. ETC. AT LEAST GIVE US THE CHOICE AS TO WHICH FORMAT WE WANT....CAN YOU SAY CUSTOMIZATION! I WILL NOT USE 4 IF THIS IS THE WAY IT IS. [just ...

Wrong error code when typing a wrong password for outgoing message
There's a problem when I type a wrong password for an outgoing message (using AUTH on Submit port 587 on my EIMS server): SM doesn't ask for a new password, it doesn't return "wrong pw" error; instead it keeps sending the wrong one to the server and returns a generic SMTP error "check your smtp settings". This only happens using SM. Gabriele Gabriele wrote: > There's a problem when I type a wrong password for an outgoing message > (using AUTH on Submit port 587 on my EIMS server): SM doesn't ask for a > new password, it does...

Wrong Thing, Wrong Time, Wrong Prof
Hey folks, I couldn't resist passing this along from Fred Langa's List, from the "Just For Grins" department, where, in a .wmv media presentation, a professor pretty much spells out in how much - and how deep - doo-doo a thief is for stealing his laptop and how it is he knows who did it. http://media1.break.com/dnet/media/content/stolenlaptop.wmv -- Captain Ozone "Beat me, daddy, eight to the bar!" 8-) Captain Ozone writes: > Hey folks, I couldn't resist passing this along from Fred Langa's List, from > the "Just For Gri...

Firefox sends wrong language code -- how can I catch this?
Hi all, I am trying to localize a website for Nynorsk (nn-NO, which is the second official language in Norway). The problem is, while Internet Explorer sends the right code, Firefox (most current version) only sends "nn". ASP.NET's internal internationalization routines don't accept this. Creating a /App_GlobalResources/Resource.nn.resx file throws a compilation error (CS0101: The namespace 'Resources' already contains a definition for 'Resource'), and querying Thread.CurrentThread.CurrentCulture.Name inside InitializeCulture() even returns "nb-NO&quo...

What is wrong with this code
string licenseNumber = "MyKeyValue"; imglnk.Url = "javascript:OpenTextbook( " + licenseNumber + " )"; Error is: Error: LIC0002 is not defined Source File: javascript:OpenTextbook( LIC0002 ) Line: 1 HighOnCodingWanna get high!  azamsharp wrote:string licenseNumber = "MyKeyValue"; imglnk.Url = "javascript:OpenTextbook( " + licenseNumber + " )"; Error is: Error: LIC0002 is not definedSource File: javascript:OpenTextbook( LIC0002 )As the error message states (and a view source would confirm) your output is:   javascript:OpenTextbook( LIC0002 )which is invali...

What is wrong in my code?????????
I would like to return ALL ITEMES in a column by this way. Where is wrong in my code?? Please help (without using "asp:Repeater"!) <!-- #INCLUDE FILE="..\include.aspx" --> <script language="VB" runat="server"> dim mypagename as string Sub Page_Load(sender As Object, e As EventArgs) Dim query As String = "Select * FROM tblPages where id>0" Dim myConn As OdbcConnection = gooz Dim myCmd As New ODBCCommand(query,myConn) myConn.Open() Dim myReader As ODBCDataReader = myC...

What is wrong with this code ?
    protected void Page_Load(object sender, EventArgs e)    {        if (HttpContext.Current.User.IsInRole("MODERATOR"))        {               BulletedList bl = (BulletedList)lvAdministrator.FindControl("bl");       }    } <%@ Page Language="C#" MasterPageFile="~/SelfService/MpSelfservice.master" AutoEventWireup="true" C...

What is wrong with this code?
The class below which is inherited from TRectangle, when instantiated and added to a form, is supposed to draw a rectangle with a label centered inside it. I do not have much experience with writing components, etc. but I have based this on one of the response to a questions that was asked in this forum. It does that properly, i.e. draws rectangle with a label inside it. But also what happens is that when the focus goes away from the rectangle, such as by clicking on some other control on the form, the effects applied to the label inside is misbehaving. This happens on the device as well th...

What is wrong with code
</asp:DataList> Line 41: <ItemTemplate> Line 42: ProductName<asp:Label id="Label1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem "ProductName") %>'></asp:Label> Line 43: </ItemTemplate> Line 44: </asp:DataList> I am doing DataList and Templates exercise and I get the message that something is wrong with line 42 DataItem not a member of 'System.Web.UI.Control'. What do I change??? Thanks again You've got </asp:DataLi...

Where is it wrong with my code
Hello, all. I am trying to assign a "P" for any values greater than 1.0 and assign a "A" otherwise. However, I need to skip the header line and the first column. Something is wrong with my code and it does not skip the first column well. Please help me to detect the bug. Thanks, Aiguo #!/usr/bin/perl use warnings; use strict; while (<DATA>) { next unless /_at/; my @groupPA = split(/\t/, $_); print " \t @groupPA \n"; foreach my $groupPA (@groupPA){ my $call; my @PAcall; next unless $groupPA =~ (/\d+/); print $groupPA; #pr...

What is wrong with my code?
I am new to VB.net and programming in general. I need some help in figuring out what the problem is with my program. My intention is that I should be able to put in a number in any of the 5 boxes and get my grade calculated. If I launch the program and put in 100 in any of the boxes and calculate the grade I get a 33 with a grade of F. If I hit the Clear button and then try again, I get the expected results. I can't figure out what I have that is causing the bad calculation when I launch the application.  1 Option Explicit On 2 Option Strict On 3 4 5 Public...

What is wrong with this code?
Hi all, Could you please help me with fixing this code because i have no idea what i'm doing wrong! Thanx already! ERROR Server Error in '/' Application. -------------------------------------------------------------------------------- Syntaxisfout (operator ontbreekt) in query-expressie 1A = 'true'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.OleDb.OleDbException: Syntaxisfout (operat...

wrong language
Name: Wollitz Ernst Email: rejorgatgmxdotde Product: Firefox Summary: wrong language Comments: Hello, I downloaded the freeware firefox v 1.5.08 For language I clicked german and got it in danish. But I can handle it. Version 2 seem to be available only in danish? Why not in english. So I would better stay with firefox v 1.5.08 in danish? Thanks Browser Details: Mozilla/5.0 (Windows; U; Win98; da; rv:1.8.0.8) Gecko/20061025 Firefox/1.5.0.8 ...

Web resources about - Making Wrong Code Type Wrong - perl.perl6.language

The Latest: Islamic State Group Praises California Shootings
The Latest: Islamic State group airs statement praising California mass shootings

Will Janet Yellen Sabotage Hillary Clinton?
A 211,000 jobs increase for November will finally push the Fed over the line and into a quarter-of-a-point rate hike later this month. The question ...

Janet Yellen says ‘looking forward’ to day of rate hike
Federal Reserve Chair Janet Yellen said on Wednesday she was "looking forward" to a U.S. interest rate hike that will be seen as a testament ...

Scott Weiland Dies At 48, Bandmate Arrested For Cocaine Found On Tour Bus
The music world was rocked by the news that former Stone Temple Pilots front-man, Scott Weiland, was found dead on December 3, in Bloomington, ...

Here’s Why Donald Trump’s December Poll Numbers Matter
Here’s some good news for Donald Trump fans: History is now on his side. For months, members of the Republican Establishment have dismissed ...

Samsung agrees to pay Apple $548 million in settlement
Samsung has been fighting Apple in court for years, but it sounds like it's getting near to letting it all go. The South Korean electronics maker ...

US Supreme Court to hear Puerto Rico debt appeal case
The US Supreme Court agreed to consider Puerto Rico's appeal of a ruling forbidding its use of a US law that would allow it to declare bankruptcy ...

Demi Lovato Reacts to the Death of Co-Star Tiffany Thornton's Husband
Demi Lovato is speaking out about the death of Chris Carney , who tragically passed away in a car accident early Friday morning (December 4). ...

Texas backs down from effort to block Syrian refugees
Washington Post Texas backs down from effort to block Syrian refugees Miami Herald Texas stopped trying Friday to block Syrian refugees from ...

Officer Who Repeatedly Punched 51-Year-Old Marlene Pinnock Will Not Be Charged With Crime
Yesterday, the Los Angeles County DA’s office announced that it would not be pressing charges against highway patrol officer officer Daniel Andrew, ...

Resources last updated: 12/5/2015 11:31:46 AM