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 <gerald@impressive.net>". 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:

此條目之中立性有争议。其內容、語調可能帶有明顯的個人觀點或地方色彩。 (2011年6月)加上此模板的編輯者需在討論頁說明此文中立性有爭議的原因,以便讓各編輯者討論和改善。在編輯之前請務必察看讨论页。 格奥尔基·季米特洛夫保加利亚共产党中央委员会总书记任期1948年8月—1949年7月2日前任自己(第一书记)继任维尔科·契尔文科夫保加利亚共产党中央委员会第一书…

尊敬的拿督赛夫丁阿都拉Saifuddin bin Abdullah国会议员馬來西亞国会下议院英迪拉马哥打现任就任日期2018年7月16日 (2018-07-16)前任法兹阿都拉曼(希盟公正党)多数票10,950(2018) 马来西亚外交部长任期2021年8月30日—2022年11月24日君主最高元首苏丹阿都拉首相依斯迈沙比里副职卡玛鲁丁查化(国盟土团党)前任希山慕丁(国阵巫统)继任赞比里(国阵巫统)任期2018年7月2日…

土库曼斯坦总统土库曼斯坦国徽土库曼斯坦总统旗現任谢尔达尔·别尔德穆哈梅多夫自2022年3月19日官邸阿什哈巴德总统府(Oguzkhan Presidential Palace)機關所在地阿什哈巴德任命者直接选举任期7年,可连选连任首任萨帕尔穆拉特·尼亚佐夫设立1991年10月27日 土库曼斯坦土库曼斯坦政府与政治 国家政府 土库曼斯坦宪法 国旗 国徽 国歌 立法機關(英语:National Council of Turkmenistan) 土…

土库曼斯坦总统土库曼斯坦国徽土库曼斯坦总统旗現任谢尔达尔·别尔德穆哈梅多夫自2022年3月19日官邸阿什哈巴德总统府(Oguzkhan Presidential Palace)機關所在地阿什哈巴德任命者直接选举任期7年,可连选连任首任萨帕尔穆拉特·尼亚佐夫设立1991年10月27日 土库曼斯坦土库曼斯坦政府与政治 国家政府 土库曼斯坦宪法 国旗 国徽 国歌 立法機關(英语:National Council of Turkmenistan) 土…

TD Systems BaskoniaLigaLiga ACBEuroLeagueDibentuk26 Desember 1959; 64 tahun lalu (1959-12-26)Sejarah Daftar Club Deportivo Vasconia(1959–1976) Club Deportivo Basconia(1976–1987) Saski-Baskonia S.A.D.(1988–sekarang) ArenaFernando Buesa ArenaKapasitas15,504LetakVitoria-Gasteiz, SpanyolWarna timMerah, Biru, Putih     PresidenJosé Antonio QuerejetaPelatih kepalaDuško IvanovićPemilikJosé Antonio Querejeta (57.62%)Juara4 Kejuaraan Spanyol6 Piala Spanyol4 Piala Super Spany…

العلاقات المغربية الصربية المغرب صربيا   المغرب   صربيا تعديل مصدري - تعديل   العلاقات المغربية الصربية هي العلاقات الثنائية التي تجمع بين المغرب وصربيا.[1][2][3][4][5] العلاقة الدبلوماسية بين المغرب وصربيا هي علاقة تعاونية وديبلوماسية جيدة، تشه…

فلوريان يونجفيرث (بالألمانية: Florian Jungwirth) يونجفيرث مع سان خوسيه إيرثكويكس عام 2017 معلومات شخصية الاسم الكامل فلوريان يونجفيرث[1] الميلاد 27 يناير 1989 (العمر 35 سنة)غرافلفينغ، ألمانيا الغربية الطول 1.81 م (5 قدم 11 1⁄2 بوصة) مركز اللعب مدافع / وسط الجنسية ألمانيا معلوما…

الجامعة الإسلامية العالمية، إسلام آباد   معلومات التأسيس 1980 الموقع الجغرافي إحداثيات 33°39′24″N 73°01′29″E / 33.65673056°N 73.02476111°E / 33.65673056; 73.02476111   المكان إسلام آباد البلد باكستان الإدارة الرئيس أحمد يوسف الدريويش العميد منظور أحمد إحصاءات عدد الطلاب 10,000 تقريبا. (سن…

Arlene DahlDahl, 1953LahirArlene Carol Dahl(1925-08-11)11 Agustus 1925[1][2]Minneapolis, Minnesota, A.S.Meninggal29 November 2021(2021-11-29) (umur 96)New York, A.S.AlmamaterUniversitas MinnesotaPekerjaanAktrisTahun aktif1944–2012Suami/istriLex Barker ​ ​(m. 1951; c. 1952)​ Fernando Lamas ​ ​(m. 1954; c. 1960)​ Christian R. Holmes ​ ​(m. 1960;&#…

1935–1945 fascist political party in Hungary Arrow Cross Party – Hungarist Movement Nyilaskeresztes Párt – Hungarista MozgalomLeaderFerenc Szálasi[1]Founded15 March 1939; 85 years ago (15 March 1939)Dissolved7 May 1945; 79 years ago (7 May 1945)Preceded byNSZMP – HM [hu][2]HeadquartersAndrássy út 60, BudapestMembership 300,000 (1939 est.)[3]Ideology Hungarism Agrarianism[4] Hungarian Turanism[5] Hunga…

Road in the Philippines Expressway 1Route informationPart of AH26 Maintained by NLEX Corporation and SMC TPLEX CorporationMajor junctionsMajor intersections N213 (Magalang–Concepcion Road) in Concepcion, Tarlac N2 (MacArthur Highway) in Mabalacat E1 (North Luzon Expressway) in Mabalacat N301 (Roman Superhighway) in Dinalupihan, Bataan E1 (Subic–Clark–Tarlac Expressway) in Mabalacat N3 (Jose Abad Santos Avenue) in San Fernando AH 26 (N1) (Maharlika Highway) in Guiguinto N247 (Plaridel Bypas…

This article needs to be updated. Please help update this article to reflect recent events or newly available information. (November 2010) 2008 U.S. presidential election Timeline General election debates National polling Statewide polling Parties Democratic Party Candidates Debates and forums Primaries National polling Statewide polling Results Nominee Convention superdelegates Republican Party Candidates Debates and forums Primaries National polling Statewide polling Results Nominee Convention…

.kz

.kzDiperkenalkan19 September 1994Jenis TLDTLD kode negara InternetStatusAktifRegistriPusat Informasi Jaringan Kazakhstan (KazNIC)(Казахский центр сетевой информации)SponsorAsosiasi Perusahaan IT KazakhstanPemakaian yang diinginkanEntitas yang terhubung dengan  KazakhstanPemakaian aktualDigunakan di KazakhstanPembatasanHanya ada di tingkat ketigaStrukturRegistrasi dilakukan secara langsung di tingkat kedua, atau ketigaDokumenRulesKebijakan sengketaDispute resol…

「関口博」あるいは「関口博史」とは別人です。 せきぐち ひろし関口 宏本名 関口 宏生年月日 (1943-07-13) 1943年7月13日(80歳)出身地 日本・東京都世田谷区身長 170 cm血液型 A型職業 司会者、タレント、俳優、作詞家ジャンル テレビドラマ、映画活動期間 1963年 -活動内容 テレビドラマ配偶者 西田佐知子(歌手、女優)著名な家族 佐野周二(父) 関口知宏(長男) 佐野守…

Symbol or mark representing linguistic tone ˧ redirects here. For the hangul letter, see ㅓ. For the reversed turnstile, see ⊣. Register tones˥ ˦ ˧ ˨ ˩꜒ ꜓ ꜔ ꜕ ꜖ IPA Number519–523Entity (decimal)&#741;–&#745;EncodingUnicode (hex)U+02E5–U+02E9 Level tones˥ ˧ ˩˥ ˩Long level-tone letters are commonly used for non-checked syllables and short letters for checked syllables, though this is not an IPA distinction. Rising and falling tones[1]˩˥ ˧˥ ˨˦ ˩…

Constellations recognized by the International Astronomical Union IAU designated constellations in equirectangular projection (epoch B1875.0) In contemporary astronomy, 88 constellations are recognized by the International Astronomical Union (IAU).[1] Each constellation is a region of the sky bordered by arcs of right ascension and declination, together covering the entire celestial sphere. Their boundaries were officially adopted by the International Astronomical Union in 1928 and publi…

شمال إفريقيا الفرنسية   معلومات عامة التاريخ 1830-1934 الموقع شمال أفريقيا المتحاربون  فرنسا  الدولة العثمانية إيالة الجزائر تونس في العهد العثماني متمردون مغاربة تعديل مصدري - تعديل   شمال إفريقيا الفرنسية (بالفرنسية: Afrique du Nord française) هو المصطلح الذي يطلق على الأراضي ا…

此條目没有列出任何参考或来源。 (2013年10月29日)維基百科所有的內容都應該可供查證。请协助補充可靠来源以改善这篇条目。无法查证的內容可能會因為異議提出而被移除。 帕拉卡图Paracatu市镇帕拉卡图在巴西的位置坐标:17°13′18″S 46°52′30″W / 17.2217°S 46.875°W / -17.2217; -46.875国家巴西州米纳斯吉拉斯州面积 • 总计8,232.233 平方公里(3,178.483…

Lake in Shutesbury, Massachusetts, US Lake WyolaLake WyolaShow map of MassachusettsLake WyolaShow map of the United StatesLocationShutesbury, MassachusettsCoordinates42°30′06″N 72°26′12″W / 42.50167°N 72.43667°W / 42.50167; -72.43667TypeLake then reservoirPrimary inflowsFiske BrookPrimary outflowsSawmill RiverCatchment area6.4 sq mi (16.6 km2)Basin countriesUnited StatesSurface area128 acres (0.5 km2)Average depth11 ft (3.4 m…

Japanese epic compiled prior to 1330 The Heike Story redirects here. For the anime television series, see The Heike Story (anime). Detail of a screen painting depicting scenes from The Tales of Heike The Tale of the Heike (平家物語, Heike Monogatari) is an epic account compiled prior to 1330 of the struggle between the Taira clan and Minamoto clan for control of Japan at the end of the 12th century in the Genpei War (1180–1185). It has been translated into English at least five times, the …