Introdução à Linguagens de Programação

51
Fernando Magno Quintão Pereira Linguagens de Programação L A B O R A T O R I O D E C O M P I L A D O R E S Department of Computer Science Universidade Federal de Minas Gerais Brazil

Transcript of Introdução à Linguagens de Programação

Page 1: Introdução à Linguagens de Programação

FernandoMagnoQuintãoPereira

LinguagensdeProgramação

L A B O R A T O R I O D E C O M P I L A D O R E SDepartment of Computer Science − Universidade Federal de Minas Gerais − Brazil

Page 2: Introdução à Linguagens de Programação

•  Oquesãolinguagensdeprogramação?•  Porqueelasexistem?

•  Comocomputadoreseramprogramadosantesdaslinguagensdeprogramação?

Page 3: Introdução à Linguagens de Programação

ATorredeBabel

•  Existementre5.000e6.000línguasfaladasemnossoplaneta.

•  Cercade200idiomaspossuemmaisdeummilhãodefalantes.

•  Comodescreverumidioma?Queelementosestãopresentesnadescriçãodeumalinguagem?

Page 4: Introdução à Linguagens de Programação

Computadorestambémconversam

•  Comoéalinguagemfaladapeloscomputadores?– Quesímboloselausa?

– Quaispalavras?– ComoseriaagramáMcadessalínguaeletrônica?

Page 5: Introdução à Linguagens de Programação

Vamosfalarzero-um-nês?

•  Computadorespossuemcordasvocaismuitosimples:ouemitemsom,ounãoemitem

•  Épossívelhaverumalinguagemcomapenasdoissímbolos?

•  Porquesomentedoissímbolos?

Page 6: Introdução à Linguagens de Programação

Dialetosdozero-um-nês

•  Hámuitaslinguagensdezeroseunsdiferentes,assimcomohámuitaslinguagensdiferentesusandocaractereslaMnos:inglês,português,espanhol,etc.

•  Quemmedáexemplosdezero-um-nêsdiferentes?

Page 7: Introdução à Linguagens de Programação

“Thebookisonthetable”

•  Cadainstruçãoemzero-um-nêspossuiumnome,chamadoopcode,eoperandos.

•  Instruçõesmudamoestadodocomputador.

•  QueMposdeinstruçõespoderiamexisMr?

•  Falarzero-um-nêsdeveserfácil,nãoé?

Page 8: Introdução à Linguagens de Programação

Masnãoénão…

•  AnMgamenteprogramarcomputadoreseramuitodi[cil.

•  Qualoproblemacomzero-um-nês?

•  Alguémaiconhececartõesperfurados?

•  Comodeixarzero-um-nêsmaisfácildeusar?

Page 9: Introdução à Linguagens de Programação

EveioaDeusa

•  Palavrassãomaisfáceisdelembrarquesequênciasdezeroseuns.

•  Porexemplo:qualinstruçãoémaisfácildeler:mov $1, AL,ou10110000 01100001?

Page 10: Introdução à Linguagens de Programação

OQueesteprogramafaz?

movl $5, %eax movl $1, %edx .L4: imull %eax, %edx decl %eax testl %eax, $0 jg .L4

Page 11: Introdução à Linguagens de Programação

OQueesteprogramafaz?

movl $5, %eax movl $1, %edx .L4: imull %eax, %edx decl %eax testl %eax, $0 jg .L4

Coloque5em%eax

Coloque1em%edx

MulMplique%eaxpor%edx,ecoloqueoresultadoem%edx

Subtraia1de%eax

Testese%eaxéZero

SeZero,entãovápara.L4

Page 12: Introdução à Linguagens de Programação

OMontador

•  Aspessoasfalavamassembly,masoscomputadoresaindafalavamzero-um-nês.– Eraprecisoumtradutor.

•  OqueumtradutordesteMpodeveriasercapazdefazer?

Page 13: Introdução à Linguagens de Programação

ADeusanãofoisuficiente

•  Programaremassemblyaindaeradi[cil.•  Osprogramadoresqueriamqueoscomputadoresfossemcapazesdefalarlínguasaindamaisparecidascomlinguagenshumanas.

Page 14: Introdução à Linguagens de Programação

•  Quaisforamasprimeiraslinguagensdeprogramação?

•  Quemforamospaisdessaslinguagens?

Page 15: Introdução à Linguagens de Programação

SurgeFortran

•  JohnBackusestavacompreguiçadeescreverprogramasemassembly.

•  IBM1953/54

•  Programarficouumas20vezesmaisfácil– Masaspessoasaindaestavamrelutantes…Porque?

Page 16: Introdução à Linguagens de Programação

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?

Page 17: Introdução à Linguagens de Programação

ESurgeLISP

•  1958,Massachuse<sIns>tuteofTechnology•  ProfessorJohnMcCarthy.

•  Umanotaçãosimples,baseadaemfunçõesmatemáMcas.

• Muitosparênteses,

•  Elistas…

Page 18: Introdução à Linguagens de Programação

ExemplodeProgramaemLISP

(defun factorial (n) (if (<= n 1) 1 (* n (factorial (- n 1)))))

nfact=1 do i=1, n nfact = nfact*I enddo

Fortran

LISP

Equando,nosanos70,ossoviéMcosconseguiramasúlMmas500linhasdosistemademísseisamericanos…

Recursão!

Page 19: Introdução à Linguagens de Programação

ALGOL–umMmedeestrelas

•  Precisava-sedeumpadrãoparaalgoritmos.

•  Umcomitêfoiformadoem1958.– JohnBackus– C.A.R.Hoare– JohnMcCarthy,etc

•  DestecomitênasceuALGOL58.

•  Talvezamaisinfluentelinguagemdeprogramação.

Page 20: Introdução à Linguagens de Programação

ALGOL–exemplo

integerprocedureFactorial(m);integerm;BeginintegerF;F:=ifm=1then1elsem*Factorial(m-1);Factorial:=Fend;

•  Vocêsjáviramalgoparecidocomisto?

Page 21: Introdução à Linguagens de Programação

ECOBOL

•  COBOLfoifeitaparanegócios:– Contadores,economistas,etc

– Comodeveriaserumalinguagemassim?

•  1958:COBOLfoicriadaporumcomitê.– Indústria,governoeacademia

•  Aindausadaemmuitascompanhias,atéemBH!

Page 22: Introdução à Linguagens de Programação

ExemplodeprogramasemCOBOL

ADD YEARS TO AGE.

MULTIPLY PRICE BY QUANTITY GIVING COST.

SUBTRACT DISCOUNT FROM COST GIVING FINAL-COST.

Page 23: Introdução à Linguagens de Programação

•  Quantaslinguagensdeprogramaçãoexistem?•  Quaisaslinguagensmaispopulares?

Page 24: Introdução à Linguagens de Programação

Quantassão?

•  AeditoraO’Reillydizqueexistem2.500linguagensdeprogramaçãodocumentadas.

•  Awikipédiadocumenta650.

•  Existemmuitas…

• Mas,porquetantas?

Page 25: Introdução à Linguagens de Programação

Propósitosdiferentes

•  Fortranserviaparacálculoscienyficos.

•  Lisperausadaemteoriadacomputação.

•  COBOLfoifeitaparaaplicaçõescomerciais.

•  Algoléumalinguagemacadêmica.

•  Easoutraslinguagensqueconhecemos?

Page 26: Introdução à Linguagens de Programação

Quaissãoaslinguagenspop?

•  DadosreMradosdewww.tiobe.com – Java:18.71%– C:16.89%– PHP:10.39%

•  Googlecode:C,Java,C++,PHP

•  Craigslist:PHP,C,SQL•  Queoutrasmedidas?

Page 27: Introdução à Linguagens de Programação

AlguémaífalaJavanês?

•  Deacordocommuitoscritérios,Javaéaalinguagemmaispopular.

•  ParaqueserveJava?•  Comoestalinguagemsurgiu?

•  Oqueelatemdemais?

Page 28: Introdução à Linguagens de Programação

Umexemplodejavanês:

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); } }

Page 29: Introdução à Linguagens de Programação

éA,éB,éC…

•  Csurgiuem1972,efoi,durantemuitosanos,alinguagemdeprogramaçãomaispopular.

•  PorqueCtemestenome?

•  OqueagentefazcomC?

•  PorqueCfoitãopopular?•  QuaisosproblemascomC?

•  Ctevegrandeinfluência…

Page 30: Introdução à Linguagens de Programação

FalandoemC…

int main() { int n = 5; int fact = 1; while (n > 1) { fact *= n; n--; } printf("%d\n", fact); }

•  Alguémjáviuistoantes?

Page 31: Introdução à Linguagens de Programação

Ctevegrandeinfluência…

int n = 5; int fact = 1; while (n > 1) { fact *= n; n--; }

int n = 5; int fact = 1; while (n > 1) { fact *= n; n--; }

Page 32: Introdução à Linguagens de Programação

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 line 14 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

•  AlguémaquijáprogramouemPHP?•  Oqueestenomequerdizer?

•  Comodeveserumalinguagemparadesenvolvimentoweb?

Page 33: Introdução à Linguagens de Programação

UmexemplodePHPês:

$id = $_GET[”user”];

if ($id == '') { echo "Invalid user: $id" } else { $getuser = $DB->query (”SELECT * FROM 'table' WHERE id=’$id’”); echo $getuser; }

•  AlguémnotouumpouquinhodeCaí?•  QualoMpodavariável$id?

Page 34: Introdução à Linguagens de Programação

•  Computadoresfalamzero-um-nês,nósfalamoslinguagensdeprogramação…quemtraduzestascoisas?

•  Ecomoestatraduçãoéfeita?

Page 35: Introdução à Linguagens de Programação

Compiladoressãopontes

•  Oprimeirocompiladorfoi,provavelmente,oA-0deGraceHopper(1949).

•  Linguagensdeprogramaçãodiferentespossuemdiferentescompiladores.

• Masomesmocompiladortambémpodecompilarlinguagensdiferentes.

Page 36: Introdução à Linguagens de Programação

Anatomiadeumcompilador

FrontEnd

OMmizadorBackEnd

Fortran

COBOL

Lisp

ARM

x86

PowerPC

Page 37: Introdução à Linguagens de Programação

MáquinasVirtuais

•  UmamáquinavirtualéumhardwareimplementadoemsoDware.

•  Porqueistoéinteressante?•  Quelinguagensexecutamemmáquinasvirtuais?

•  Aindaénecessárioumtradutor?

Page 38: Introdução à Linguagens de Programação

Àsvezes,tudoéinterpretado•  Uminterpretadornãoproduzcódigodemáquina.Aocontrário,elelêocódigodoprogramafonte,einterpretacadacomandoencontrado.

•  Quaisasvantagensdeuminterpretador?

•  Quaislinguagenssãointerpretadas?

•  Seráqueháalgumalinguagemquenecessariamentetenhadeserinterpretada?

•  Essascoisassãoeficiente?

Page 39: Introdução à Linguagens de Programação

Fazemosjust-in->me

•  Algumaslinguagenssãocompiladasenquantoestãosendointerpretadas.– JavaScript,porexemplo.

•  Edeondevemaeficiência?•  Seráquedáparafazermelhorqueumcompiladortradicional?

Page 40: Introdução à Linguagens de Programação

•  Existeumalinguagemdeprogramação“maispoderosa”quetodasasoutras?

•  Seexiste,quelinguageméesta?

• Mascomomedireste“poder”?

Page 41: Introdução à Linguagens de Programação

FácilouDi[cil

1.  EncontrearededeestradasmaiscurtaqueligatodasascidadesdeMinasGerais.

2.  Encontreamenorrotapassandoportodasascidades,semrepeMr.

3.  DadoumprogramaPpararesolver(2),verifiqueseaprimeiracoisaquePimprimeéNovaEra.

Page 42: Introdução à Linguagens de Programação

Háquesermoshumildes

•  AmáquinadeTuringéummodelotéoricoquedefinetodososproblemasquesãocomputáveis.– Estado,fita,leitor,símbolos,instruções.

•  SenãohásoluçãonaMáquinadeTuring,entãonãotemjeitomesmo...

Page 43: Introdução à Linguagens de Programação

LinguagensTuring-Completas

•  SeumalinguageméequivalenteàMáquinadeTuring,entãoelaéTuring-Completa.

•  QuasetodaLPéTuring-Completa.

• Masexistemlinguagensquenãoosão.Algumexemplo?

Page 44: Introdução à Linguagens de Programação

Brain-fuc*

Umarranjomuitogrande,contendonúmeros.Oitocomandos:

>moveumaposiçãoparadireita<moveumaposiçãoparaesquerda+somaumàposiçãocorrente(PC)-subtraiumdaPC.imprimeconteúdodaPC,lêentradaearmazenanaPC[vaiparacomandoapós]sePCézero]voltaparacomandoapós[sePCnãoézero.

Oqueestesprogramasfazem?[-]ou[ > + < - ]

Page 45: Introdução à Linguagens de Programação

•  Essaslinguagenstodasqueagenteviu…Java,PHP,C,Fortran,COBOL,Algol,etc,etc…elassãomuitoparecidas:variáveis,loops,comandos…Seráquenãoexistenenhumoutroparadigmanão?

Page 46: Introdução à Linguagens de Programação

LinguagensImperaMvaseDeclaraMvas

•  LinguagensimperaMvas:– Oprogramasãoinstruções.

– Atribuições,loops,sequências.– Efeitoscolateraiseestado.

•  LinguagensdeclaraMvas:– Oprogramadescreveumaverdade.

– Ausênciadeefeitoscolaterais.– Loopsviachamadadefunçõesrecursivas.

Page 47: Introdução à Linguagens de Programação

SML•  Oprogramaéumconjuntodefunções.– Programassãoprovasporindução.

•  Principaisestruturasdedadossãolistasetuplas.

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)

Page 48: Introdução à Linguagens de Programação

SorMngfun leq a b = a <= b

fun grt 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))

Page 49: Introdução à Linguagens de Programação

Prolog

•  Oprogramaéumconjuntoderestrições:– SeAéverdade,eA!Béverdade,entãoBéverdade.

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).

•  Oqueproduzirábisavo(X, Y)?

Page 50: Introdução à Linguagens de Programação

UmproblemaNP-completo

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).

DadaumalistaLdenúmerosinteiros,existeumasublistaScujasomasejaN?

Page 51: Introdução à Linguagens de Programação

PorquesabermaissobreLPs?

•  Porqueelasestãoaí!•  Algumasdisputassãofascinantes.

•  Ahistóriadelaséincrível.

•  Diferentesproblemaspedemdiferentessoluções.