Главная » Все файлы » Просмотр файлов из архивов » PDF-файлы » 2005. Programming Languages Security - A Survey

2005. Programming Languages Security - A Survey, страница 2

PDF-файл 2005. Programming Languages Security - A Survey, страница 2 Конструирование компиляторов (53037): Статья - 7 семестр2005. Programming Languages Security - A Survey: Конструирование компиляторов - PDF, страница 2 (53037) - СтудИзба2019-09-18СтудИзба

Описание файла

PDF-файл из архива "2005. Programming Languages Security - A Survey", который расположен в категории "". Всё это находится в предмете "конструирование компиляторов" из 7 семестр, которые можно найти в файловом архиве МГУ им. Ломоносова. Не смотря на прямую связь этого архива с МГУ им. Ломоносова, его также можно найти и в других разделах. .

Просмотр PDF-файла онлайн

Текст 2 страницы из PDF

Computers internally do not distinguish betweenthe way signed and unsigned variables are stored leading tothis type of insidious bug.If a programmer passes a signed negative integer as an argument to a function expecting an unsigned value, such asmemcpy(), the signed negative integer will bypass any sizechecks and be implicitly cast to an unsigned integer. This castwill cause the value passed to wrap around and become a largeunsigned positive value. If this value is now used as the lengthof bytes that memcpy() has to copy from source to destination it will result in memcpy() copying well past the end ofthe destination buffer resulting in a buffer overflow.Bugs could also arise if an integer overflows and wrapsaround to a negative number.

For example, the addition oftwo large signed positive integers (say, s1 and s2) could wraparound to form a negative signed integer. This negative signedinteger would pass any maximum size checks but when theindividual values ( i.e. s1 and s2) are used they could belarge enough to write past the end of buffers causing a bufferoverflow.free(x);/* code */free(x);When a program calls free() twice with the same argument, the heap’s memory management data structures become corrupted [29]. This corruption can be exploited by anattacker to execute arbitrary code using the privileges of theexploited application, leading to a partial or total compromiseof the system.2.3Format String BugsFormat string bugs are caused by unfiltered user input that ispassed as the format string argument to specific C formattingfunctions, such as those of the printf() family of functions.Format strings use format specifiers, such as %s, %x, and%n, to indicate to the compiler the format of the output thatthe function should produce.

Format functions retrieve arguments for the format specifiers off of the stack. For example, printf(‘‘%s’’, buf), here the string buf will bepopped off the stack. However if this statement is carelesslywritten as printf(buf), then buf will be interpreted as aformat string, and will be parsed for any format specifiers itmight have. An attacker can take advantage of this and specify a carefully crafted format string to the format function tocontrol what the function pops from the stack [100].By using the %n formatting specifier, an attacker can causeprintf() to write the number of bytes printed so far into alocation specified by a pointer argument (int *); it can beused to write arbitrary values to arbitrary locations chosen bythe attacker.Format string vulnerabilities can also lead to denial of service attacks by employing numerous instances of the %s format specifier to read data off the stack until the program triesto read from an illegal address (i.e.

an unmapped address),which will cause it to crash.Format string bugs originate because of C’s type-unsafeargument passing mechanisms. Neither the type nor the countof arguments passed are checked at run-time or compile-time.It is the responsibility of the function taking on the argumentsto pop the appropriate number, type, and order of argumentsoff of the stack [17].2.42.5Type-cast MismatchesType-casting refers to converting a variable of one datatypeinto another type.

Conversion can be done either implicitly orexplicitly. Type-casting is risky as it occurs at run-time. Forexample, C compilers only perform simple checks to ensurethat the syntax is correct, but do no additional checking todetermine if the cast is appropriate and will not cause errors.Unsafe casts include floating-point and integer values tocharacters (since all characters have an integer ASCII value),numerical arrays to character arrays and casts between pointers and integers.

Type-casting allows converting any pointerinto any other pointer type, independent of the datatypes theypoint to. These powerful features makes it easy to controllow-level machine details at the cost of sacrificing type safety.Integer InaccuraciesInteger inaccuracies [5] fall into two classes: integer overflowsand integer signedness errors.Integer overflow errors occur when an integer either becomes greater than its datatype’s maximum value or smaller32.6Memory Leaks3.1CCured is a type-safe implementation of C that statically attempts to verify that source code is free from memory errors,and introduces run-time checks where static analysis does notguarantee safety [62].

CCured seeks to transform C programsinto equivalent memory-safe versions, and its main aim is tobring safety to legacy applications [12]. It can also function asa debugging tool as it necessitates that a program be memorysafe. The CCured System is shown in Figure 3.It consists of several components: an OCaml translator, aset of Perl scripts that are used to invoke the CCured application, and a run-time library.CCured uses a type system that broadens the existing Ctype system, by differentiating pointer types according to theway they are used in a program. It employs a type-inferencealgorithm that analyzes the program and is able to deduce theapt pointer type for all the pointers in the program. The intentof this distinction is to prevent misuse of pointers, and thusensure that programs do not access memory areas they shouldnot. It uses three types of pointers that differ in their speedand capabilities.Pointers in C programs that have no casts or arithmeticoperations performed on them are marked as SAFE pointers.Such pointers can be either NULL or valid references, and sothe only checking that needs to be done are NULL checks.Pointers that are not involved in casts but have arithmetic operations performed on them are marked as SEQ pointers.

SEQpointers carry additional information, such as array boundsdetails, which are necessary for performing run-time checks.When used, these pointers have NULL and run-time boundschecks performed on them. Wild (WILD) pointers are pointers whose type cannot be determined statically as they are involved in type-casts, they require NULL, bounds and run-timetype checking.This mode of pointer treatment that requires few changes(unlike other safe languages, such as Cyclone) to legacy Ccode, to make it able to be compiled with CCured is a greatadvantage of CCured.CCured prevents dangling pointer dereferences, by using agarbage collector for memory management. Memory is notallowed to be explicitly deallocated (by making free() donothing), instead memory is reclaimed using the conservativeBoehm-Demers-Weiser [6] garbage collector. When an object is freed under CCured, the storage is not immediately reclaimed, but rather marked as inaccessible.

Subsequent accesses check the mark and signal an error when the objectis dereferenced. Ultimately, the mark is reclaimed with thegarbage collector to avoid leaks. The garbage collector results in programmers having less control over memory management.Certain programs fail to release all the memory that they allocate resulting in unnecessary memory consumption over time.This failure to deallocate needless blocks of memory is calleda memory leak. These programs will experience a degradationin performance and will eventually crash when they run outof memory. Typical memory leaks involve unreachable dynamically allocated memory as a consequence of having thepointer that pointed to that piece of memory being destroyed.Attackers can deliberately induce a memory leak to launcha denial of service attack or take advantage of other unpredictable program behavior due to a low memory condition [96].2.7Race ConditionsRace conditions are undesired situations that occur as a resultof incorrectly moderated accesses to a shared resource.File-based race conditions such as the time-of-check-timeof-use (TOCTOU) race condition are well known securityflaws.

Issues crop up when a process checks some propertyon a file (such as whether it exists or not), then later uses thefile with the assumption that the recently checked informationis still true. Even if the use comes immediately after the check,there is often some considerable chance that a second processcan invalidate the check in a malicious way. This situation canbe exploited to launch a privilege escalation attack.For example, a privileged program might open a temporaryfile “tmp/foo” after checking to see that it does not alreadyexist.

After the check, but before the file is actually opened, amalicious attacker could replace that file with a symbolic linkto the system password file “/etc/passwd”. The attackerthen types his new password file and saves it [91]. Here theattacker has managed to deceive the program into performing an operation that would otherwise be prohibited and hasthereby gained elevated privileges.3CCuredSafe Programming LanguagesSafe programming languages are languages in which most ofthe above vulnerabilities have been made hard or eliminated.By coding in these safer languages it is unlikely that programs will suffer from common security vulnerabilities suchas buffer overflows, dangling pointers and format string attacks.

To benefit from these languages, programmers needto either implement a program using them or port an existingprogram into them.4Memory-safetyC source codeCCured TranslatorStatically verified andCompile and executeinstrumented C codememory-safe versionviolation: AbortRun normallyFigure 3: The CCured SystemFor type-safety, CCured’s type system is extended “with aphysical subtyping mechanism for handling the upcasts andwith a special kind of pointer that carries run-time type information for handling the downcasts” [15].CCured achieves compatibility with code that has not beencompiled with it by representing arrays and pointers in a compatible format.

CCured separates the additional information(referred to as metadata) that it maintains for its objects andstores that information in a similar but separate data structure.Each value in the original non-CCured program will be represented by two values in the transformed program – one fordata and one for metadata. Similarly, each operation in theoriginal non-CCured program is split into two – one operation on the data value and one on the metadata value.

However, integrating some third-party libraries (especially thosecontaining pointers in the data structures) with the CCuredtype system might be difficult.The CCured authors carried out experiments to measurethe performance cost of run-time checks inserted by CCuredand report that, “for almost all the benchmarks, CCured’ssafety checks added between 3% and 87% to the runningtimes of these tests.”Many of CCured’s design decisions are due to the fact thatit is most concerned with porting legacy code with minimalchanges.CCured works on Linux and Microsoft Windows (Win95operation is undependable but Win98, Win2k or WinXPshould work). It may also work on other systems that useGCC, however the CCured authors have not attempted it. Inaddition, since the translator is written in OCaml it would require OCaml to be installed in order to run.3.2In some cases the Cyclone compiler might decline fromcompiling a program.

This could be because the program hasbeen found to be unsafe or because a static analysis of theinstrumented source code was not adequate to provide safetyguarantees. In such cases, the programmer can modify theprogram to include more informative annotations that eitheraid in static analysis, or cause the program to maintain additional information needed for run-time checks.Cyclone ensures type-safety while endeavoring to maintainlow-level control over aspects such as data representation andmemory management. Porting legacy C to Cyclone has beenfound to require an alteration in about 8% of the code.According to Grossman et al. [33], one of the most interesting aspects of Cyclone is the implemented prevention mechanisms to handle dangling pointer dereferences and memoryleaks.To prevent safety violations, such as NULL dereferences,Cyclone introduces new kinds of pointers, such as the“never-NULL” pointer, denoted with a “@”.

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
5137
Авторов
на СтудИзбе
440
Средний доход
с одного платного файла
Обучение Подробнее