Defensive programming

Defensive programming is a form of defensive design intended to develop programs that are capable of detecting potential security abnormalities and make predetermined responses.[1] It ensures the continuing function of a piece of software under unforeseen circumstances. Defensive programming practices are often used where high availability, safety, or security is needed.

Defensive programming is an approach to improve software and source code, in terms of:

  • General quality – reducing the number of software bugs and problems.
  • Making the source code comprehensible – the source code should be readable and understandable so it is approved in a code audit.
  • Making the software behave in a predictable manner despite unexpected inputs or user actions.

Overly defensive programming, however, may safeguard against errors that will never be encountered, thus incurring run-time and maintenance costs.

Secure programming

Secure programming is the subset of defensive programming concerned with computer security. Security is the concern, not necessarily safety or availability (the software may be allowed to fail in certain ways). As with all kinds of defensive programming, avoiding bugs is a primary objective; however, the motivation is not as much to reduce the likelihood of failure in normal operation (as if safety were the concern), but to reduce the attack surface – the programmer must assume that the software might be misused actively to reveal bugs, and that bugs could be exploited maliciously.

int risky_programming(char *input) {
  char str[1000]; 
  
  // ...
  
  strcpy(str, input);  // Copy input.
  
  // ...
}

The function will result in undefined behavior when the input is over 1000 characters. Some programmers may not feel that this is a problem, supposing that no user will enter such a long input. This particular bug demonstrates a vulnerability which enables buffer overflow exploits. Here is a solution to this example:

int secure_programming(char *input) {
  char str[1000+1];  // One more for the null character.

  // ...

  // Copy input without exceeding the length of the destination.
  strncpy(str, input, sizeof(str));

  // If strlen(input) >= sizeof(str) then strncpy won't null terminate. 
  // We counter this by always setting the last character in the buffer to NUL,
  // effectively cropping the string to the maximum length we can handle.
  // One can also decide to explicitly abort the program if strlen(input) is 
  // too long.
  str[sizeof(str) - 1] = '\0';

  // ...
}

Offensive programming

Offensive programming is a category of defensive programming, with the added emphasis that certain errors should not be handled defensively. In this practice, only errors from outside the program's control are to be handled (such as user input); the software itself, as well as data from within the program's line of defense, are to be trusted in this methodology.

Trusting internal data validity

Overly defensive programming
const char* trafficlight_colorname(enum traffic_light_color c) {
    switch (c) {
        case TRAFFICLIGHT_RED:    return "red";
        case TRAFFICLIGHT_YELLOW: return "yellow";
        case TRAFFICLIGHT_GREEN:  return "green";
    }
    return "black"; // To be handled as a dead traffic light.
}
Offensive programming
const char* trafficlight_colorname(enum traffic_light_color c) {
    switch (c) {
        case TRAFFICLIGHT_RED:    return "red";
        case TRAFFICLIGHT_YELLOW: return "yellow";
        case TRAFFICLIGHT_GREEN:  return "green";
    }
    assert(0); // Assert that this section is unreachable.
}

Trusting software components

Overly defensive programming
if (is_legacy_compatible(user_config)) {
    // Strategy: Don't trust that the new code behaves the same
    old_code(user_config);
} else {
    // Fallback: Don't trust that the new code handles the same cases
    if (new_code(user_config) != OK) {
        old_code(user_config);
    }
}
Offensive programming
// Expect that the new code has no new bugs
if (new_code(user_config) != OK) {
    // Loudly report and abruptly terminate program to get proper attention
    report_error("Something went very wrong");
    exit(-1);
}

Techniques

Here are some defensive programming techniques:

Intelligent source code reuse

If existing code is tested and known to work, reusing it may reduce the chance of bugs being introduced.

However, reusing code is not always good practice. Reuse of existing code, especially when widely distributed, can allow for exploits to be created that target a wider audience than would otherwise be possible and brings with it all the security and vulnerabilities of the reused code.

When considering using existing source code, a quick review of the modules(sub-sections such as classes or functions) will help eliminate or make the developer aware of any potential vulnerabilities and ensure it is suitable to use in the project. [citation needed]

Legacy problems

Before reusing old source code, libraries, APIs, configurations and so forth, it must be considered if the old work is valid for reuse, or if it is likely to be prone to legacy problems.

Legacy problems are problems inherent when old designs are expected to work with today's requirements, especially when the old designs were not developed or tested with those requirements in mind.

Many software products have experienced problems with old legacy source code; for example:

  • Legacy code may not have been designed under a defensive programming initiative, and might therefore be of much lower quality than newly designed source code.
  • Legacy code may have been written and tested under conditions which no longer apply. The old quality assurance tests may have no validity any more.
    • Example 1: legacy code may have been designed for ASCII input but now the input is UTF-8.
    • Example 2: legacy code may have been compiled and tested on 32-bit architectures, but when compiled on 64-bit architectures, new arithmetic problems may occur (e.g., invalid signedness tests, invalid type casts, etc.).
    • Example 3: legacy code may have been targeted for offline machines, but becomes vulnerable once network connectivity is added.
  • Legacy code is not written with new problems in mind. For example, source code written in 1990 is likely to be prone to many code injection vulnerabilities, because most such problems were not widely understood at that time.

Notable examples of the legacy problem:

  • BIND 9, presented by Paul Vixie and David Conrad as "BINDv9 is a complete rewrite", "Security was a key consideration in design",[2] naming security, robustness, scalability and new protocols as key concerns for rewriting old legacy code.
  • Microsoft Windows suffered from "the" Windows Metafile vulnerability and other exploits related to the WMF format. Microsoft Security Response Center describes the WMF-features as "Around 1990, WMF support was added... This was a different time in the security landscape... were all completely trusted",[3] not being developed under the security initiatives at Microsoft.
  • Oracle is combating legacy problems, such as old source code written without addressing concerns of SQL injection and privilege escalation, resulting in many security vulnerabilities which have taken time to fix and also generated incomplete fixes. This has given rise to heavy criticism from security experts such as David Litchfield, Alexander Kornbrust, Cesar Cerrudo.[4][5][6] An additional criticism is that default installations (largely a legacy from old versions) are not aligned with their own security recommendations, such as Oracle Database Security Checklist, which is hard to amend as many applications require the less secure legacy settings to function correctly.

Canonicalization

Malicious users are likely to invent new kinds of representations of incorrect data. For example, if a program attempts to reject accessing the file "/etc/passwd", a cracker might pass another variant of this file name, like "/etc/./passwd". Canonicalization libraries can be employed to avoid bugs due to non-canonical input.

Low tolerance against "potential" bugs

Assume that code constructs that appear to be problem prone (similar to known vulnerabilities, etc.) are bugs and potential security flaws. The basic rule of thumb is: "I'm not aware of all types of security exploits. I must protect against those I do know of and then I must be proactive!".

Other ways of securing code

  • One of the most common problems is unchecked use of constant-size or pre-allocated structures for dynamic-size data[citation needed] such as inputs to the program (the buffer overflow problem). This is especially common for string data in C[citation needed]. C library functions like gets should never be used since the maximum size of the input buffer is not passed as an argument. C library functions like scanf can be used safely, but require the programmer to take care with the selection of safe format strings, by sanitizing it before using it.
  • Encrypt/authenticate all important data transmitted over networks. Do not attempt to implement your own encryption scheme, use a proven one instead. Message checking with CRC or similar technology will also help secure data sent over a network.

The three rules of data security

  • All data is important until proven otherwise.
  • All data is tainted until proven otherwise.
  • All code is insecure until proven otherwise.
    • You cannot prove the security of any code in userland, or, more commonly known as: "never trust the client".

These three rules about data security describe how to handle any data, internally or externally sourced:

All data is important until proven otherwise - means that all data must be verified as garbage before being destroyed.

All data is tainted until proven otherwise - means that all data must be handled in a way that does not expose the rest of the runtime environment without verifying integrity.

All code is insecure until proven otherwise - while a slight misnomer, does a good job reminding us to never assume our code is secure as bugs or undefined behavior may expose the project or system to attacks such as common SQL injection attacks.

More Information

  • If data is to be checked for correctness, verify that it is correct, not that it is incorrect.
  • Design by contract
  • Assertions (also called assertive programming)
  • Prefer exceptions to return codes
    • Generally speaking, it is preferable[according to whom?] to throw exception messages that enforce part of your API contract and guide the developer instead of returning error code values that do not point to where the exception occurred or what the program stack looked liked, Better logging and exception handling will increase robustness and security of your software[citation needed], while minimizing developer stress[citation needed].

See also

References

  1. ^ Boulanger, Jean-Louis (2016-01-01), Boulanger, Jean-Louis (ed.), "6 - Technique to Manage Software Safety", Certifiable Software Applications 1, Elsevier, pp. 125–156, ISBN 978-1-78548-117-8, retrieved 2022-09-02
  2. ^ "fogo archive: Paul Vixie and David Conrad on BINDv9 and Internet Security by Gerald Oskoboiny <[email protected]>". impressive.net. Retrieved 2018-10-27.
  3. ^ "Looking at the WMF issue, how did it get there?". MSRC. Archived from the original on 2006-03-24. Retrieved 2018-10-27.
  4. ^ Litchfield, David. "Bugtraq: Oracle, where are the patches???". seclists.org. Retrieved 2018-10-27.
  5. ^ Alexander, Kornbrust. "Bugtraq: RE: Oracle, where are the patches???". seclists.org. Retrieved 2018-10-27.
  6. ^ Cerrudo, Cesar. "Bugtraq: Re: [Full-disclosure] RE: Oracle, where are the patches???". seclists.org. Retrieved 2018-10-27.

Read other articles:

CA28Stasiun Aino愛野駅Stasiun Aino pada 2006Lokasi691-8 Aino, Fukuroi-shi, Shizuoka-kenJepangKoordinat34°45′9″N 137°57′42″E / 34.75250°N 137.96167°E / 34.75250; 137.96167Koordinat: 34°45′9″N 137°57′42″E / 34.75250°N 137.96167°E / 34.75250; 137.96167Operator JR CentralJalur Jalur Utama TokaidoLetak234.6 kilometer dari TokyoJumlah peron1 peron pulauInformasi lainStatusMemiliki staf (Midori no Madoguchi)SejarahDibuka22 Ap...

 

 

Ini adalah nama Korea; marganya adalah Choi. Choi DanielLahir22 Februari 1986 (umur 38)Seoul, Korea SelatanPekerjaanAktorTahun aktif2005–sekarangNama KoreaHangul최다니엘 Alih AksaraChoe DanielMcCune–ReischauerCh'oe Taniel Choi Daniel (Hangul:최다니엘) (lahir 22 Februari 1986) adalah aktor asal Korea Selatan. Ia dikenal karena perannya dalam High Kick Through the Roof, Cyrano Agency, dan Baby Faced Beauty.[1][2][3][4][5] Filmografi ...

 

 

Book by Robert Payne Mao Tse-tung: Ruler of Red China First editionAuthorRobert PayneLanguageEnglishGenreBiographiesPublisherHenry SchumanPublication date1950Media typePrint (hardback book)ISBN978-1-4437-2521-7 Mao Tse-tung: Ruler of Red China is a book written by Robert Payne and published by Henry Schuman, New York in 1950, shortly after Mao Zedong (here his name is transliterated as Mao Tse-tung) came to power.[1] Fifteen years before the Cultural Revolution, Payne anticipated...

1848 1852 Élections législatives françaises de 1849 705 députés 13 et 14 mai 1849 Type d’élection Élections législatives Corps électoral et résultats Inscrits 9 936 000 Votants 6 765 000   68,09 %  15,3 Votes exprimés 6 564 000 Blancs et nuls 171 000 Parti de l'Ordre – Odilon Barrot Voix 3 310 000 50,20 %   27,2 Députés élus 450  250 Montagne – Alexandre Ledru-Roll...

 

 

Historic house in Virginia, United States United States historic placePine KnotU.S. National Register of Historic PlacesVirginia Landmarks Register Fenceline at the edge of the propertyShow map of VirginiaShow map of the United StatesLocationVA 712, Glendower, near Charlottesville, VirginiaCoordinates37°51′0″N 78°31′25″W / 37.85000°N 78.52361°W / 37.85000; -78.52361Area90 acres (36 ha)Built1905NRHP reference No.88003211[1]VLR No....

 

 

Town in New South Wales, AustraliaEmmavilleNew South WalesView of EmmavilleEmmavilleCoordinates29°27′S 151°36′E / 29.450°S 151.600°E / -29.450; 151.600Population519 (2016 census)[1]Postcode(s)2371Elevation890 m (2,920 ft)Location 662 km (411 mi) NNE of Sydney 271 km (168 mi) SW of Brisbane 45 km (28 mi) NW of Glen Innes LGA(s)Glen Innes Severn CouncilCountyGoughState electorate(s)Northern TablelandsFederal d...

Земская почтаУезды Алатырский Александрийский Ананьевский Ардатовский Арзамасский Аткарский Ахтырский Балашовский Бахмутский Бежецкий Белебеевский Белозерский Бердянский Бобровский Богородский Богучарский Борисоглебский Боровичский Бронницкий Бугульминский Бу�...

 

 

French footballer Jean-Claude Piumi Personal informationFull name Jean-Claude PiumiDate of birth 27 May 1940Place of birth Giraumont, FranceDate of death 24 March 1996 (1996-03-25) (aged 55)Position(s) DefenderYouth career0000–1959 GiraumontSenior career*Years Team Apps (Gls)1959–1970 Valenciennes 318 (5)1970–1972 Monaco 22 (0)Total 340 (22)International career1962–1967 France 4 (1) *Club domestic league appearances and goals Jean-Claude Piumi (27 May 1940 – 24 March 1...

 

 

义勇军进行曲義勇軍進行曲B. Indonesia: Barisan Para SukarelawanPiringan hitam asli saat lagu dirilis pada tahun 1935Lagu kebangsaan  TiongkokPenulis lirikTian Han, 1934KomponisNie Er, 1935Penggunaan 27 September 1949 (Sementara) 4 Desember 1982 (Resmi)[1] 1 Juli 1997 (Hong Kong) 20 Desember 1999 (Makau) 14 Maret 2004 (Konstitusional) Mars Para Sukarelawan (义勇军进行曲, pinyin: Yìyǒngjūn Jìnxíngqú) adalah lagu kebangsaan Republik Rakyat Tiongkok (RRT)....

American television series This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Gangland TV series – news · newspapers · books · scholar · JSTOR (March 202...

 

 

Australian football club Australian rules football club Burnie DockersNamesFull nameBurnie Dockers Football ClubNickname(s)DockersClub songWe're a happy team at Burnie2020 (NWFL) seasonAfter finalsPremiersLeading goalkickerHarry Walters (25)Club detailsFounded1995; 29 years ago (1995)Colours     CompetitionNWFLPresidentPeter VincentCoachTBAGround(s)West Park, Burnie (capacity: 12,000)Uniforms Home Away Other informationOfficial websiteburniedockers.com.au Burn...

 

 

يفتقر محتوى هذه المقالة إلى الاستشهاد بمصادر. فضلاً، ساهم في تطوير هذه المقالة من خلال إضافة مصادر موثوق بها. أي معلومات غير موثقة يمكن التشكيك بها وإزالتها. (نوفمبر 2023) فرديناند، دوق بريسغاو   معلومات شخصية الميلاد 1 يونيو 1754   قصر شونبرون  الوفاة 24 ديسمبر 1806 (52 سنة) ...

Dalam nama Tionghoa ini, nama keluarganya adalah Ng (Hanzi: 黄; Pinyin: Huáng). DatukNg Moon HingUskup Malaysia Barat dan Uskup Agung Asia Tenggara Uskup Datuk Ng Moon HingNama asal黄满兴黃滿興GerejaPersekutuan AnglikanProvinsi gerejawiGereja Provinsi Asia TenggaraKeuskupanMalaysia BaratTakhtaKatedral Santa Maria, Kuala LumpurAwal masa jabatan2007PendahuluLim Cheng EanImamatTahbisan imamJuni 1985Tahbisan uskup5 Mei 2007oleh Uskup Agung Dr. John Chew dari Asia Tenggara, Us...

 

 

Heinrich Geissler. Heinrich Geissler (1815-1879) adalah seorang ahli mesin, ahli fisika, dan peniup kaca berkebangsaan Jerman.[1] Ia dilaihirkan di kota Ingelshieb, German.[2] Ayahnya adalah seorang pengrajin kaca.[2] Ia memulai bengkel kerjanya di Bonn pada tahun 1852, pada tahun yang sama pula, Geissler bertemu dengan rekan kerjanya, Julius Plücker, seorang ahli matematika dan fisika.[2] Bersama dengan Plucker, Geissler mengerjakan termometer dan tube kapile...

 

 

У Вікіпедії є статті про інші значення цього терміна: 51-ша бригада. 51-ша окрема механізована бригада(2002—2014) 51-ша механізована дивізія(1992—2002)Нарукавний знак бригадиНа службі1992—2014Країна УкраїнаВид Сухопутні військаТип Механізовані військаЧисельністьбригадаУ с...

Imperial Free City of TriesteLibera Città imperiale di Trieste (Italian)Reichsunmittelbare Freistadt Triest (German)1382–18091849–1922 Flag of Austrian Trieste Coat of arms of Trieste (1850–1918) Map of the Austrian Littoral   Princely County of Gorizia and Gradisca   Imperial Free City of Trieste   March of IstriaCapitalTrieste45°38′N 13°48′E / 45.633°N 13.800°E / 45.633; 13.800GovernmentFree cityEmperor Legi...

 

 

This article is about the hospital. For the attached church, see San Giacomo in Augusta. Hospital in Italy, ITOspedale di San Giacomo degli IncurabiliSouthern façade of the Hospital San GiacomoGeographyLocationLazio, Italy, ITOrganisationCare systemSistema Sanitario NazionaleFundingPublic hospitalTypeGeneralPatronSaint JamesServicesEmergency departmentYesBeds170 (2008)HistoryOpened1338Closed2008 The hospital of San Giacomo in Augusta (Saint James in Augusta), also known as San Giacomo degli ...

 

 

1996 studio album by Three 6 MafiaChapter 1: The EndStudio album by Three 6 MafiaReleasedDecember 3, 1996 (1996-12-03)[1]Recorded1995–1996GenreMemphis raphorrorcorehardcore hip hopgangsta rapLength74:30LabelProphetProducerDJ PaulJuicy JThree 6 Mafia chronology Mystic Stylez(1995) Chapter 1: The End(1996) Chapter 2: World Domination(1997) Professional ratingsReview scoresSourceRatingAllMusic[1] The End is the second studio album by American hip hop grou...

Species of bird Yellow-billed jacamar A male yellow-billed jacamar at Presidente Figueiredo, Amazonas state, Brazil Conservation status Least Concern  (IUCN 3.1)[1] Scientific classification Domain: Eukaryota Kingdom: Animalia Phylum: Chordata Class: Aves Order: Piciformes Family: Galbulidae Genus: Galbula Species: G. albirostris Binomial name Galbula albirostrisLatham, 1790 The yellow-billed jacamar (Galbula albirostris) is a species of bird in the family Galbulidae. It is ...

 

 

Lunar impact craterFeature on the moonBoltzmannClementine mosaicCoordinates74°54′S 90°42′W / 74.9°S 90.7°W / -74.9; -90.7Diameter76 kmDepthUnknownColongitude95° at sunriseEponymLudwig Boltzmann Lunar Orbiter 4 image Boltzmann is an old lunar impact crater that is located along the southern limb of the Moon, in the vicinity of the south pole. At this location the crater is viewed from the side from Earth, and so not much detail can be seen. It is located to the...