What's the defensive coding techniques

Some Defensive programming techniques

Here are some defensive programming techniques suggested by some leading computer scientists[citation needed] to avoid creating security problems and software bugs[citation needed] These computer scientists state that while this process can improve general quality of code, it not sufficient to ensure security[citation needed]. See the articles computer insecurity and secure computing for more information.

Defensive software programming principles described by leading proponents[citation needed] include:

Reduce source code complexity

Never make code more complex than necessary. Complexity breeds bugs, including security problems. This goal can conflict with the goal of writing programs that can recover from any error and handle any user input. Handling all unexpected occurrences in a program requires the programmer to add extra code, which may also contain bugs.

 Source code reviews

A source code review is where someone other than the original author performs a code audit. A do-it-yourself security audit is insufficient: the review must be made by a non-author, just as when writing a book, it must be proofread by someone other than the author.

Simply making the code available for others to read (see Free software or Open Source Definition) is insufficient: there is no guarantee that the code will ever be looked at, let alone that it will be rigorously reviewed.

Software testing

Software testing should include both whether the software works as intended, and what is supposed to happen when deliberately bad input is supplied.

Testing tools can capture keystrokes associated with normal operations, then the captured keystroke strings can be copied and edited to try out all permutations of combinations, then extended for later tests after any modifications. Proponents of key logging state[citation needed] that programmers who use this method should make sure that the people whose keystrokes are being captured are aware of this, and for what purpose, to avoid accusations of privacy violation.

Intelligent source code reuse

If possible, reuse code instead of writing from scratch. The idea is to capture the benefits of well written and well tested source code, instead of creating unnecessary bugs.

However, re-using code is not always the best way to go forward, particularly when business logic is involved. Reuse in this case may cause serious business process bugs.

The 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 about 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" [1], 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" *, 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 has 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 (1,2,3). 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.

Secure Input / Output Handling

Managing input is a difficult problem, which is detailed in Secure input and output handling.

Canonicalization

Crackers are likely to invent new kinds of representations of incorrect data.

For example, if you checked if a requested file is not "/etc/passwd", a cracker might pass another variant of this file name, like "/etc/./passwd".

To avoid bugs due to non-canonical input, employ Canonicalization API's.

Principle of least privilege

Employ Principle of least privilege. Avoid having software running in a privileged mode if possible;

  • Never make UNIX programs setuid unless you're really sure they are secure.
  • Never make Windows programs run as Local System service unless you're really sure they are secure.
  • Don't grant more permissions than necessary to large user groups or public/everyone.
  • Don't grant more permissions than necessary to small user groups or specific users.
  • Prefer granting permissions to small user groups or specific users, rather than granting permissions to large user groups or public/everyone. It is better if a few users have high permissions, rather than many users having high permissions.

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 techniques

  • One of the most common problems is unchecked use of constant-size structures and functions for dynamic-size data (the buffer overflow problem). This is especially common for string data in C. 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 sanitising it before using it.
  • Encrypt/authenticate all important data transmitted over networks. Do not attempt to implement your own encryption scheme, but use a proven one instead.
  • All data is important until proven otherwise.
  • All data is tainted until proved otherwise.
  • All code is insecure until proven otherwise.
    • You cannot prove the security of any code in userland, or, more canonically: "never trust the client".
  • If data are checked for correctness, verify that they are correct, not that they are incorrect.
  • Design by Contract
    • Design by contract uses preconditions, postconditions and invariants to ensure that provided data (and the state of the program as a whole) is sanitized. This allows code to document its assumptions and make them safely. This may involve checking arguments to a function or method for validity before executing the body of the function. After the body of a function, doing a check of object state (in Object-oriented programming languages) or other held data and the return value before exits (break/return/throw/error code) is also wise.
  • Assertions
    • Within functions, you may want to check that you are not referencing something that is not valid (i.e., null) and that array lengths are valid before referencing elements, especially on all temporary/local instantiations. A good heuristic is to not trust the libraries you did not write either. So any time you call them, check what you get back from them. It often helps to create a small library of "asserting" and "checking" functions to do this along with a logger so you can trace your path and reduce the need for extensive debugging cycles in the first place. With the advent of logging libraries and Aspect Oriented Programming, many of the tedious aspects of defensive programming are mitigated.
  • Prefer exceptions to return codes
    • Generally speaking, it is preferable to throw intelligible exception messages that enforce part of your API contract and guide the client programmer instead of returning values that a client programmer is likely to be unprepared for and hence minimize their complaints and increase robustness and security of your software.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
代码下载:完整代码,可直接运行 ;运行版本:2022a或2019b或2014a;若运行有问题,可私信博主; **仿真咨询 1 各类智能优化算法改进及应用** 生产调度、经济调度、装配线调度、充电优化、车间调度、发车优化、水库调度、三维装箱、物流选址、货位优化、公交排班优化、充电桩布局优化、车间布局优化、集装箱船配载优化、水泵组合优化、解医疗资源分配优化、设施布局优化、可视域基站和无人机选址优化 **2 机器学习和深度学习方面** 卷积神经网络(CNN)、LSTM、支持向量机(SVM)、最小二乘支持向量机(LSSVM)、极限学习机(ELM)、核极限学习机(KELM)、BP、RBF、宽度学习、DBN、RF、RBF、DELM、XGBOOST、TCN实现风电预测、光伏预测、电池寿命预测、辐射源识别、交通流预测、负荷预测、股价预测、PM2.5浓度预测、电池健康状态预测、水体光学参数反演、NLOS信号识别、地铁停车精准预测、变压器故障诊断 **3 图像处理方面** 图像识别、图像分割、图像检测、图像隐藏、图像配准、图像拼接、图像融合、图像增强、图像压缩感知 **4 路径规划方面** 旅行商问题(TSP)、车辆路径问题(VRP、MVRP、CVRP、VRPTW等)、无人机三维路径规划、无人机协同、无人机编队、机器人路径规划、栅格地图路径规划、多式联运运输问题、车辆协同无人机路径规划、天线线性阵列分布优化、车间布局优化 **5 无人机应用方面** 无人机路径规划、无人机控制、无人机编队、无人机协同、无人机任务分配 **6 无线传感器定位及布局方面** 传感器部署优化、通信协议优化、路由优化、目标定位优化、Dv-Hop定位优化、Leach协议优化、WSN覆盖优化、组播优化、RSSI定位优化 **7 信号处理方面** 信号识别、信号加密、信号去噪、信号增强、雷达信号处理、信号水印嵌入提取、肌电信号、脑电信号、信号配时优化 **8 电力系统方面** 微电网优化、无功优化、配电网重构、储能配置 **9 元胞自动机方面** 交通流 人群疏散 病毒扩散 晶体生长 **10 雷达方面** 卡尔曼滤波跟踪、航迹关联、航迹融合

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值