From 0c8e0e355c9b74fb267e20336176880f88b1cf28 Mon Sep 17 00:00:00 2001 From: John-Mark Gurney Date: Sat, 13 Feb 2016 10:09:17 -0800 Subject: [PATCH] enforce all ones for true bool... test long strings... test for invalid bool.. [git-p4: depot-paths = "//depot/python/pypasn1/main/": change = 1819] --- pasn1.py | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/pasn1.py b/pasn1.py index a5d9893..8c1111a 100644 --- a/pasn1.py +++ b/pasn1.py @@ -9,8 +9,9 @@ # MUST not be used. The shorted form of length encoding MUST be used. # A longer length encoding MUST be rejected. -import pdb import math +import os +import pdb import sys import unittest @@ -139,10 +140,14 @@ class ASN1Coder(object): @staticmethod def enc_bool(obj): - return '\x01' + chr(obj) + return '\x01' + ('\xff' if obj else '\x00') def dec_bool(self, d, pos, end): - return bool(self.dec_int(d, pos, end)[0]), end + v = self.dec_int(d, pos, end)[0] + if v not in (-1, 0): + raise ValueError('invalid bool value: %d' % v) + + return bool(v), end @staticmethod def enc_null(obj): @@ -302,7 +307,7 @@ class TestCode(unittest.TestCase): self.assertEqual(dumps(256), '02020100'.decode('hex')) self.assertEqual(dumps(False), '010100'.decode('hex')) - self.assertEqual(dumps(True), '010101'.decode('hex')) + self.assertEqual(dumps(True), '0101ff'.decode('hex')) self.assertEqual(dumps(None), '0500'.decode('hex')) @@ -318,6 +323,10 @@ class TestCode(unittest.TestCase): v = loads(s) self.assertTrue(math.isnan(v)) + def test_invalids(self): + for v in [ '010101', ]: + self.assertRaises(ValueError, loads, v.decode('hex')) + def test_cryptoutilasn1(self): '''Test DER sequences generated by Crypto.Util.asn1.''' @@ -327,6 +336,12 @@ class TestCode(unittest.TestCase): ]: self.assertEqual(loads(s), v) + def test_longstrings(self): + for i in (203, 65484): + s = os.urandom(i) + v = dumps(s) + self.assertEqual(loads(v), s) + def test_dumps(self): for i in [ None, True, False,