Intro Lecture
Transcript of Intro Lecture
-
LinguagensdeProgramao
FernandoMagnoQuintoPereira
-
Oquesolinguagensdeprogramao? Porqueelasexistem? Comocomputadoreseramprogramadosantesdaslinguagensdeprogramao?
-
ATorredeBabel
Existementre5.000e6.000lnguasfaladasemnossoplaneta.
Cercade200idiomaspossuemmaisdeummilhodefalantes.
Comodescreverumidioma?Queelementosestopresentesnadescriodeumalinguagem?
-
Computadorestambmconversam
Comoalinguagemfaladapeloscomputadores?Quesmboloselausa?Quaispalavras?ComoseriaagramMcadessalnguaeletrnica?
-
Vamosfalarzeroumns?
Computadorespossuemcordasvocaismuitosimples:ouemitemsom,ounoemitem
possvelhaverumalinguagemcomapenasdoissmbolos?
Porquesomentedoissmbolos?
-
Dialetosdozeroumns
Hmuitaslinguagensdezeroseunsdiferentes,assimcomohmuitaslinguagensdiferentesusandocaractereslaMnos:ingls,portugus,espanhol,etc.
Quemmedexemplosdezeroumnsdiferentes?
-
Thebookisonthetable
Cadainstruoemzeroumnspossuiumnome,chamadoopcode,eoperandos.
Instruesmudamoestadodocomputador. QueMposdeinstruespoderiamexisMr? Falarzeroumnsdeveserfcil,no?
-
Masnono
AnMgamenteprogramarcomputadoreseramuitodi[cil.
Qualoproblemacomzeroumns?
Algumaiconhececartesperfurados?
Comodeixarzeroumnsmaisfcildeusar?
-
EveioaDeusa
Palavrassomaisfceisdelembrarquesequnciasdezeroseuns.
Porexemplo:qualinstruomaisfcildeler:mov $1, AL,ou10110000 01100001?
-
Oqueesteprogramafaz?
movl $5, %eax movl $1, %edx .L4: imull %eax, %edx decl %eax testl %eax, $0 jg .L4
-
Oqueesteprogramafaz?
movl $5, %eax movl $1, %edx .L4: imull %eax, %edx decl %eax testl %eax, $0 jg .L4
Coloque5emeax
Coloque1emedx
MulMpliqueeaxporedxecoloqueoresultadoemedx
Subtraia1deeax
Testeseeax0no
-
OMontador
Aspessoasfalavamassembly,masoscomputadoresaindafalavamzeroumns.Eraprecisoumtradutor.
OqueumtradutordesteMpodeveriasercapazdefazer?
-
ADeusanofoisuciente
Programaremassemblyaindaeradi[cil. Osprogramadoresqueriamqueoscomputadoresfossemcapazesdefalarlnguasaindamaisparecidascomlinguagenshumanas.
-
Quaisforamasprimeiraslinguagensdeprogramao?
Quemforamospaisdessaslinguagens?
-
SurgeFortran
JohnBackusestavacompreguiadeescreverprogramasemassembly.
IBM1953/54 Programarcouumas20vezesmaisfcilMasaspessoasaindaestavamrelutantesPorque?
-
ExemplodeprogramaemFortran
nfact=1 do i=1, 5 nfact = nfact*I enddo
movl $5, %eax movl $1, %edx .L4: imull %eax, %edx decl %eax testl %eax, $0 jg .L4
Fortran Assembly
QuenovidadessurgiramcomFortran?
-
ESurgeLISP
1958,Massachuse=sIns?tuteofTechnology ProfessorJohnMcCarthy. Umanotaosimples,baseadaemfunesmatemMcas.
Muitosparnteses, Elistas
-
ExemplodeProgramaemLISP
(defun factorial (n) (if (
-
ALGOLumMmedeestrelas
Precisavasedeumpadroparaalgoritmos.
Umcomitfoiformadoem1958. JohnBackusC.A.R.Hoare JohnMcCarthy,etc
DessecomitnasceuALGOL58. Talvezamaisinuentelinguagemdeprogramao.
-
ALGOLexemplo
integerprocedureFactorial(m);integerm;BeginintegerF;F:=ifm=1then1elsem*Factorial(m1);Factorial:=Fend;
Vocsjviramalgoparecidocomisto?
-
ECOBOL
COBOLfoifeitaparanegcios:Contadores,economistas,etcComodeveriaserumalinguagemassim?
1958:COBOLfoicriadaporumcomit. Indstria,governoeacademia
Aindausadaemmuitascompanhias,atemBH!
-
ExemplodeprogramasemCOBOL
ADD YEARS TO AGE. MULTIPLY PRICE BY QUANTITY GIVING COST.
SUBTRACT DISCOUNT FROM COST GIVING FINAL-COST.
-
Quantaslinguagensdeprogramaoexistem? Quaisaslinguagensmaispopulares?
-
Quantasso?
AeditoraOReillydizqueexistem2.500linguagensdeprogramaodocumentadas.
Awikipdiadocumenta650.
Existemmuitas Mas,porquetantas?
-
Propsitosdiferentes
Fortranserviaparaclculoscienwcos.
Lisperausadaemteoriadacomputao.
COBOLfoifeitaparaaplicaescomerciais.
Algolumalinguagemacadmica.
Easoutraslinguagensqueconhecemos?
-
Quaissoaslinguagenspop?
DadosreMradosdewww.tiobe.com Java:18.71%C:16.89%PHP:10.39%
Googlecode:C,Java,C++,PHP
Craigslist:PHP,C,SQL Queoutrasmedidas?
-
AlgumafalaJavans?
Deacordocommuitoscritrios,Javaaalinguagemmaispopular.
ParaqueserveJava? Comoessalinguagemsurgiu? Oqueelatemdemais?
-
Umexemplodejavans:
public class Fact { public static void main(String a[]) { int n = 5; int fact = 1; while (n > 1) { fact *= n; n--; } System.out.println(fact); } }
-
A,B,C
Csurgiuem1972,efoi,durantemuitosanos,alinguagemdeprogramaomaispopular.
PorqueCtemestenome? OqueagentefazcomC? PorqueCfoitopopular? QuaisosproblemascomC? Ctevegrandeinuncia
-
FalandoemC
int main() { int n = 5; int fact = 1; while (n > 1) { fact *= n; n--; } printf("%d\n", fact); }
Algumjviuistoantes?
-
Ctevegrandeinuncia
int n = 5; int fact = 1; while (n > 1) { fact *= n; n--; }
int n = 5; int fact = 1; while (n > 1) { fact *= n; n--; }
-
Figure 1. Web application architecture.
effectively under a heavy load of requests. Finally, some runtimetechniques [23, 24] require a modified runtime system, which con-stitutes a practical limitation in terms of deployment and upgrading.Static analyses to find SQLCIVs have also been proposed, but
none of them runs without user intervention and can guarantee theabsence of SQLCIVs. String analysis-based techniques [3, 20] useformal languages to characterize conservatively the set of values astring variable may assume at runtime. They do not track the sourceof string values, so they require a specification, in the form of aregular expression, for each query-generating point or hotspot inthe program a tedious and error-prone task that few program-mers are willing to do. Static taint analyses [12, 18, 31] track theflow of tainted (i.e., untrusted) values through a program and re-quire that no tainted values flow into hotspots. Because they usea binary classification for data (tainted or untainted), they classifyfunctions as either being santitizers (i.e., all return values are un-tainted) or being security irrelevant. Because the policy that thesetechniques check is context-agnostic, it cannot guarantee the ab-sence of SQLCIVs without being overly conservative. For exam-ple, if the escape quotes function (which precedes quotes withan escaping character so that they will be interpreted as charac-ter literals and not as string delimiters) is considered a sanitizer, anSQLCIV exists but would not be found in an application that con-structs a query using escaped input to supply an expected numericvalue, which need not be delimited by quotes. Additionally, statictaint analyses for PHP typically require user assistance to resolvedynamic includes (a construct in which the name of the includedfile is generated dynamically).
1.2 Our Approach
We propose a sound, automated static analysis algorithm to over-come the limitations described above. It is grammar-based; wemodel string values as context free grammars (CFGs) and stringoperations as language transducers following Minamide [20]. Thisstring analysis-based approach tracks the effects of string opera-tions and retains the structure of the values that flow into hotspots(i.e., where query construction occurs). If all of each string in thelanguage of a nonterminal comes from a source that can be influ-enced by a user, we label the nonterminal with one of two labels.We assign a direct label if a user can influence the source di-rectly (as with GET parameters) and a indirect label if a user caninfluence the source indirectly (as with data returned by a databasequery). Such labeling tracks the source of string values. We usea syntax-based definition of SQL injection attacks [25], which re-quires that input from a user be syntactically isolated within a gen-erated query. This policy does not need user-provided specifica-tions. Finally, we check policy conformance by first abstracting thelabeled subgrammars out of the generated CFG to find their con-texts. We then use regular language containment and context freelanguage derivability [28], to check that each subgrammar derivesonly syntactically isolated expressions.We have implemented this analysis for PHP, and applied it to
several real-world web applications. Our tool scales to large codebases it successfully analyzes the largest PHP web application
...01 isset ($ GET['userid']) ?02 $userid = $ GET['userid'] : $userid = '';03 if ($USER['groupid'] != 1)04 {05 // permission denied06 unp msg($gp permserror);07 exit;08 }09 if ($userid == '')10 {11 unp msg($gp invalidrequest);12 exit;13 }14 if (!eregi('[0-9]+', $userid))15 {16 unp msg('You entered an invalid user ID.');17 exit;18 }19 $getuser = $DB->query("SELECT * FROM `unp user`"20 ."WHERE userid='$userid'");21 if (!$DB->is single row($getuser))22 {23 unp msg('You entered an invalid user ID.');24 exit;25 }...
Figure 2. Example code with an SQLCIV.
previously analyzed in the literature (about 100K loc). It discoveredmany vulnerabilities, some previously unknown and some based oninsufficient filtering, and generated few false positives.
2. Overview
In order to motivate our analysis, we first present the policy thatdefines SQLCIVs, and then give an overview of how our analysischecks web applications against that policy.
2.1 SQL Command Injection Vulnerabilities
This section illustrates SQLCIVs and formally defines them.
2.1.1 Example Vulnerability
Figure 2 shows a code fragment excerpted from Utopia News Pro,a real-world news management system written in PHP; we willuse this code to illustrate the key points of our algorithm. Thiscode authenticates users to perform sensitive operations, such asmanaging user accounts and editing news sources. Initially, thevariable $userid gets assigned data from a GET parameter, whicha user can easily set to arbitrary values. The code then performs twochecks on the value of $userid before incorporating it into an SQLquery. The query should return a single row for a legitimate user,and no rows otherwise. From line 14 it is clear that the programmerintends $userid to be numeric, and from line 20 it is clear thatthe programmer intends that $userid evaluate to a single valuein the SQL query for comparison to the userid column. However,because the regular expression on line14 lacks anchors (^ and $for the beginning and end of the string, respectively), any value for$userid that has at least one numeric character will be includedinto the generated query. If a user sets the GET parameter to 1';DROP TABLE unp user; --, this code will send to the databasethe folloing query:
SELECT * FROM `unp user` WHERE userid='1';DROP TABLE unp user; --'
AInternetrespiraPHP
AlgumaquijprogramouemPHP? Oqueessenomequerdizer? Comodeveserumalinguagemparadesenvolvimentoweb?
-
UmexemplodePHPs:
$id = $_GET[user];
if ($id == '') { echo "Invalid user: $id" } else { $getuser = $DB->query (SELECT * FROM 'table' WHERE id=$id); echo $getuser; }
AlgumnotouumpouquinhodeCa? QualoMpodavarivel$id?
-
Computadoresfalamzeroumns,nsfalamoslinguagensdeprogramaoquemtraduzestascoisas?
Ecomoessatraduofeita?
-
Compiladoressopontes
Oprimeirocompiladorfoi,provavelmente,oA-0deGraceHopper(1949).
Linguagensdeprogramaodiferentespossuemdiferentescompiladores.
Masomesmocompiladortambmpodecompilarlinguagensdiferentes.
-
Anatomiadeumcompilador
FrontEnd
OMmizadorBackEnd
Fortran
COBOL
Lisp
ARM
x86
PowerPC
-
MquinasVirtuais
UmamquinavirtualumhardwareimplementadoemsoEware.
Porqueissointeressante? Quelinguagensexecutamemmquinasvirtuais?
Aindanecessrioumtradutor?
-
svezes,tudointerpretado Uminterpretadornoproduzcdigodemquina.Aocontrrio,elelocdigodoprogramafonte,einterpretacadacomandoencontrado.
Quaisasvantagensdeuminterpretador? Quaislinguagenssointerpretadas?
Serquehalgumalinguagemquenecessariamentetenhadeserinterpretada?
Essascoisassoeciente?
-
Fazemosjustin?me
Algumaslinguagenssocompiladasenquantoestosendointerpretadas. JavaScript,porexemplo.
Edeondevemaecincia? Serquedparafazermelhorqueumcompiladortradicional?
-
Existeumalinguagemdeprogramaomaispoderosaquetodasasoutras?
Seexiste,quelinguagemessa? Mascomomediressepoder?
-
FcilouDi[cil
1. EncontrearededeestradasmaiscurtaqueligatodasascidadesdeMinasGerais.
2. Encontreamenorrotapassandoportodasascidades,semrepeMr.
3. DadoumprogramaPpararesolver(2),veriqueseaprimeiracoisaquePimprimeNovaEra.
-
Hquesermoshumildes
AmquinadeTuringummodelotoricoquedenetodososproblemasquesocomputveis.Estado,ta,leitor,smbolos,instrues.
SenohsoluonaMquinadeTuring,entonotemjeitomesmo...
-
LinguagensTuringCompletas
SeumalinguagemequivalenteMquinadeTuring,entoelaTuringCompleta.
QuasetodaLPTuringCompleta. Masexistemlinguagensquenooso.Algumexemplo?
-
Brainfuc*
Umarranjomuitogrande,contendonmeros.Oitocomandos:
>moveumaposioparadireita + < - ]
-
EssaslinguagenstodasqueagenteviuJava,PHP,C,Fortran,COBOL,Algol,etc,etcelassomuitoparecidas:variveis,loops,comandosSerquenoexistenenhumoutroparadigmano?
-
LinguagensImperaMvaseDeclaraMvas
LinguagensimperaMvas:Oprogramainstruicomomudaroestadodamquina.
Variveis,loops,sequnciasdecomandos.Efeitoscolaterais.Existefunoqueretornavaloresdiferentesdadosparmetrosiguais?
LinguagensdeclaraMvas:Oprogramadescreveumaverdade.Ausnciadeefeitoscolaterais.Loopsviachamadadefunesrecursivas.
-
SML Oprogramaumconjuntodefunes.Programassoprovasporinduo.
Principaisestruturasdedadossolistasetuplas.
fun sum [] = 0 | sum (h::t) = h + sum t
fun filter [] _ = [] | filter (h::t) f = if (f h) then h :: (filter f t) else (filter f t)
-
SorMngfun leq a b = a b fun filter _ nil = nil | filter f (h::t) = if f h then h :: filter f t else filter f t fun qsort nil = nil | qsort (h::t) = (qsort (filter (grt h) t)) @ [h] @ (qsort (filter (leq h) t))
-
Prolog
Oprogramaumconjuntoderestries:SeAverdade,eABverdade,entoBverdade.
parent(kim, holly). parent(margaret, kim). parent(margaret, kent). parent(esther, margaret). parent(herbert, margaret). parent(herbert, jean).
bisavo(GGP, GGC) :- parent(GGP, GP), parent(GP, P), parent(P, GGC).
ancestor(X, Y) :- parent(X, Y). ancestor(X, Y) :- parent(Z, Y), ancestor(X, Z).
Oqueproduzirbisavo(X, Y)?
-
UmproblemaNPcompleto
sum([],0). sum([Head|Tail],X) :- sum(Tail,TailSum), X is Head + TailSum.
subList([], []). subList([H|T], [H|R]) :- subList(T, R). subList([_|T], R) :- subList(T, R).
intSum(L, N, S) :- subList(L, S), sumList(S, N).
DadaumalistaLdenmerosinteiros,existeumasublistaScujasomasejaN?