Load a certain line from a .txt into html - text

How do I load a certain line from a text document (for example line 546) into a website?

Do it with PHP. Use the fopen(), fread() and fclose() methods. To get a specific line of txt is relative, because the formatting of .txt
Start with w3schools and PHP manual. The best way to figured it out is to try and documentations. In my case it was helpful all the way.

I propose this solution using old technology because you asked to make this work for an old file format (html)! So here it goes! Don't be scared! What we are going to do is use Server Side Includes (SSI) to embed the results of a Common Gateway Interface (CGI) program into a static HTML document by using the "#exec cgi" directive. It sounds complicated but it's pretty simple. We only have to create two files and then make sure the web server is properly configured. Three simple steps! I'll guide you step by step:
1. Create Your HTML File
Your HTML file content would be just this (simply copy and paste into an HTML file on your server using a simple text editor):
<HTML>
<TITLE>Load a certain line from a .txt into html</TITLE>
Here's the content of line 546 in filename.txt:
<!--#exec cgi="/cgi-bin/perl-print-line.pl 546 filename.txt"-->
</HTML>
2. Create Your PERL Script File
The above won't work yet. It depends on a simple program to output your line number. It is perl-print-line.pl by Alvin Alexander, and you can simply create this file by copying and pasting the PERL code below into a text editor too (be sure to place it inside your cgi-bin directory):
#!/usr/bin/perl
# purpose: print a specific line from a text file
# usage: perl-print-line.pl line-number input-file
# use perl argv to verify the number of command line arguments
#ARGV == 2 or die "Usage: print-specific-line.pl line-number input-file\n";
$desired_line_number = $ARGV[0];
$filename = $ARGV[1];
# use perl open function to open the file (or die trying)
open(FILE, $filename) or die "Could not read from $filename, program halting.";
# loop through the file with a perl while loop, stopping when you get to the desired record
$count = 1;
while (<FILE>)
{
if ($count == $desired_line_number)
{
# print line, then get out of here
print $_;
close FILE;
exit;
}
$count++;
}
close FILE;
print "Sorry, I think the line number you entered is greater than the number of lines in the file.\n";
3. Configure SSI On Your Web Server
Now, all of the above will not work unless your web server is first configured to process SSI. All popular web servers can still do it, but you must first make sure it is configured. Per the PerlScriptsJavaScripts.com site,
If your server is a unix/linux server, you can be pretty sure it
supports SSI. SI requires the use of Apache Server software. Most
unix/linux server use Apache. Some Windows server also use Apache, but
most of them use IIS (Internet Information Server). The server
software is not something you can change, and because it runs th
entire server (including other people's web sites) your host will also
refuse to change it for you. They may instead be kind enough to move
your site to anther one of their servers which does use Apache.
Most people will tell you that to use SSI, you must name the page with
a "shtml" extension. While that may be the case initially, you can set
the server to also accept and parse regular "htm" or "html" files.
If you have a Windows server instead of a UNIX/Linux server, then you might find this article by Robert McMurray useful. Most importantly he states,
SSI is not enabled by default on IIS 6. To enable SSI on IIS 6, set
the status for the Server Side Includes web service extension to
Allowed in the Internet Information Services (IIS) Manager.
SSI is not installed by default on IIS 7. To install SSI on IIS 7, see
the Server Side Include topic.
The cmd directive for #exec is disabled by default in IIS 5 and IIS 6.
To enable the cmd directive, see Microsoft KB article 233969.
The cmd directive for #exec is now disabled for SSI files in IIS 7;
you can only use the cgi directive.
Finally, if you are dealing with IIS 7.5 and your SSI directives inside your *.html files aren't being automatically preprocessed, try reading this post.

Related

Exploiting and Correcting Path Traversal Vulnerability

I have a Java Web App running on Tomcat on which I'm supposed to exploit Path traversal vulnerability. There is a section (in the App) at which I can upload a .zip file, which gets extracted in the server's /tmp directory. The content of the .zip file is not being checked, so basically I could put anything in it. I tried putting a .jsp file in it and it extracts perfectly. My problem is that I don't know how to reach this file as a "normal" user from browser. I tried entering ../../../tmp/somepage.jsp in the address bar, but Tomcat just strips the ../ and gives me http://localhost:8080/tmp/ resource not available.
Ideal would be if I could somehow encode ../ in the path of somepage.jsp so that it gets extracted in the web riot directory of the Web App. Is this possible? Are there maybe any escape sequences that would translate to ../ after extracting?
Any ideas would be highly appreciated.
Note: This is a school project in a Security course where I'm supposed to locate vulnerabilities and correct them. Not trying to harm anyone...
Sorry about the downvotes. Security is very important, and should be taught.
Do you pass in the file name to be used?
The check that the server does is probably something something like If location starts with "/tmp" then allow it. So what you want to do is pass `/tmp/../home/webapp/"?
Another idea would be to see if you could craft a zip file that would result in the contents being moved up - like if you set "../" in the filename inside the zip, what would happen? You might need to manually modify things if your zip tools don't allow it.
To protect against this kind of vulnerability you are looking for something like this:
String somedirectory = "c:/fixed_directory/";
String file = request.getParameter("file");
if(file.indexOf(".")>-1)
{
//if it contains a ., disallow
out.print("stop trying to hack");
return;
}
else
{
//load specified file and print to screen
loadfile(somedirectory+file+".txt");
///.....
}
If you just were to pass the variable "file" to your loadfile function without checking, then someone could make a link to load any file they want. See https://www.owasp.org/index.php/Path_Traversal

Where/How to save a preferences file in a *nix command line utility?

I am writing a small command line utility. It should hopefully be able to run on OSX, UNIX and Linux.
It needs to save a few preferences somewhere, like in a small YAML config file.
Where would one save such a file?
Language: Python 2.7
OS: *nix
Commonly, these files go somewhere like ~/.rc (eg: ~/.hgrc). This could be the path to a file, or to a directory if you need lots of configuration settings.
For a nice description see http://www.linuxtopia.org/online_books/programming_books/art_of_unix_programming/ch10s03.html
I would avoid putting the file in the ~ directory only because it has gotten totally flooded with crap. The recent trend, at least on ubuntu, is to use ~/.config/<appname>/ for whatever dot files you need. I really like that convention.
If your application is named "someapp" you save the configuration in a file such as $HOME/.someapp. You can give the config file an extension if you like. If you think your app may have more than one config file you can use the directory $HOME/.someapp and create regular-named (not hidden) files in there.
Many cross-platform tools use the same path on OS X as on linux (and other POSIX/non-Windows platforms). The main advantage of using the POSIX locations isn't saving a few lines of code, but saving the need for Mac-specific instructions, and allowing Mac users to get help from the linux users in the community (without any need to translate their suggestions).
The other alternative is to put them in the "Mac-friendly" locations under ~/Library instead. The main advantage of using the Mac locations is basically "Apple says so"—unless you plan to sandbox your code, in which case the main advantage is that you can do so.
If you choose to use the Library locations, you should read About the OS X File System and OS X Library Directory Details in the File System Programming Guide, but here's the short version:
Almost everything: Create a subdirectory with your app's name or bundle ID (unless you're going out of your way to set a bundle ID, you'll get org.python.python, which you don't want…) under ~/Library/Application Support. Ideally you should use APIs like -[NSFileManager URLForDirectory:inDomain:appropriateForURL:create:error:] to get the path; if not, you have to deal with things like localization, sandbox containers, etc. manually.
Anything that can be easily re-created (so it doesn't need to be backed up, migrated, etc.): An identically-named subdirectory of ~/Library/Caches.
Preferences: Use the NSUserDefaults or CFPreferences APIs instead. If you use your own format, the "old" way of doing things is to create a subdirectory under ~/Library/Preferences named with your app's name or bundle ID, and put your files in that. Apple no longer recommends that, but doesn't really recommend an alternative (short of "use CFPreferences, damnit!"); many apps (e.g., Aquamacs) still do it the old way, but others instead pretend they're not preferences and store them under Application Support.
In Python, this works as follows (leaving out the error handling, and assuming you're going by name instead of setting a bundle ID for yourself):
from Foundation import *
fm = NSFileManager.defaultManager()
appsupport = (fm.URLForDirectory_inDomain_appropriateForURL_create_error_(
NSApplicationSupportDirectory, NSUserDomainMask, None, True, None)[0].
URLByAppendingPathComponent_isDirectory_(
appname, True))
caches = (fm.URLForDirectory_inDomain_appropriateForURL_create_error_(
NSCachesDirectory, NSUserDomainMask, None, True, None)[0].
URLByAppendingPathComponent_isDirectory_(
appname, True))
prefs = NSUserDefaults.persistentDomainForName_(appname)

How to disable "header already sent" message on linux, cpanel?

I building my sites on the localhost (runs wamp on windows), and when I upload it to my server, I always get
"Cannot modify header information - headers already sent"
I understand that there shouldn't be any blank lines and everyhing, and usually this works out. but now I need to redirect someone after the header has been sent, how can I make my server act like my localhost ?
i'm using cpanel and WHM:
cPanel 11.25.0-R42399 - WHM 11.25.0 - X 3.9
CENTOS 5.4 x86_64 virtuozzo on vps
I will appreciate any help
In short, you need to prevent PHP from outputting anything to the browser before you get to the point where you want to use the header() function.
This should be done by careful programming practices, of which your 'no blank lines' is one, or by storing PHP's output in an output buffer, and only outputting when you're ready for it.
See the ob_start() and ob_flush() methods. You use ob_start() at the start of your application. This disables output and stores it into a buffer. When you're ready to start outputting, use ob_flush() and PHP will send the buffer's contents to the browser, including the headers that are set till that point. If you don't call ob_flush() then the buffer is output (flushed) at the end of the script.
The reason why it works on your WAMP development environment is most likely that output buffering is already enable by default in the php.ini. Quite often these all-in-one packages enable a default buffer for the first 4k bytes or so. However, it is generally better to explicitly start and flush the buffer in your code, since that forces better coding practices.
Well,
I guess by more thinking and better programing you can manage to keep all redirects before any HTML is written.
This problem solved by the old rules...
#user31279: The quickest and dirtiest way I know of is to use # to suppress the warning, so e.g.
#header('Location: some-other-page.php');

Reproducing the blocked exe "unblock" option in file properties in windows 2003

When I download my program from my website to my windows 2003 machine, it has a block on it and you have to right click on the exe, then properties, then select the button "Unblock".
I would like to add detection in my installer for when the file is blocked and hence doesn't have enough permissions.
But I can't eaisly reproduce getting my exe in this state where it needs to be unblocked.
How can I get the unblock to appear on my exe so I can test this functionality?
This is done using NTFS File Streams. There is a stream named "Zone.Identifier" added to downloaded files. When IE7 downloads certain types of file that stream contains:
[ZoneTransfer]
ZoneId=3
The simplest way to set it is to create a text file with those contents in it, and use more to add it to the alternate stream.
Zone.Identifier.txt:
[ZoneTransfer]
ZoneId=3
Command:
more Zone.Identifier.txt > file.exe:Zone.Identifier
Then, the way for you to check it would be to try to open the Zone.Identifier stream and look for ZoneId=3, or simply assume that if the stream exists at all that your user will receive that warning.
It's also important to note that this has nothing to do with permissions. Administrators see the same warning; it's to do entirely with the source and type of file. The entire stream goes away when users uncheck the "Always ask before opening this file" box and then click Run.
There is a supported API for this, documented on MSDN. Search on MSDN for "Persistent Zone Identifier Object". Basically you CoCreateInstance with CLSID_PersistentZoneIdentifier and request an IPersistFile interface. You then call IPersistFile::Load with the name of the file in question. Next, QI for an IZoneIdentifier interface and use IZoneIdentifier::GetId to obtain the zone of the file. If there was no "mark of the web", you should get URLZONE_LOCAL_MACHINE. The ZoneId of 3 mentioned in the other reply is URLZONE_INTERNET. (The enumeration is called URLZONE and is also documented on MSDN, or see sdk\inc\urlmon.h.) You can remove or change the "mark of the web" by calling IZoneIdentifier::Remove or IZoneIdentifier::SetId and then call IPersistFile::Save. There are more details about all of this on MSDN. Good luck!
Thanks for this it helped me a lot.
You can make the process even easier if you create a batch file with the contents.
echo [ZoneTransfer] > Zone.Identifier
echo ZoneId=3 >> Zone.Identifier
more Zone.Identifier > %1:Zone.Identifier
This will generate the Zone.Identifier for you and mark the file accordingly.
To run it just supply the file name e.g. if the file is called mark.bat
mark.bat myfile.txt

"Silent" Printing in a Web Application

I'm working on a web application that needs to prints silently -- that is without user involvement. What's the best way to accomplish this? It doesn't like it can be done with strictly with Javascript, nor Flash and/or AIR. The closest I've seen involves a Java applet.
I can understand why it would a Bad Idea for just any website to be able to do this. This specific instance is for an internal application, and it's perfectly acceptable if the user needs to add the URL to a trusted site list, install an addon, etc.
Here’s what you need to do to enable Firefox immediately print without showing the print preferences dialog box.
Type about:config at Firefox’s location bar and hit Enter.
Right click at anywhere on the page and select New > Boolean
Enter the preference name as print.always_print_silent and click OK.
I found that somewhere and it helped me
As #Axel wrote, Firefox has the print.always_print_silent option.
For Chrome, use the --kiosk-printing option to skip the Print Preview dialog:
Edit the shortcut you use to start Chrome and add "--kiosk-printing" then restart Chrome.
Note: If it doesn't work it is most likely because you did not completely stop Chrome, logging out and back in will surely do the trick.
Here are two code samples you can try:
1:
<script>
function Print() {
alert ("THUD.. another tree bites the dust!")
if (document.layers)
{
window.print();
}
else if (document.all)
{
WebBrowser1.ExecWB(6, 1);
//use 6, 1 to prompt the print dialog or 6, 6 to omit it
//some websites also indicate that 6,2 should be used to omit the box
WebBrowser1.outerHTML = "";
}
}
</script>
<object ID="WebBrowser1" WIDTH="0" HEIGHT="0"
CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2">
</object>
2:
if (navigator.appName == "Microsoft Internet Explorer")
{
var PrintCommand = '<object ID="PrintCommandObject" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></object>';
document.body.insertAdjacentHTML('beforeEnd', PrintCommand);
PrintCommandObject.ExecWB(6, -1); PrintCommandObject.outerHTML = "";
}
else {
window.print();
}
You may need to add the site/page you are testing on to you local intranet zone.
We struggled with a similar problem. We needed to print checks to a check printer, labels to a label printer, and customer invoices to an invoice printer for retail store embrasse-moi. We have dummy computers, nooks, ipads, iphones with no printing capabilities. The printing an invoice feature was basically a silent print. A pdf was written to the server, and a shell script was used locally to retrieve it and print.
We used the following for a perfect solution with minimal libraries:
use TCPDF in PHP to create PDF. Store the PDF on the server. Put it in a 'Print Queue' Folder. Kudos for TCPDF, a bit difficult to learn, but SICK SICK SICK. Note we are printing 80 labels per page using avery 5167 with a bar code with perfect accuracy. We have a labels, check, and invoice print queue. Different folders basically for different printers.
Use the included shell script to connect to the server via FTP, download the PDF, delete the PDF off the server, send the PDF to the printer, and again, delete the PDF.
Using a local computer attached to the printer, run the script in terminal. obviously modify your printers and paths.
Because you always want this running, and because you use a MAC, create an 'app' using automator. Start automator, put the script in a 'run shell script' and save. Then stick that app in a login item. See the script below the shell script if you want to see the 'output' window on the MAC.
BAM - works sick.
Here is the shell script
#!/bin/bash
# Get a remote directory Folder
# List the contents every second
# Copy the files to a local folder
# delete the file from server
# send the file to a printer
# delete the file
# compliments of embrasse-moi.com
clear # clear terminal window
echo "##########################################"
echo "Embrasse-Moi's Remote Print Queue Script"
echo "##########################################"
#Local Print Queue Directory
COPY_TO_DIRECTORY=/volumes/DATA/test/
echo "Local Directory: $COPY_TO_DIRECTORY"
#Priter
PRINTER='Brother_MFC_7820N'
echo "Printer Name: $PRINTER"
#FTP Info
USER="user"
PASS="pass"
HOST="ftp.yourserver.com"
#remote path
COPY_REMOTE_DIRECTORY_FILES=/path
echo "Remote Print Queue Directory: $HOST$COPY_REMOTE_DIRECTORY_FILES"
echo 'Entering Repeating Loop'
while true; do
#make the copy to directory if not exist
echo "Making Directory If it Does Not Exist"
mkdir -p $COPY_TO_DIRECTORY
cd $COPY_TO_DIRECTORY
######################### WGET ATTEMPTS ############################################
#NOTE wget will need to be installed
echo "NOT Using wget to retrieve remote files..."
# wget --tries=45 -o log --ftp-user=$USER --ftp-password=$PASS ftp://ftp.yourserver.com$COPY_REMOTE_DIRECTORY_FILES/*.pdf
######################### FTP ATTEMPTS ############################################
echo "NOT Using ftp to retrieve and delete remote files..."
#This seems to fail at mget, plus not sure how to delete file or loop through files
ftp -n $HOST <<END_SCRIPT
quote USER $USER
quote PASS $PASS
cd $COPY_REMOTE_DIRECTORY_FILES
ls
prompt
mget *
mdel *
END_SCRIPT
echo "Examining Files in $COPY_TO_DIRECTORY"
for f in $COPY_TO_DIRECTORY/*.pdf
do
# take action on each file. $f store current file name
#print
echo "Printing File: $f To: $PRINTER"
lpr -P $PRINTER $f
# This will remove the file.....
echo "Deleting File: $f"
rm "$f"
done
echo "Script Complete... now repeat until killed..."
sleep 5
done
and the automator script if you want to see output, keep the app with the script
choose a run apple script option:
on run {input, parameters}
tell application "Finder" to get folder of (path to me) as Unicode text
set workingDir to POSIX path of result
tell application "Terminal"
do script "sh " & "'" & workingDir & "script1.sh" & "'"
end tell
return input
end run
I know this is an older thread, but it's still the top Google search for 'silent printing' so I'll add my findings for the benefit of anyone coming across this now.
We had a similar issue with printing labels of various types to various printers for a stocksystem. It took some trial and error, but we got around it by having the system create a pdf of the labels, with printer name and page qty's encoded in the pdf. All you then have to do is:
IN IE, go to Internet Options >> Security >> Trusted Sites >> Sites
Clear 'Require server verification (https:) for all sites in this zone'
add "http://[yoururl]"
and the pdf will print out automatically.
When we originally set this up we were using Chrome as the default browser, but in September 2015, Chrome dropped the ability to run NPAPI plugins. This meant that you could no longer select the Adobe pdf plugin as the default pdf handler, and the built in pdf plugin does not handle silent printing :-(
It does still work in Internet Explorer (IE11 at time of writing) but I've not tried any other browsers.
HTH
Cheers,
Nige
I wrote a python tsr that polled the server every so often (it pulled its polling frequency from the server) and would print out to label printer. Was relatively nice.
Once written in python, I used py2exe on it, then inno setup compiler, then put on intranet and had user install it.
It was not great, but it worked. Users would launch it in the morning, and the program would receive the kill switch from the server at night.
I have it working all day long using a simple JSP page and the Java PDF Renderer library (https://pdf-renderer.dev.java.net). This works because Java prints using the OS and not the browser. Supposedly "silent printing" is considered a browser vulnerability/exploit and was patched after IE 6 so good luck getting it to work via Javascript or Active X. Maybe its possible but I couldn't get it to work without Java.
I have to be honest, I am kinda thinking out loud here.. But could it not be done with an applet or some sort (be it Java or whatever) that is given trusted permissions (such as that within the Intranet zone) or something?
May be worth investigating what permissions can be given to each zone?
Following a Google, I think you definately have a challenge, so far most of the articles I have seen involve printing to printers connected to the server.
If its internal, would it be possible to route printing from the server to department/user printers or something?
If it is just an internal application, then you can avoid printing from the browser, and send a printout directly from the server to the nearest printer to the user.
I'm on the same issue here, this is what i learn so far.
A.: You need to setup an IPP PrintServer
You have multiple print server implementations you may try.
Hardware IPP print server: like DLINK DPR-1020 or similar, some printer have this functionality builtin.
Linux server with CUPPS : http://www.howtoforge.com/ipp_based_print_server_cups
XP-Pro server with ISS: http://www.michaelphipps.com/ipp-print-server-windows-xp-solution
B.: You need to make your WebApp a client of this IPP Server so you pick-process-send every user's print request to the PrintServer.
PHP::PRINT::IPP is a php lib you may try (it's well tested on cups servers).
You should have a look at PrintNode. They provide a silent remote printing services for web applications. You install a piece of software on the desktop which syncs to their servers. You can then send printjobs using an json request and they are instantly printed out.

Resources