def _create_ssh_dir(self, user): '''Creates a .ssh dir''' os.mkdir(user.home + "/.ssh", 0700) os.chown(user.home + "/.ssh", user.uid, user.gid) testlib.create_fill(user.home + "/.ssh/known_hosts", "localhost,127.0.0.1 " + self.sshd_rsa_public_key) os.chown(user.home + "/.ssh/known_hosts", user.uid, user.gid)
def test_cve_2011_1097(self): '''Test CVE-2011-1097''' # PoC taken from https://bugzilla.samba.org/show_bug.cgi?id=7936 for filename in ['src', 'src/sub']: os.mkdir(os.path.join(self.tempdir, filename)) for filename in ['src/1', 'src/2', 'src/sub/file']: testlib.create_fill(os.path.join(self.tempdir, filename), "") (rc, report) = testlib.cmd(["rsync", "-a", "src/", "dest/"]) expected = 0 result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report) open('src/1', 'w').write("data") os.unlink('src/2') (rc, report) = testlib.cmd(["rsync", "-nvi", "-rc", "--delete", \ "src/", "dest/"]) expected = 0 result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report) # verify rsync doesn't think sub/file has changed result = 'Rsync thinks sub/file has changed! Report:%s\n' % report self.assertFalse("sub/file" in report, result)
def test_cve_2010_4369(self): '''Test CVE-2010-4369''' # Based on example from here: # http://sourceforge.net/tracker/?func=detail&aid=2537928&group_id=13764&atid=113764 # hackfile = os.path.join(self.tempdir, "vuln.pm") escaped_tempdir = self.tempdir.replace("/", "\/") os.chmod(self.tempdir, 0777) testlib.create_fill( hackfile, ''' #!/usr/bin/perl print "Content-tpe: text/html\n\n"; print "<pre>HACKED!<\/pre>"; exit; 1; ''') bad_plugin_config = 's/^#LoadPlugin=\"tooltips\"/LoadPlugin=\"..\/..\/..\/..%s\/vuln\"/' % escaped_tempdir subprocess.call(['sed', '-i', bad_plugin_config, self.awstats_conf]) self._test_url("http://localhost:8000/cgi-bin/awstats.pl", "HACKED", invert=True) self._test_url("http://localhost:8000/cgi-bin/awstats.pl", "config file contains a directive to load plugin")
def test_cron(self): '''Test that cron still works''' # Create cron file and script script = os.path.join(self.tmpdir, "test.sh") works = os.path.join(self.tmpdir, "it_works") contents = '''#!/bin/sh set -e touch %s ''' % (works) testlib.create_fill(script, contents, mode=0755) contents = "* * * * * root %s\n" % (script) testlib.create_fill(self.cronfile, contents) # Wait for result timeout = 130 print "\n Waiting for result from cron (max %d seconds)..." % (timeout) while (timeout > 0): if(os.path.exists(works)): break else: timeout -= 5 time.sleep(5) self.assertTrue(os.path.exists(works), "'%s' does not exist" % (works))
def test_tftp(self): '''Test basic tftp''' contents = "success\n" fn = os.path.join(self.tmpdir, "dtest.txt") dfn = fn + ".dl" testlib.create_fill(fn, contents) args = [ 'tftp', '-m', 'binary', '127.0.0.1', '-c', 'get', '%s' % os.path.basename(fn), '%s' % dfn ] rc, report = testlib.cmd(args) self.assertTrue(os.path.exists(dfn), "'%s' does not exist" % dfn) self.assertTrue("success" in file(dfn).read(), "'success' not found in '%s'" % dfn) contents = "success\n" fn = os.path.join(self.tmpdir, "utest.txt") ufn = fn + ".ul" testlib.create_fill(ufn, contents) # dnsmasq does not support PUT, make sure of that args = [ 'tftp', '-m', 'binary', '127.0.0.1', '-c', 'put', '%s' % ufn, '%s' % os.path.basename(fn) ] rc, report = testlib.cmd(args) self.assertFalse(os.path.exists(fn), "'%s' does not exist" % fn)
def test_awk(self): '''Test awk script detection''' if self.lsb_release['Release'] == 10.04: search = "awk script text executable" else: search = "awk script, ASCII text executable" filename = os.path.join(self.tempdir, 'awktest.awk') testlib.create_fill(filename, contents='''#!/bin/awk -f BEGIN { # Do something i=1; while (i <= 10) { printf "This is number ", i; i = i+1; } # end exit; } ''') report = self._run_file(filename) result = "Did not find '%s' in report" % search self.assertTrue(search in report, result + report)
def test_deb742265(self): '''Test perl script detection regression Debian #742265''' if self.lsb_release['Release'] == 10.04: search = "a /usr/bin/perl -w script text executable" elif self.lsb_release['Release'] == 12.04: search = "a /usr/bin/perl -w script, ASCII text executable" elif self.lsb_release['Release'] == 14.04: search = "Perl script, ASCII text executable" elif self.lsb_release['Release'] == 14.10: search = "awk script, ASCII text" else: search = "awk or perl script, ASCII text" filename = os.path.join(self.tempdir, 'deb742265.pl') testlib.create_fill(filename, contents='''#!/usr/bin/perl -w use strict; BEGIN { if ( !$ENV{'PERL_MODULES'} ) { $ENV{'PERL_MODULES'}= '/srv/fai/config/perl_modules'; } unshift @INC, $ENV{'PERL_MODULES'}; } use FAI; use NFS::Clients; ''') report = self._run_file(filename) result = "Did not find '%s' in report" % search self.assertTrue(search in report, result + report)
def test_daemon(self): '''Test dhcpd''' contents = ''' ddns-update-style none; default-lease-time 60; max-lease-time 720; allow bootp; authoritative; log-facility local7; subnet 192.168.122.0 netmask 255.255.255.0 { range 192.168.122.50 192.168.122.60; } ''' testlib.create_fill(self.server_config, contents) self.start_daemon() time.sleep(2) self.assertTrue( testlib.check_pidfile(os.path.basename(self.server_binary), self.server_pidfile)) rc, report = testlib.check_apparmor(self.server_binary, 9.04, is_running=True) if rc < 0: return self._skipped(report) expected = 0 result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report)
def test_cve_2010_4167(self): '''Test for CVE-2010-4167''' # Make sure imagemagick doesn't read config files from the current # directory. Example config files were obtained from here: # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=601824 bad_string = "All your base are belong to us." testlib.create_fill( os.path.join(self.tempdir, "coder.xml"), '''<codermap> <coder magick='png' name='notpng'/> </codermap>''') testlib.create_fill( os.path.join(self.tempdir, "delegates.xml"), '''<delegatemap> <delegate decode='png' command="echo '%s'"/> </delegatemap>''' % bad_string) shutil.copy("./data/well-formed.png", self.tempdir) os.chdir(self.tempdir) (rc, report) = testlib.cmd([ "/usr/bin/convert", "./well-formed.png", os.path.join(self.tempdir, "tempo.png") ]) result = 'Found %s in output:\n' % (bad_string) self.assertFalse(bad_string in report, result + report) expected = 0 result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report)
def test_cve_2014_1943_1(self): '''Test CVE-2014-1943 Part 1''' bad_contents = "\x45\x52\x00\x00\x00\x00\x00\x00" filename = os.path.join(self.tempdir, 'cve-2014-1943-1') testlib.create_fill(filename, contents=bad_contents) self._run_file(filename)
def setUp(self): '''Set up prior to each test_* function''' self.daemon = testlib.TestDaemon("/etc/init.d/cron") self.daemon.restart() self.tmpdir = tempfile.mkdtemp(prefix='testlib', dir='/tmp') self.seconds = 130 self.spooldir = "/var/spool/cron/crontabs" self.script = os.path.join(self.tmpdir, "test.sh") self.cronfile = os.path.join(self.tmpdir, "test.cron") self.works = os.path.join(self.tmpdir, "it_works") contents = '''#!/bin/sh set -e touch %s ''' % (self.works) testlib.create_fill(self.script, contents, mode=0755) contents = "*/1 * * * * %s\n" % (self.script) testlib.create_fill(self.cronfile, contents) self.user = testlib.TestUser() #group='users',uidmin=2000,lower=True) os.chown(os.path.dirname(self.works), self.user.uid, self.user.gid)
def test_CVE_2012_0037(self): '''Test CVE-2012-0037''' fn_entity = os.path.join(self.tmpdir, "ent.txt") s_entity = 'testlib string ABCDEFGHIJ' contents = "!!%s!!\n" % s_entity testlib.create_fill(fn_entity, contents) fn = os.path.join(self.tmpdir, "xmlent1.rdf") contents = '''<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE rdf [ <!ENTITY myentity SYSTEM "%s"> ]> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description rdf:about="http://example.org/"> <ns0:comment xmlns:ns0="http://www.w3.org/2000/01/rdf-schema#">&myentity;</ns0:comment> </rdf:Description> </rdf:RDF> ''' % (os.path.basename(fn_entity)) testlib.create_fill(fn, contents) os.chdir(self.tmpdir) rc, report = testlib.cmd(['rapper', '-q', '-i', 'rdfxml', fn]) expected = 0 result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report) search = "http://example.org/" self.assertTrue( search in report, "Could not find '%s' in report:\n%s" % (search, report)) self.assertFalse(s_entity in report, "Found '%s' in report:\n%s" % (s_entity, report))
def _setUp(self): '''Set up prior to each test_* function''' self.tempdir = tempfile.mkdtemp(dir='/tmp') self.archive_dir = "test-archive" # create some random files to archive self.archive_root = os.path.join(self.tempdir, self.archive_dir) self.files = { 'dir1': os.path.join(self.archive_root, "dir1"), \ 'dir2': os.path.join(self.archive_root, "dir1", \ "dir2"), \ 'dir3': os.path.join(self.archive_root, "dir3"), \ 'hlink1': os.path.join(self.archive_root, "hlink1"), \ 'slink1': os.path.join(self.archive_root, "slink1"), \ 'file1': os.path.join(self.archive_root, "file1"), \ 'file2': os.path.join(self.archive_root, "dir1", \ "file2"), \ 'dev2': os.path.join(self.archive_root, "dir1", "dev1") } # dirs os.mkdir(self.archive_root) os.mkdir(self.files['dir1']) os.mkdir(self.files['dir2']) os.mkdir(self.files['dir3']) # files testlib.create_fill(self.files['file1'], "foo") testlib.create_fill(self.files['file2'], "bar") # links os.link(self.files['file1'], self.files['hlink1']) os.symlink(self.files['file2'], self.files['slink1']) os.chdir(self.tempdir)
def _prepare_ssl(self, srvkey, srvcert): '''Prepare Apache for ssl connections''' self._enable_mod("ssl") # copy instead of rename so we don't get invalid cross-device link errors shutil.copy(srvkey, self.ssl_key) shutil.copy(srvcert, self.ssl_crt) if self.lsb_release['Release'] <= 7.04: testlib.config_replace(self.ports_file, "Listen 443", True) # create the conffile entry site_contents = ''' NameVirtualHost *:443 <VirtualHost *:443> SSLEngine on SSLOptions +StrictRequire SSLCertificateFile /etc/ssl/certs/server.crt SSLCertificateKeyFile /etc/ssl/private/server.key ServerAdmin webmaster@localhost DocumentRoot /var/www/ ErrorLog /var/log/apache2/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog /var/log/apache2/access.log combined ServerSignature On </VirtualHost> ''' testlib.create_fill(self.ssl_site, site_contents) self._reload()
def test_CVE_2012_2944(self): '''Test CVE-2012-2944''' self.tmpdir = tempfile.mkdtemp(dir='/tmp', prefix="testlib-") # First send bad input. We need to do this in a script because python # functions don't like our embedded NULs script = os.path.join(self.tmpdir, 'script.sh') contents = '''#!/bin/sh printf '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\n' | nc -q 1 127.0.0.1 3493 sleep 1 dd if=/dev/urandom count=64 | nc -q 1 127.0.0.1 3493 ''' testlib.create_fill(script, contents, mode=0755) rc, report = testlib.cmd([script]) # It should not have crashed. Let's see if it did self._testDaemons(['upsd']) self.assertTrue( 'ERR UNKNOWN-COMMAND' in report, "Could not find 'ERR UNKNOWN-COMMAND' in:\n%s" % report) # This CVE may also result in a hung upsd. Try to kill it, if it is # still around, it is hung testlib.cmd(['killall', 'upsd']) pidfile = os.path.join(self.rundir, 'upsd.pid') self.assertFalse(os.path.exists(pidfile), "Found %s" % pidfile) self.assertFalse(testlib.check_pidfile('upsd', pidfile), 'upsd is hung')
def test_smb_CVE_2006_5925(self): '''Test CVE-2006-5925''' if smb_url == '': return self._skipped("smb://... not specified") os.chdir(self.tempdir) contents = ''' <html> <a href='%s/%s" YYY; lcd ..; lcd ..; lcd ..; lcd ..; lcd .. ; lcd tmp; lcd %s ; get %s ; exit; '>Test CVE-2006-5925</a> </html> ''' % (smb_url, "test.txt", os.path.basename(self.tempdir), "p0wnd.txt") url = os.path.join(self.tempdir, "CVE-2006-5925.html") testlib.create_fill(url, contents) os.chdir(self.tempdir) expected = 0 search = "foobar" self._elinks_cmd(url, search, expected) print "" print " Please select the 'Test CVE-2006-5925' link, then press 'q' to exit elinks" time.sleep(3) subprocess.call(['elinks', '-no-connect', '-no-home', url]) result = 'Found \'p0wnd.txt\'\n' self.assertFalse( os.path.exists(os.path.join(self.tempdir, "p0wnd.txt")), result)
def test_CVE_2014_8737_ar(self): '''Test ar for CVE-2014-8737''' '''Origin: https://sourceware.org/bugzilla/show_bug.cgi?id=17552''' bad_archive_contents = '!<arch>\n{0:<48}{1:<10d}`\n../file\n{2:<48}{3:<10d}`\n'.format( '//', 8, '/0', 0) bad_archive = os.path.join(self.tempdir, 'cve-2014-8737.a') testlib.create_fill(bad_archive, bad_archive_contents) victim_file = os.path.join(self.tempdir, 'file') victim_contents = 'Please don\'t hurt me\n' testlib.create_fill(victim_file, victim_contents) subdir = os.path.join(self.tempdir, 'dir') os.mkdir(subdir) os.chdir(subdir) expected = 0 rc, report = testlib.cmd(['/usr/bin/ar', 'xv', bad_archive]) result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report) self.assertTrue( os.path.exists(victim_file), 'strip deleted %s; output was:\n%s' % (victim_file, report)) try: with open(victim_file, 'r') as f: new_contents = f.read() except IOError as e: self.fail('Unable to open victim \'%s\': %s' % (victim_file, str(e))) result = 'expected file contents:\n%s\nactual file contents:\n%s\n' % ( victim_contents, new_contents) self.assertEquals(victim_contents, new_contents, result + report)
def test_cve_2015_1395(self): '''Test CVE-2015-1395''' if self.lsb_release['Release'] < 14.04: return self._skipped("git style only present in Trusty and later") patch = os.path.join(self.tmpdir, "test.patch") target = "foo" bad_abs = os.path.join(self.baddir, target) bad_rel = os.path.relpath(bad_abs, self.workdir) contents = ''' diff --git a/foo b/foo new file mode 100644 --- /dev/null +++ b/%s @@ -0,0 +1 @@ +foo diff --git a/foo a/%s rename from x rename to x ''' % (bad_abs, bad_rel) testlib.create_fill(patch, contents) rc, report = testlib.cmd( ['patch', '-p1', '-i', patch, '-d', self.workdir]) self.assertFalse(os.path.exists(bad_abs)) self.assertTrue(os.path.exists(os.path.join(self.workdir, target))) self.assertTrue(rc == 1, report)
def test_cve_2010_2253(self): '''Test CVE-2010-2253''' self._enable_mod("php5") test_str = testlib_httpd.create_html_page(self.html_page) bad_filename = ".blah.txt" bad_file_path = os.path.join(self.tempdir, bad_filename) script = '''<?php $file = "%s"; header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename=\\"%s\\";"); header("Content-Transfer-Encoding: binary"); header("Content-Length: " . filesize($file)); readfile($file); exit; ?> ''' % (self.html_page, bad_filename) testlib.create_fill(self.php5_content_dispo, script) # See if it actually downloaded the file self._test_url_lwp("http://localhost/" + \ os.path.basename(self.php5_content_dispo), expected=1) # Make sure it didn't use the bad filename error = "Found the %s file." % bad_file_path self.assertFalse(os.path.exists(bad_file_path), error)
def _add_site(self, filename, name, contents): '''Add site to apache''' testlib.create_fill(filename, contents, mode=0644) if self.lsb_release['Release'] >= 14.04: self._disable_site('000-default') else: self._disable_site('default') self._enable_site(name)
def test_append(self): '''bsdtar: append''' archive = "archive.tar" new_file = "added1" # Record initial directory tree (rc, tmp) = testlib.cmd(["find", self.archive_dir]) self.assertEquals(rc, 0, tmp) first_find_report = self.clean_trailing_slash(self.sort_output(tmp)) # Create the base archive (rc, report) = testlib.cmd(["bsdtar", "cf", archive, self.archive_dir]) expected = 0 result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report) # add the file to the hieracrchy added_file = os.path.join(self.archive_root, new_file) testlib.create_fill(added_file, "new content") # Record updated directory tree (rc, tmp) = testlib.cmd(["find", self.archive_dir]) self.assertEquals(rc, 0, tmp) find_report = self.clean_trailing_slash(self.sort_output(tmp)) # Directory trees should be different self.assertNotEquals(first_find_report, find_report) # Update tar (rc, report) = testlib.cmd(["bsdtar", "uf", archive, \ os.path.join(self.archive_dir, new_file)]) expected = 0 result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report) # Record tar contents (rc, report) = testlib.cmd(["bsdtar", "tf", archive]) expected = 0 result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report) # Drop locale error message report = "\n".join([ x for x in report.splitlines() if x != 'bsdtar: Failed to set default locale' ]) + "\n" sorted_report = self.clean_trailing_slash(self.sort_output(report)) # Verify new tar does not match old find result = 'Find has:%s\n\n%s has:%s\n' % (first_find_report, \ archive, \ sorted_report) self.assertNotEquals(first_find_report, sorted_report, result) # Verify new tar does match the new find result = 'Find has:%s\n\n%s has:%s\n' % (find_report, \ archive, \ sorted_report) self.assertEquals(find_report, sorted_report, result)
def test_lp248619(self): '''Test mistaken identification of files as erlang JAM files LP: #248619''' bad_output = "Erlang" filename = os.path.join(self.tempdir, 'lp248619') testlib.create_fill(filename, contents="1/2 Tue") report = self._run_file(filename) result = "Found '%s' in report" % bad_output self.assertFalse(bad_output in report, result + report)
def create_perl_script(page): '''Create a basic perl script''' str = "perl works" script = '''#!/usr/bin/perl print "Content-Type: text/plain\\n\\n"; print "''' + str + '''\\n"; ''' testlib.create_fill(page, script, 0755) return str
def test_append(self): '''Jar append''' archive = "archive.jar" new_file = "added1" # Record initial directory tree (rc, tmp) = testlib.cmd(["find", self.archive_dir]) self.assertEquals(rc, 0, tmp) first_find_report = self.clean_trailing_slash(self.sort_output(tmp)) # Create the base archive (rc, report) = testlib.cmd( ["/usr/bin/fastjar", "-cMf", archive, self.archive_dir]) expected = 0 result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report) # add the file to the hieracrchy added_file = os.path.join(self.archive_root, new_file) testlib.create_fill(added_file, "new content") # Record updated directory tree (rc, tmp) = testlib.cmd(["find", self.archive_dir]) self.assertEquals(rc, 0, tmp) find_report = self.clean_trailing_slash(self.sort_output(tmp)) # Directory trees should be different self.assertNotEquals(first_find_report, find_report) # Update jar (rc, report) = testlib.cmd(["/usr/bin/fastjar", "-uMf", archive, \ os.path.join(self.archive_dir, new_file)]) expected = 0 result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report) # Record jar contents (rc, report) = testlib.cmd(["/usr/bin/fastjar", "-tf", archive]) expected = 0 result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report) sorted_report = self.clean_trailing_slash(self.sort_output(report)) # Verify new jar does not match old find result = 'Find has:%s\n\n%s has:%s\n' % (first_find_report, \ archive, \ sorted_report) self.assertNotEquals(first_find_report, sorted_report, result) # Verify new jar does match the new find result = 'Find has:%s\n\n%s has:%s\n' % (find_report, \ archive, \ sorted_report) self.assertEquals(find_report, sorted_report, result)
def _run_script(self, contents, expected=0, search=None, args=[]): script = os.path.join(self.tempdir, "test.lua") testlib.create_fill(script, contents, mode=0755) rc, report = testlib.cmd([exe, script]) result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report) if search != None: result = 'Could not find "%s" in output "%s"\n' % (search, report) self.assertEquals(search, report, result)
def test_template_file(self): '''Test a simple template from a file''' expected = "Ubuntu Rocks!" template = "${thing} Rocks!" template_file = os.path.join(self.tempdir, "template_file") testlib.create_fill(template_file, template) mytemplate = Template(filename=template_file) result = mytemplate.render(thing="Ubuntu") report = "Template '%s' doesn't match '%s'!" % (result, expected) self.assertTrue(result == expected, report)
def _run_script(self, contents, expected, expected_out, args=[]): '''Run "contents" as script''' self.tmpdir = tempfile.mkdtemp(prefix='testlib', dir='/tmp') script = os.path.join(self.tmpdir, "runme") testlib.create_fill(script, contents, mode=0755) rc, report = testlib.cmd([script] + args) expected = 0 result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report) result = "Got output:\n%s\nExpected \n%s" % (report, expected_out) self.assertEquals(expected_out, report, result)
def test_uscan_repack_zip(self): '''Test uscan repack with zip''' watchfile = os.path.join(self.tmpdir, "watch") contents = ''' version=3 https://launchpad.net/jbidwatcher-companion/+download .*/JBidwatcher-Companion-([0-9.]+~?.+?)\.zip ''' testlib.create_fill(watchfile, contents) rc, report = testlib.cmd([ 'uscan', '--package', 'jbidwatcher-companion', '--download', '--repack', '--upstream-version', '0.1.6', '--download-version', '0.1.7', '--verbose', '--watchfile', watchfile, '--destdir', self.tmpdir ]) expected = 0 result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report) # Utopic+ doesn't remove original tarball if self.lsb_release['Release'] < 14.10: result = "Found zip file!\n" tarball = os.path.join(self.tmpdir, "JBidwatcher-Companion-0.1.7.zip") self.assertFalse(os.path.exists(tarball), result) if self.lsb_release['Release'] < 14.10: filename = "JBidwatcher-Companion-0.1.7.tar.gz" else: filename = "jbidwatcher-companion_0.1.7.orig.tar.gz" result = "Couldn't find repacked tarball!\n" tarball = os.path.join(self.tmpdir, filename) self.assertTrue(os.path.exists(tarball), result) # Inspect contents of repacked tarball rc, report = testlib.cmd( ['tar', '-ztvf', os.path.join(self.tmpdir, filename)]) expected = 0 result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report) result = "Couldn't find file in repacked tarball!\n" self.assertTrue(" JBidwatcher-Companion-0.1.7/" in report, result) self.assertTrue(" JBidwatcher-Companion-0.1.7/setup.cfg" in report, result) self.assertTrue( " JBidwatcher-Companion-0.1.7/JBidwatcher_Companion.egg-info/PKG-INFO" in report, result)
def test_cve_2014_1943_2(self): '''Test CVE-2014-1943 Part 2''' bad_contents = "\x01" * 250000 magic = "0 byte x\n" + \ ">(1.b) indirect x\n" filename = os.path.join(self.tempdir, 'cve-2014-1943-2') magic_fn = os.path.join(self.tempdir, 'magic') testlib.create_fill(filename, contents=bad_contents) testlib.create_fill(magic_fn, contents=magic) self._run_file(filename, expected_rc=1, magic=magic_fn)
def setUp(self): '''Setup mechanisms''' self.hosts_file = "/etc/hosts" self.default_site = "/etc/apache2/sites-available/default" self.php5_content_dispo = "/var/www/test-content-dispo.php" self.tempdir = tempfile.mkdtemp(dir='/tmp', prefix="libwww-perl-") self.evil_filename = ".hiddenfile" self.evil_file = os.path.join("/var/www", self.evil_filename) testlib.create_fill(self.evil_file, "This is an evil file.") testlib_httpd.HttpdCommon._setUp(self) self.current_dir = os.getcwd()
def test_php5_gd(self): '''Test php5-gd''' self.tmpdir = self.cp_data_to_tmpdir('pfb') for f in self.files: if not f.endswith('.pfb'): continue fontpath = os.path.join(self.tmpdir, f) php_script = fontpath + ".php" pngpath = fontpath + ".png" stderr = fontpath + ".stderr" contents = '''<?php // Create a new image instance $im = imagecreatetruecolor(200, 200); $black = imagecolorallocate($im, 0, 0, 0); $white = imagecolorallocate($im, 255, 255, 255); // Make the background white imagefilledrectangle($im, 0, 0, 199, 199, $white); // Load the gd font and write 'String' $font = imagepsloadfont('%s'); // Write the font to the image imagepstext($im, 'String', $font, 36, $black, $white, 50, 50); // output to browser header("Content-type: image/png"); imagepng($im); imagedestroy($im); ?>''' % (fontpath) testlib.create_fill(php_script, contents) handle = file(pngpath, 'w') handle_stderr = file(stderr, 'w') rc, report = testlib.cmd(['php5', php_script], stdout=handle, stderr=handle_stderr) handle.close() handle_stderr.close() expected = 0 result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report) rc, report = testlib.cmd(['file', pngpath]) expected = 0 result = 'Got exit code %d, expected %d\n' % (rc, expected) self.assertEquals(expected, rc, result + report) self.assertTrue("PNG image" in report, "Could not find 'PNG image' in report:\n" + report)
def create_php_page(page, php_content=None): '''Create a basic php page''' # complexity here is due to maintaining interface compatability when # php_content is not provided if not php_content: str = "php works" php_content = "echo '" + str + "'; " else: str = php_content script = '''<?php %s ?>''' %(php_content) testlib.create_fill(page, script) return str
def _get_page_source(self, url="http://localhost/", data='', headers=None): '''Fetch html source''' cookies = "/tmp/cookies.lwp" testlib.create_fill(cookies, "#LWP-Cookies-2.0") if headers == None: headers = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'} clean_url = url if re.search(r'http(|s)://.*:.*@[a-z].*', url): tmp = re.sub(r'^http(|s)://', '', url) username = tmp.split('@')[0].split(':')[0] password = tmp.split('@')[0].split(':')[1] base64_str = base64.encodestring('%s:%s' % (username, password))[:-1] headers['Authorization'] = "Basic %s" % (base64_str) # strip out the username and password from the url clean_url = re.sub(r'%s:%s@' % (username, password), '', url) cj = cookielib.LWPCookieJar(filename=cookies) cj.load() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) try: if data != '': req = urllib2.Request(clean_url, data, headers) else: req = urllib2.Request(clean_url, headers=headers) except: raise tries = 0 failed = True while tries < 3: try: handle = urllib2.urlopen(req) failed = False break except urllib2.HTTPError, e: raise if e.code != 503: # for debugging #print >>sys.stderr, 'Error retrieving page "url=%s", "data=%s"' % (url, data) raise tries += 1 time.sleep(2)
def create_html_page(page): '''Create html page''' str = "html works" testlib.create_fill(page, "<html><body>" + str + "</body></html>") return str