devexpress asp.net pdf viewer : Extract one page from pdf application control utility azure html winforms visual studio AppleShellScripting-201423-part664

Withalargernumberofcases,theresultsmorepredictablyresemblewhatonemightexpect.The
case
version
isfastest,followedbythe
elif
version,followedbythe
if
version,withthe
eval
versionstillcominginlast.
Theseresultstendedtobemoreconsistent,though
eval
wasoftenfasterthantheseriesof
if
statements.
Althoughtheperformancedifferences(showninTable12-2)arerelativelysmall,inasufficientlycomplexscript
withalargenumberofcases,theycanmakeasizabledifference.Inparticular,the
case
statementtendsto
degrademoregracefully,whereastheseriesof
if
statementsbythemselvestendstocauseanever-increasing
performancepenalty.
PerformComputationsOnlyOnce
Forexample,ifyouhaveasubroutinethatincludes
expr $ROW + 1
intwoormorelinesofcode,youshould
definealocalvariable
ROW_PLUS_1
andstorethevalueoftheexpressioninthatvariable.Cachingtheresults
ofcomputationisparticularlyimportantifyouareusing
expr
formoreportablemath,butdoingsoconsistently
resultsinasmallperformanceimprovementevenwhenusingshellmath.
Table12-3
Performance(inseconds)of1000iterations,performingeachcomputationonceortwice
Oncewithshellmath
Twicewithshellmath
Oncewithexpr
Twicewithexpr
6.486
6.596
12.820
23.744
UseShellBuiltinsWhereverPossible
Using
echo
byitselfistypicallyabout30timesfasterthanexplicitlyexecuting
/bin/echo
.Thisimproved
performancealsoappliestootherbuiltinssuchas
umask
or
test
.
Ofcourse,
test
isparticularlyimportantbecauseitdoublesasthebracket(
[
)command,whichisessential
formostcontrolstatementsintheshell.Ifyouexplicitlywriteacontrolstatementusing
/bin/[
,thescript’s
performancedegradesimmensely,Fortunately,itisunlikelythatanyonewouldeverdothataccidentally.
Table12-4
Relativeperformance(inseconds)of1000iterationsoftheechobuiltinandtheechocommand
/usr/bin/printf
printf(builtin)
/bin/echo
echo(builtin)
6.359
0.230
6.212
0.285
Onarelatednote,the
printf
builtinissignificantlyfasterthanthe
echo
builtinifyourshellprovidesit(most
do).Thus,formaximumperformance,youshoulduse
printf
insteadof
echo
.
PerformanceTuning
OtherPerformanceTips
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
231
Extract one page from pdf - application control utility:C# PDF Page Extract Library: copy, paste, cut PDF pages in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
Easy to Use C# Code to Extract PDF Pages, Copy Pages from One PDF File and Paste into Others
www.rasteredge.com
Extract one page from pdf - application control utility:VB.NET PDF Page Extract Library: copy, paste, cut PDF pages in vb.net, ASP.NET, MVC, Ajax, WinForms, WPF
Detailed VB.NET Guide for Extracting Pages from Microsoft PDF Doc
www.rasteredge.com
ForMaximumPerformance,UseShellMath,NotExternalTools
Althoughsignificantlylessportable,codethatusestheZSH-andBASH-specific
$(( $VAR + 1))
math
notationexecutesupto125timesfasterthanidenticalcodewrittenwiththe
expr
commandandupto225
timesfasterthanidenticalcodewrittenwiththe
bc
command.
Use
expr
inpreferenceto
bc
foranyintegermaththatexceedsthecapabilitiesoftheshell’smathcapabilities.
Thefloating-pointmathusedby
bc
tendstobesignificantlyslower.
Table12-5
Relativeperformance(inseconds)of1000iterationsofshellmath,expr,andbc
bccommand
exprcommand
shellmath
25.008
14.106
0.111
CombineMultipleExpressionswithsed
The
sed
tool,likeanyotherexternaltool,isexpensivetostartup.Ifyouareprocessingalargechunkofdata,
thispenaltyislostinthenoise,butifyouareprocessingashortquantityofdata,itcanbeasizablepercentage
ofscriptexecutiontime.Thus,ifyoucanprocessmultipleregularexpressionsinasingleinstanceof
sed
,itis
muchfasterthanprocessingeachexpressionseparately.
Consider,forexample,thefollowingcode,whichchanges“Thisisatest”into“Thisisburnttoast”andthen
throwsawaytheresultsbyredirectingthemto
/dev/null
.
function1()
{
LOOP=0
while [ $LOOP -lt 1000 ] ; do
echo "This is a test." | sed 's/a/burnt/g' | sed 's/e/oa/g' > /dev/null
LOOP=$((LOOP + 1))
done
}
Youcanspeedthisupdramaticallybyrewritingtheprocessinglinetolooklikethis:
echo "This is a test." | sed -e 's/a/burnt/g' -e 's/e/oa/g' > /dev/null
PerformanceTuning
OtherPerformanceTips
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
232
application control utility:VB.NET PDF Page Delete Library: remove PDF pages in vb.net, ASP.
If you are looking for a solution to conveniently delete one page from your PDF document, you can use this VB.NET PDF Library, which supports a variety of PDF
www.rasteredge.com
application control utility:C# PDF File Merge Library: Merge, append PDF files in C#.net, ASP.
C# developers can easily merge and append one PDF document to document imaging toolkit, also offers other advanced PDF document page processing and
www.rasteredge.com
Bypassingmultipleexpressionsto
sed
,itprocessestheminasingleexecution.Inthiscase,theprocessingof
thesecondexpressioncanbereducedbymorethan60%onatypicalcomputer.
AsexplainedinAvoidingUnnecessaryExternalCommands (page 222),youcanimproveperformancefurther
byconcatenatingthesestringsintoasinglestringandprocessingtheoutputofall1000linesinasingle
invocationof
sed
(withtwoexpressions).Thischangereducesthetotalexecutiontimebynearlyafactorof
20comparedwiththeoriginalversion.
Forsmallinputs,theexecutionpenaltyisrelativelylarge,socombiningexpressionsresultsinasignificant
improvement.Forlargeinputs,theexecutionpenaltyisrelativelysmall,socombiningexpressionsgenerally
resultsinnegligibleimprovement.However,evenwithlargeinputs,ifthe
sed
statementsareexecutedina
loop,thecumulativeperformancedifferencecouldbenoticeable.
Table12-6
Relativeperformance(inseconds)ofdifferentusecasesforsed
Onecallon
accumulated
text
Twocallson
accumulated
text
Onecallperline
(1000callstotal)
Twocallsperline
(2000callstotal)
0.665
0.670
9.983
16.874
Single-processor
system
0.612
0.619
8.143
11.460
Dual-processor
system
PerformanceTuning
OtherPerformanceTips
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
233
application control utility:C# PDF Image Extract Library: Select, copy, paste PDF images in C#
Open a document. PDFDocument doc = new PDFDocument(inputFilePath); PDFPage page = (PDFPage)pdf.GetPage(0); // Extract all images on one pdf page.
www.rasteredge.com
application control utility:VB.NET PDF File Merge Library: Merge, append PDF files in vb.net
all. This guiding page will help you merge two or more PDF documents into a single one in a Visual Basic .NET imaging application.
www.rasteredge.com
Securityisoftenoverlookedwhenwritingshellscripts.Manyprogrammersignoreshellscriptsecurityunder
theassumptionthatanythinganattackercandobyattackingascriptcanbeachievedmoreeasilybysimply
executingthecommandsthemselves.Thisisnottrue,however,whenthescripttakesinputfromanuntrusted
thirdparty:
ShellscriptsrunningasCGIscriptsonawebservertakeinputfromthenetwork.
Shellscriptsthatreadfilesandtakeactionsbasedontheircontentsmaytakeinputfromuntrustedfiles.
Shellscriptsthatperformwebqueries(with
curl
,forexample)orothernetworkrequestsmaytakeinput
fromuntrustedserversorclients.
Further,mostsecurityproblemsarealsocorrectnessbugsevenifsomeoneisnottryingtoattackyourcode.
Thischapterdescribesafewcommonmistakesinscripting,showshowthesevulnerabilitiescanbeexploited,
andexplainshowtopreventtheseattacksinyourscripts.
ThischapteralsodescribeshowUNIXpermissionsandPOSIXaccesscontrollists(ACLs)affectyourscriptsand
howtomanipulatethosepermissionsandACLsinyourscripts.
EnvironmentAttacks
Environmentvariableattacksarethemostcommonwaytomanipulatescriptbehavior.Bymanipulatingthe
environmentofascript,youcanchangeitsbehaviorifthescriptdependsonthevaluesofthoseenvironment
variables.
Althoughtheyarelessharmfulforscriptsthesedays(becausescriptscannotberunsetuidinanymodernOS),
theycanstillcauseincorrectbehavior.Forsetuidbinaries,theyareevenmoredangerous.Theseattackscan
alsobeharmfulinamultiusersettingifoneusergainstheabilitytomodifytheloginscriptsofanotheruser
throughabugorincorrectconfiguration.
Themostcommonenvironmentattackismodifyingthe
PATH
environmentvariable.Thisvariablecontrols
whatgetsexecutedwhenyoutypeacommandwithoutgivingthefullpath.
Considerthefollowingcode:
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
234
Shell Script Security
application control utility:VB.NET PDF Annotate Library: Draw, edit PDF annotation, markups in
to display it. Thus, PDFPage, derived from REPage, is a programming abstraction for representing one PDF page. Annotating Process.
www.rasteredge.com
application control utility:C# PDF Page Delete Library: remove PDF pages in C#.net, ASP.NET
Using RasterEdge Visual C# .NET PDF page deletion component, developers can easily select one or more PDF pages and delete it/them in both .NET web and Windows
www.rasteredge.com
#!/bin/sh
ls /tmp
Theattack:
Createanexecutablebinaryorscriptthatdoessomethingharmfulandnameit“ls”.Thendothis:
export PATH=/path/to/malicious/binary:$PATH
/path/to/above/script
Becausethepathtothemaliciousbinaryisfirstinthesearchpath,themalicious
ls
commandgetsexecuted
insteadoftherealone.
Mitigation:
Alwaysspecifyabsoluteorrelativepathswhenexecutingbinariesorotherscripts.Ifyourscriptrunsother
scriptsorbinariesthatdonotuseabsoluteorrelativepathsinternally,youshouldexplicitlysetthevalueof
the
PATH
environmentvariableinyourscriptstopreventproblems.
AttacksOnFilesInPubliclyWritableDirectories
Filesinpubliclywritabledirectories,includingtemporaryfiles,arevulnerabletoattackbysubstitutinga
maliciousfileinplaceofthefileyourscriptintendedtoreadorwrite.
TemporaryFileAttack
Thesimplestexampleofthisattackisatoolstoringsecretinformationintoatemporaryfile.
Considerthefollowingcode:
#!/bin/sh
SECRETDATA="My password is 12345."
echo > /tmp/mysecretdata
chmod og-rwx /tmp/mysecretdata
echo "$SECRETDATA" >> /tmp/mysecretdata
ShellScriptSecurity
AttacksOnFilesInPubliclyWritableDirectories
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
235
application control utility:C# PDF copy, paste image Library: copy, paste, cut PDF images in
how to copy an image from one page of PDF to cut image from PDF file page by using PDFDocument doc = new PDFDocument(inputFilePath); // Extract all images from
www.rasteredge.com
application control utility:VB.NET PDF copy, paste image library: copy, paste, cut PDF images
how to copy an image from one page of PDF how to cut image from PDF file page by using doc As PDFDocument = New PDFDocument(inputFilePath) ' Extract all images
www.rasteredge.com
Theattack:
Createatoolthatwatchesforthefile
/tmp/mysecretdata
toappear.(Althoughthiscanbedonewithashell
script,itprobablywon’tbefastenoughtoworkveryoften.UsetheFileSystemEventsAPIinCinstead.)
Upondetectingtheexistenceofthepath,dothis:
FILE *fp=fopen("/tmp/mysecretdata", "r");
Iftheattackermanagestoopenthefilebeforethescriptexecutesthe
chmod
command,itcancontinueto
readdatafromthefileforaslongasitkeepsthefileopen.
Mitigation:
Therearetwothingsyoumustdotofixthis:
Alwaysusethe
umask
commandtospecifyinitialpermissionsonthefilewhenyoucreateit.
Alwayscreatetemporaryfileswiththe
mktemp
command.Thiscreatesanewfilewiththespecified
template,ensuringthatafileorsymboliclinkwiththatnamedoesnotalreadyexist.
Forexample:
#!/bin/sh
SECRETDATA="My password is 12345."
umask 0177
FILENAME="$(mktemp /tmp/mytempfile.XXXXXX)"
echo "$SECRETDATA" >> "$FILENAME"
However,assumingyouactuallyintendtousethedataagaininthefuture,thismitigationisprobablynot
sufficienteither,forthereasonsdescribedinthenextattack.
InputFileAttack
Asimilarattackcanbeperformedonfilesusedasinputstoshellscripts.
Considerascriptthatexecutesthefollowingcode:
#!/bin/sh
ShellScriptSecurity
AttacksOnFilesInPubliclyWritableDirectories
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
236
echo "My password is secret!" > /tmp/mypublicdata
...
PUBLICDATA="$(cat /tmp/mypublicdata)"
echo "$PUBLICDATA" | nc 192.168.1.102 3333
Thisscriptsendsthecontentsofatemporaryfiletoport3333ofanothercomputeratIPnumber192.168.1.102
usingthe
nc
utility.
Theattack:
Createatoolthatwatchesforthefile
/tmp/mydata
toappear.(Althoughthiscanbedonewithashellscript,
itprobablywon’tbefastenoughtoworkveryoften.UsetheFileSystemEventsAPIinCinstead.)
Upondetectingtheexistenceofthepath,dothis:
unlink("/tmp/mypublicdata");
unlink("/etc/myscretdata", "/tmp/mypublicdata");
Iftheattackermanagestodothisbeforethescriptreadsthefile,thenyoursecretpassword(presumably12345,
fromthepreviousscript)issentunencryptedoverport3333.Theattackercanthensnifffortrafficonthatport,
andcanlogintoyouraccount(oratleastunlockyourluggage).
Mitigation:
ThisisparticularlytroublesometomitigatebecauseUNIXtoolsinherentlyfollowsymboliclinks.Theonlyway
tosolvetheproblemistoavoidwritingtheactualfilesintopublicdirectories.Youshoulddothisasfollows:
Alwayscreatetemporarydirectorieswiththe
mktemp
command,thencreateyouractualtemporaryfiles
insidethosedirectories.Bydoingthis,youcansetrestrictivepermissionsonthedirectorythatwillprevent
anattackerfromdeletingyourfilesandreplacingthem.
Ifyouspecifythe
-d
flag,the
mktemp
commandcreatesanewdirectorywiththespecifiedtemplate,
ensuringthatafileordirectorywiththatnamedoesnotalreadyexist.
Alwaysusethe
umask
commandtospecifyinitialpermissionsonfilesanddirectorieswhenyoucreate
them.
Forexample:
ShellScriptSecurity
AttacksOnFilesInPubliclyWritableDirectories
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
237
#!/bin/sh
umask 0177
TMPDIR="$(mktemp -d /tmp/mytempfile.XXXXXX)"
echo "My password is secret!" > "$TMPDIR"/mypublicdata
...
PUBLICDATA="$(cat "$TMPDIR"/mypublicdata)"
echo "$PUBLICDATA" | nc 192.168.1.102 3333
InjectionAttacks
Themostcommontypeofattackinshellscriptsistheinjectionattack.Thistypeofattackoccurswhenarguments
storedinuser-providedvariablesarepassedtocommandswithoutproperquoting.
SimpleExample
Considerthefollowingexample:
read FOO
read BAR
if [ x$FOO = xfoo ] ; then
echo $FOO
eval $BAR
fi
Thiscodehastwosecurityholes.Canyouspotthem?
if [ x$FOO = xfoo ] ; then
Thisstatementallowsforaninjectionattackon
FOO
.
Theattack:
Pass“
foo = xfoo -o x
”asthevaluefor
FOO
.
ShellScriptSecurity
InjectionAttacks
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
238
Despitethefactthatthevalueof
FOO
isnot“foo”,thestatementexecutesanyway.Dependingonwhat
thistestdoes,thiscouldpotentiallycauseunexpectedbehavior.
Mitigation:
Tofixthisbug,changetheifstatementtoread:
if [ "$FOO" = "foo" ] ; then
eval $BAR
Thisisano-no.Neverrunevalondatapassedinbyauserunlessyouhavevery,verycarefullysanitized
it(andifpossible,useawhitelisttolimittheallowedvalues).
Theattack:
Passadangerouscommandfor
BAR
.
Mitigation:
Justdon’tdothat.
SubtleExample
Thefollowingexampleismoresubtle.Insteadofrunning
eval
,itwritesdatatoascript,butdoessowithout
protectingthevalues:
#!/bin/sh
read FOO
# ...
echo ls $FOO >> myscript.sh
# ...
chmod a+x myscript.sh
./myscript.sh
Theattack:
Passthevalue“
; rm randomfile
”tocausethisscripttodeleteafile.
ShellScriptSecurity
InjectionAttacks
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
239
TheWrongMitigation:
Youmightbetemptedtofixthisbugbychangingtheechoandexecutionlinestoread:
echo ls "\"$FOO\"" >> myscript.sh
export FOO
However,thisstilldoesnotsolvetheproblembecause
FOO
isexpandedimmediately,whichmeansthatifthe
valueof
FOO
containsaquotationmark—forexample,“
";rm randomfile ; echo "
”,younowhavea
different(butequallybad)securityhole.
CorrectMitigation#1:
Onewaytofixthisbugistochangetheecholinetoread:
echo ls "\"\$FOO\"" >> myscript.sh
Thiscausesthevariable
FOO
tobeexpandedwhenthescriptisexecuted.However,thisworksonlyifthe
variable
FOO
isexported,becauseotherwisethevariable
FOO
wouldexpandtonothinginthesecondscript.
CorrectMitigation#2:
Anotherwaytofixthisbugistochangetheecholinetoread:
QUOTFOO="$(echo "$FOO" | sed "s/'/'\"'\"'/g")"
echo ls "'$QUOTFOO'" >> myscript.sh
Byusingsinglequotesaroundthestringinthesecondaryscript,theonlycharacterrelevanttotheshellisthe
singlequotecharacter.The
sed
commandthenreplacesanysinglequotecharactersinthestringwithaclosing
singlequotefollowedbyasinglequotewrappedindoublequotesfollowedbyanopeningsinglequote.
BackwardsCompatibilityExample
Thefollowingexampleisnotdangerousinmodernshells,butisdangerousinolderBourneshells:
#!/bin/sh
read FOO
echo $FOO
ShellScriptSecurity
InjectionAttacks
2014-03-10   |   Copyright © 2003, 2014 Apple Inc. All Rights Reserved.
240
Documents you may be interested
Documents you may be interested