Как пишется реверс инжиниринг

Reverse engineering (also known as backwards engineering or back engineering) is a process or method through which one attempts to understand through deductive reasoning how a previously made device, process, system, or piece of software accomplishes a task with very little (if any) insight into exactly how it does so. It is essentially the process of opening up or dissecting a system to see how it works, in order to duplicate or enhance it. Depending on the system under consideration and the technologies employed, the knowledge gained during reverse engineering can help with repurposing obsolete objects, doing security analysis, or learning how something works.[1][2]

Although the process is specific to the object on which it is being performed, all reverse engineering processes consist of three basic steps: Information extraction, Modeling, and Review. Information extraction refers to the practice of gathering all relevant information for performing the operation. Modeling refers to the practice of combining the gathered information into an abstract model, which can be used as a guide for designing the new object or system. Review refers to the testing of the model to ensure the validity of the chosen abstract.[1] Reverse engineering is applicable in the fields of computer engineering, mechanical engineering, design, electronic engineering, software engineering, chemical engineering,[3] and systems biology.[4]

Overview[edit]

There are many reasons for performing reverse engineering in various fields. Reverse engineering has its origins in the analysis of hardware for commercial or military advantage.[5]: 13  However, the reverse engineering process, may not always be concerned with creating a copy or changing the artifact in some way. It may be used as part of an analysis to deduce design features from products with little or no additional knowledge about the procedures involved in their original production.[5]: 15 

In some cases, the goal of the reverse engineering process can simply be a redocumentation of legacy systems.[5]: 15 [6] Even when the reverse-engineered product is that of a competitor, the goal may not be to copy it but to perform competitor analysis.[7] Reverse engineering may also be used to create interoperable products and despite some narrowly-tailored United States and European Union legislation, the legality of using specific reverse engineering techniques for that purpose has been hotly contested in courts worldwide for more than two decades.[8]

Software reverse engineering can help to improve the understanding of the underlying source code for the maintenance and improvement of the software, relevant information can be extracted to make a decision for software development and graphical representations of the code can provide alternate views regarding the source code, which can help to detect and fix a software bug or vulnerability. Frequently, as some software develops, its design information and improvements are often lost over time, but that lost information can usually be recovered with reverse engineering. The process can also help to cut down the time required to understand the source code, thus reducing the overall cost of the software development.[9] Reverse engineering can also help to detect and to eliminate a malicious code written to the software with better code detectors. Reversing a source code can be used to find alternate uses of the source code, such as detecting the unauthorized replication of the source code where it was not intended to be used, or revealing how a competitor’s product was built.[10] That process is commonly used for «cracking» software and media to remove their copy protection,[10]: 7  or to create a possibly-improved copy or even a knockoff, which is usually the goal of a competitor or a hacker.[10]: 8 

Malware developers often use reverse engineering techniques to find vulnerabilities in an operating system to build a computer virus that can exploit the system vulnerabilities.[10]: 5  Reverse engineering is also being used in cryptanalysis to find vulnerabilities in substitution cipher, symmetric-key algorithm or public-key cryptography.[10]: 6 

There are other uses to reverse engineering:

  • Interfacing. Reverse engineering can be used when a system is required to interface to another system and how both systems would negotiate is to be established. Such requirements typically exist for interoperability.
  • Military or commercial espionage. Learning about an enemy’s or competitor’s latest research by stealing or capturing a prototype and dismantling it may result in the development of a similar product or a better countermeasure against it.
  • Obsolescence. Integrated circuits are often designed on proprietary systems and built on production lines, which become obsolete in only a few years. When systems using those parts can no longer be maintained since the parts are no longer made, the only way to incorporate the functionality into new technology is to reverse-engineer the existing chip and then to redesign it using newer tools by using the understanding gained as a guide. Another obsolescence originated problem that can be solved by reverse engineering is the need to support (maintenance and supply for continuous operation) existing legacy devices that are no longer supported by their original equipment manufacturer. The problem is particularly critical in military operations.
  • Product security analysis. That examines how a product works by determining the specifications of its components and estimate costs and identifies potential patent infringement. Also part of product security analysis is acquiring sensitive data by disassembling and analyzing the design of a system component.[11] Another intent may be to remove copy protection or to circumvent access restrictions.
  • Competitive technical intelligence. That is to understand what one’s competitor is actually doing, rather than what it says that it is doing.
  • Saving money. Finding out what a piece of electronics can do may spare a user from purchasing a separate product.
  • Repurposing. Obsolete objects are then reused in a different-but-useful manner.
  • Design. Production and design companies applied Reverse Engineering to practical craft-based manufacturing process. The companies can work on “historical” manufacturing collections through 3D scanning, 3D re-modeling and re-design. In 2013 Italian manufactures Baldi and Savio Firmino together with University of Florence optimized their innovation, design, and production processes.[12]

Common uses[edit]

Machines[edit]

As computer-aided design (CAD) has become more popular, reverse engineering has become a viable method to create a 3D virtual model of an existing physical part for use in 3D CAD, CAM, CAE, or other software.[13] The reverse-engineering process involves measuring an object and then reconstructing it as a 3D model. The physical object can be measured using 3D scanning technologies like CMMs, laser scanners, structured light digitizers, or industrial CT scanning (computed tomography). The measured data alone, usually represented as a point cloud, lacks topological information and design intent. The former may be recovered by converting the point cloud to a triangular-faced mesh. Reverse engineering aims to go beyond producing such a mesh and to recover the design intent in terms of simple analytical surfaces where appropriate (planes, cylinders, etc.) as well as possibly NURBS surfaces to produce a boundary-representation CAD model. Recovery of such a model allows a design to be modified to meet new requirements, a manufacturing plan to be generated, etc.

Hybrid modeling is a commonly used term when NURBS and parametric modeling are implemented together. Using a combination of geometric and freeform surfaces can provide a powerful method of 3D modeling. Areas of freeform data can be combined with exact geometric surfaces to create a hybrid model. A typical example of this would be the reverse engineering of a cylinder head, which includes freeform cast features, such as water jackets and high-tolerance machined areas.[14]

Reverse engineering is also used by businesses to bring existing physical geometry into digital product development environments, to make a digital 3D record of their own products, or to assess competitors’ products. It is used to analyze how a product works, what it does, what components it has; estimate costs; identify potential patent infringement; etc.

Value engineering, a related activity that is also used by businesses, involves deconstructing and analyzing products. However, the objective is to find opportunities for cost-cutting.

Printed circuit boards[edit]

[icon]

This section needs expansion. You can help by adding to it. (April 2022)

Reverse engineering of printed circuit boards involves recreating fabrication data for a particular circuit board. This is done to allow benchmarking, and support for legacy systems.

Software[edit]

In 1990, the Institute of Electrical and Electronics Engineers (IEEE) defined (software) reverse engineering (SRE) as «the process of analyzing a
subject system to identify the system’s components and their interrelationships and to create representations of the system in another form or at a higher
level of abstraction» in which the «subject system» is the end product of software development. Reverse engineering is a process of examination only, and the software system under consideration is not modified, which would otherwise be re-engineering or restructuring. Reverse engineering can be performed from any stage of the product cycle, not necessarily from the functional end product.[9]

There are two components in reverse engineering: redocumentation and design recovery. Redocumentation is the creation of new representation of the computer code so that it is easier to understand. Meanwhile, design recovery is the use of deduction or reasoning from general knowledge or personal experience of the product to understand the product’s functionality fully.[9] It can also be seen as «going backwards through the development cycle.»[15] In this model, the output of the implementation phase (in source code form) is reverse-engineered back to the analysis phase, in an inversion of the traditional waterfall model. Another term for this technique is program comprehension.[6] The Working Conference on Reverse Engineering (WCRE) has been held yearly to explore and expand the techniques of reverse engineering.[10][16] Computer-aided software engineering (CASE) and automated code generation have contributed greatly in the field of reverse engineering.[10]

Software anti-tamper technology like obfuscation is used to deter both reverse engineering and re-engineering of proprietary software and software-powered systems. In practice, two main types of reverse engineering emerge. In the first case, source code is already available for the software, but higher-level aspects of the program, which are perhaps poorly documented or documented but no longer valid, are discovered. In the second case, there is no source code available for the software, and any efforts towards discovering one possible source code for the software are regarded as reverse engineering. The second usage of the term is more familiar to most people. Reverse engineering of software can make use of the clean room design technique to avoid copyright infringement.

On a related note, black box testing in software engineering has a lot in common with reverse engineering. The tester usually has the API but has the goals to find bugs and undocumented features by bashing the product from outside.[17]

Other purposes of reverse engineering include security auditing, removal of copy protection («cracking»), circumvention of access restrictions often present in consumer electronics, customization of embedded systems (such as engine management systems), in-house repairs or retrofits, enabling of additional features on low-cost «crippled» hardware (such as some graphics card chip-sets), or even mere satisfaction of curiosity.

Binary software[edit]

Binary reverse engineering is performed if source code for a software is unavailable.[10] This process is sometimes termed reverse code engineering, or RCE.[18] For example, decompilation of binaries for the Java platform can be accomplished by using Jad. One famous case of reverse engineering was the first non-IBM implementation of the PC BIOS, which launched the historic IBM PC compatible industry that has been the overwhelmingly-dominant computer hardware platform for many years. Reverse engineering of software is protected in the US by the fair use exception in copyright law.[19] The Samba software, which allows systems that do not run Microsoft Windows systems to share files with systems that run it, is a classic example of software reverse engineering[20] since the Samba project had to reverse-engineer unpublished information about how Windows file sharing worked so that non-Windows computers could emulate it. The Wine project does the same thing for the Windows API, and OpenOffice.org is one party doing that for the Microsoft Office file formats. The ReactOS project is even more ambitious in its goals by striving to provide binary (ABI and API) compatibility with the current Windows operating systems of the NT branch, which allows software and drivers written for Windows to run on a clean-room reverse-engineered free software (GPL) counterpart. WindowsSCOPE allows for reverse-engineering the full contents of a Windows system’s live memory including a binary-level, graphical reverse engineering of all running processes.

Another classic, if not well-known, example is that in 1987 Bell Laboratories reverse-engineered the Mac OS System 4.1, originally running on the Apple Macintosh SE, so that it could run it on RISC machines of their own.[21]

Binary software techniques[edit]

Reverse engineering of software can be accomplished by various methods.
The three main groups of software reverse engineering are

  1. Analysis through observation of information exchange, most prevalent in protocol reverse engineering, which involves using bus analyzers and packet sniffers, such as for accessing a computer bus or computer network connection and revealing the traffic data thereon. Bus or network behavior can then be analyzed to produce a standalone implementation that mimics that behavior. That is especially useful for reverse engineering device drivers. Sometimes, reverse engineering on embedded systems is greatly assisted by tools deliberately introduced by the manufacturer, such as JTAG ports or other debugging means. In Microsoft Windows, low-level debuggers such as SoftICE are popular.
  2. Disassembly using a disassembler, meaning the raw machine language of the program is read and understood in its own terms, only with the aid of machine-language mnemonics. It works on any computer program but can take quite some time, especially for those who are not used to machine code. The Interactive Disassembler is a particularly popular tool.
  3. Decompilation using a decompiler, a process that tries, with varying results, to recreate the source code in some high-level language for a program only available in machine code or bytecode.

Software classification[edit]

Software classification is the process of identifying similarities between different software binaries (such as two different versions of the same binary) used to detect code relations between software samples. The task was traditionally done manually for several reasons (such as patch analysis for vulnerability detection and copyright infringement), but it can now be done somewhat automatically for large numbers of samples.

This method is being used mostly for long and thorough reverse engineering tasks (complete analysis of a complex algorithm or big piece of software). In general, statistical classification is considered to be a hard problem, which is also true for software classification, and so few solutions/tools that handle this task well.

Source code[edit]

A number of UML tools refer to the process of importing and analysing source code to generate UML diagrams as «reverse engineering.» See List of UML tools.

Although UML is one approach in providing «reverse engineering» more recent advances in international standards activities have resulted in the development of the Knowledge Discovery Metamodel (KDM). The standard delivers an ontology for the intermediate (or abstracted) representation of programming language constructs and their interrelationships. An Object Management Group standard (on its way to becoming an ISO standard as well), KDM has started to take hold in industry with the development of tools and analysis environments that can deliver the extraction and analysis of source, binary, and byte code. For source code analysis, KDM’s granular standards’ architecture enables the extraction of software system flows (data, control, and call maps), architectures, and business layer knowledge (rules, terms, and process). The standard enables the use of a common data format (XMI) enabling the correlation of the various layers of system knowledge for either detailed analysis (such as root cause, impact) or derived analysis (such as business process extraction). Although efforts to represent language constructs can be never-ending because of the number of languages, the continuous evolution of software languages, and the development of new languages, the standard does allow for the use of extensions to support the broad language set as well as evolution. KDM is compatible with UML, BPMN, RDF, and other standards enabling migration into other environments and thus leverage system knowledge for efforts such as software system transformation and enterprise business layer analysis.

Protocols[edit]

Protocols are sets of rules that describe message formats and how messages are exchanged: the protocol state machine. Accordingly, the problem of protocol reverse-engineering can be partitioned into two subproblems: message format and state-machine reverse-engineering.

The message formats have traditionally been reverse-engineered by a tedious manual process, which involved analysis of how protocol implementations process messages, but recent research proposed a number of automatic solutions.[22][23][24] Typically, the automatic approaches group observe messages into clusters by using various clustering analyses, or they emulate the protocol implementation tracing the message processing.

There has been less work on reverse-engineering of state-machines of protocols. In general, the protocol state-machines can be learned either through a process of offline learning, which passively observes communication and attempts to build the most general state-machine accepting all observed sequences of messages, and online learning, which allows interactive generation of probing sequences of messages and listening to responses to those probing sequences. In general, offline learning of small state-machines is known to be NP-complete,[25] but online learning can be done in polynomial time.[26] An automatic offline approach has been demonstrated by Comparetti et al.[24] and an online approach by Cho et al.[27]

Other components of typical protocols, like encryption and hash functions, can be reverse-engineered automatically as well. Typically, the automatic approaches trace the execution of protocol implementations and try to detect buffers in memory holding unencrypted packets.[28]

Integrated circuits/smart cards[edit]

Reverse engineering is an invasive and destructive form of analyzing a smart card. The attacker uses chemicals to etch away layer after layer of the smart card and takes pictures with a scanning electron microscope (SEM). That technique can reveal the complete hardware and software part of the smart card. The major problem for the attacker is to bring everything into the right order to find out how everything works. The makers of the card try to hide keys and operations by mixing up memory positions, such as by bus scrambling.[29][30]

In some cases, it is even possible to attach a probe to measure voltages while the smart card is still operational. The makers of the card employ sensors to detect and prevent that attack.[31] That attack is not very common because it requires both a large investment in effort and special equipment that is generally available only to large chip manufacturers. Furthermore, the payoff from this attack is low since other security techniques are often used such as shadow accounts. It is still uncertain whether attacks against chip-and-PIN cards to replicate encryption data and then to crack PINs would provide a cost-effective attack on multifactor authentication.

Full reverse engineering proceeds in several major steps.

The first step after images have been taken with a SEM is stitching the images together, which is necessary because each layer cannot be captured by a single shot. A SEM needs to sweep across the area of the circuit and take several hundred images to cover the entire layer. Image stitching takes as input several hundred pictures and outputs a single properly-overlapped picture of the complete layer.

Next, the stitched layers need to be aligned because the sample, after etching, cannot be put into the exact same position relative to the SEM each time. Therefore, the stitched versions will not overlap in the correct fashion, as on the real circuit. Usually, three corresponding points are selected, and a transformation applied on the basis of that.

To extract the circuit structure, the aligned, stitched images need to be segmented, which highlights the important circuitry and separates it from the uninteresting background and insulating materials.

Finally, the wires can be traced from one layer to the next, and the netlist of the circuit, which contains all of the circuit’s information, can be reconstructed.

Military applications[edit]

Reverse engineering is often used by people to copy other nations’ technologies, devices, or information that have been obtained by regular troops in the fields or by intelligence operations. It was often used during the Second World War and the Cold War. Here are well-known examples from the Second World War and later:

  • Jerry can: British and American forces in WW2 noticed that the Germans had gasoline cans with an excellent design. They reverse-engineered copies of those cans, which cans were popularly known as «Jerry cans.»
  • Panzerschreck: The Germans captured an American bazooka during the Second World War and reverse engineered it to create the larger Panzerschreck.
  • Tupolev Tu-4: In 1944, three American B-29 bombers on missions over Japan were forced to land in the Soviet Union. The Soviets, who did not have a similar strategic bomber, decided to copy the B-29. Within three years, they had developed the Tu-4, a nearly-perfect copy.[32]
  • SCR-584 radar: copied by the Soviet Union after the Second World War, it is known for a few modifications — СЦР-584, Бинокль-Д.
  • V-2 rocket: Technical documents for the V-2 and related technologies were captured by the Western Allies at the end of the war. The Americans focused their reverse engineering efforts via Operation Paperclip, which led to the development of the PGM-11 Redstone rocket.[33] The Soviets used captured German engineers to reproduce technical documents and plans and worked from captured hardware to make their clone of the rocket, the R-1. Thus began the postwar Soviet rocket program, which led to the R-7 and the beginning of the space race.
  • K-13/R-3S missile (NATO reporting name AA-2 Atoll), a Soviet reverse-engineered copy of the AIM-9 Sidewinder, was made possible after a Taiwanese (ROCAF) AIM-9B hit a Chinese PLA MiG-17 without exploding in September 1958.[34] The missile became lodged within the airframe, and the pilot returned to base with what Soviet scientists would describe as a university course in missile development.
  • BGM-71 TOW missile: In May 1975, negotiations between Iran and Hughes Missile Systems on co-production of the TOW and Maverick missiles stalled over disagreements in the pricing structure, the subsequent 1979 revolution ending all plans for such co-production. Iran was later successful in reverse-engineering the missile and now produces its own copy, the Toophan.
  • China has reversed engineered many examples of Western and Russian hardware, from fighter aircraft to missiles and HMMWV cars, such as the MiG-15,17,19,21 (which became the J-2,5,6,7) and the Su-33 (which became the J-15).[35] More recent analyses of China’s military growth have pointed to the inherent limitations of habitual reverse engineering for advanced weapon systems.[36]
  • During the Second World War, Polish and British cryptographers studied captured German «Enigma» message encryption machines for weaknesses. Their operation was then simulated on electromechanical devices, «bombes», which tried all the possible scrambler settings of the «Enigma» machines that helped the breaking of coded messages that had been sent by the Germans.
  • Also during the Second World War, British scientists analyzed and defeated a series of increasingly-sophisticated radio navigation systems used by the Luftwaffe to perform guided bombing missions at night. The British countermeasures to the system were so effective that in some cases, German aircraft were led by signals to land at RAF bases since they believed that they had returned to German territory.

Gene networks[edit]

Reverse engineering concepts have been applied to biology as well, specifically to the task of understanding the structure and function of gene regulatory networks. They regulate almost every aspect of biological behavior and allow cells to carry out physiological processes and responses to perturbations. Understanding the structure and the dynamic behavior of gene networks is therefore one of the paramount challenges of systems biology, with immediate practical repercussions in several applications that are beyond basic research.[37]
There are several methods for reverse engineering gene regulatory networks by using molecular biology and data science methods. They have been generally divided into six classes:[38]

The six classes of gene network inference methods, according to[38]

  • Coexpression methods are based on the notion that if two genes exhibit a similar expression profile, they may be related although no causation can be simply inferred from coexpression.
  • Sequence motif methods analyze gene promoters to find specific transcription factor binding domains. If a transcription factor is predicted to bind a promoter of a specific gene, a regulatory connection can be hypothesized.
  • Chromatin ImmunoPrecipitation (ChIP) methods investigate the genome-wide profile of DNA binding of chosen transcription factors to infer their downstream gene networks.
  • Orthology methods transfer gene network knowledge from one species to another.
  • Literature methods implement text mining and manual research to identify putative or experimentally-proven gene network connections.
  • Transcriptional complexes methods leverage information on protein-protein interactions between transcription factors, thus extending the concept of gene networks to include transcriptional regulatory complexes.

Often, gene network reliability is tested by genetic perturbation experiments followed by dynamic modelling, based on the principle that removing one network node has predictable effects on the functioning of the remaining nodes of the network.[39]
Applications of the reverse engineering of gene networks range from understanding mechanisms of plant physiology[40] to the highlighting of new targets for anticancer therapy.[41]

Overlap with patent law[edit]

Reverse engineering applies primarily to gaining understanding of a process or artifact in which the manner of its construction, use, or internal processes has not been made clear by its creator.

Patented items do not of themselves have to be reverse-engineered to be studied, for the essence of a patent is that inventors provide a detailed public disclosure themselves, and in return receive legal protection of the invention that is involved. However, an item produced under one or more patents could also include other technology that is not patented and not disclosed. Indeed, one common motivation of reverse engineering is to determine whether a competitor’s product contains patent infringement or copyright infringement.

Legality[edit]

United States[edit]

In the United States, even if an artifact or process is protected by trade secrets, reverse-engineering the artifact or process is often lawful if it has been legitimately obtained.[42]

Reverse engineering of computer software often falls under both contract law as a breach of contract as well as any other relevant laws. That is because most end-user license agreements specifically prohibit it, and US courts have ruled that if such terms are present, they override the copyright law that expressly permits it (see Bowers v. Baystate Technologies[43][44]). According to Section 103(f) of the Digital Millennium Copyright Act (17 U.S.C. § 1201 (f)), a person in legal possession of a program may reverse-engineer and circumvent its protection if that is necessary to achieve «interoperability,» a term that broadly covers other devices and programs that can interact with it, make use of it, and to use and transfer data to and from it in useful ways. A limited exemption exists that allows the knowledge thus gained to be shared and used for interoperability purposes.[a]

European Union[edit]

EU Directive 2009/24 on the legal protection of computer programs, which superseded an earlier (1991) directive,[45] governs reverse engineering in the European Union.[46][b]
</ref>

See also[edit]

  • Antikythera mechanism
  • Backward induction
  • Benchmarking
  • Bus analyzer
  • Chonda
  • Clone (computing)
  • Clean room design
  • CMM
  • Code morphing
  • Connectix Virtual Game Station
  • Counterfeiting
  • Cryptanalysis
  • Decompile
  • Deformulation
  • Digital Millennium Copyright Act (DMCA)
  • Disassembler
  • Dongle
  • Forensic engineering
  • Industrial CT scanning
  • Interactive Disassembler
  • Knowledge Discovery Metamodel
  • Laser scanner
  • List of production topics
  • Listeroid Engines
  • Logic analyzer
  • Paycheck
  • Product teardown
  • Repurposing
  • Reverse architecture
  • Round-trip engineering
  • Retrodiction
  • Sega v. Accolade
  • Software archaeology
  • Software cracking
  • Structured light digitizer
  • Value engineering

Notes[edit]

  1. ^ The section states:
    (f) Reverse Engineering.—
    (1) Notwithstanding the provisions of subsection (a)(1)(A), a person who has lawfully obtained the right to use a copy of a computer program may circumvent a technological measure that effectively controls access to a particular portion of that program for the sole purpose of identifying and analyzing those elements of the program that are necessary to achieve interoperability of an independently created computer program with other programs, and that have not previously been readily available to the person engaging in the circumvention, to the extent any such acts of identification and analysis do not constitute infringement under this title.
    (2) Notwithstanding the provisions of subsections (a)(2) and (b), a person may develop and employ technological means to circumvent a technological measure, or to circumvent protection afforded by a technological measure, in order to enable the identification and analysis under paragraph (1), or for the purpose of enabling interoperability of an independently created computer program with other programs, if such means are necessary to achieve such interoperability, to the extent that doing so does not constitute infringement under this title.
    (3) The information acquired through the acts permitted under paragraph (1), and the means permitted under paragraph (2), may be made available to others if the person referred to in paragraph (1) or (2), as the case may be, provides such information or means solely for the purpose of enabling interoperability of an independently created computer program with other programs, and to the extent that doing so does not constitute infringement under this title or violate applicable law other than this section.
    (4) For purposes of this subsection, the term 「interoperability」 means the ability of computer programs to exchange information, and of such programs mutually to use the information which has been exchanged.
  2. ^ The directive states:

    The unauthorised reproduction, translation, adaptation or transformation of the form of the code in which a copy of a computer program has been made available constitutes an infringement of the exclusive rights of the author. Nevertheless, circumstances may exist when such a reproduction of the code and translation of its form are indispensable to obtain the necessary information to achieve the interoperability of an independently created program with other programs. It has therefore to be considered that, in these limited circumstances only, performance of the acts of reproduction and translation by or on behalf of a person having a right to use a copy of the program is legitimate and compatible with fair practice and must therefore be deemed not to require the authorisation of the rightholder. An objective of this exception is to make it possible to connect all components of a computer system, including those of different manufacturers, so that they can work together. Such an exception to the author’s exclusive rights may not be used in a way which prejudices the legitimate interests of the rightholder or which conflicts with a normal exploitation of the program.

References[edit]

  1. ^ a b «What is Reverse-engineering? How Does It Work». SearchSoftwareQuality. Retrieved 2022-07-27.
  2. ^ «Reverse Engineering». ethics.csc.ncsu.edu. Retrieved 2022-07-27.
  3. ^ Thayer, Ken. «How Does Reverse Engineering Work?». globalspec. IEEE Global Spec. Retrieved 26 February 2018.
  4. ^ Villaverde, Alejandro F.; Banga, Julio R. (6 February 2014). «Reverse engineering and identification in systems biology: strategies, perspectives and challenges». Journal of the Royal Society Interface. 11 (91): 20130505. doi:10.1098/rsif.2013.0505. PMC 3869153. PMID 24307566.
  5. ^ a b c Chikofsky, E.J. & Cross, J.H., II (1990). «Reverse Engineering and Design Recovery: A Taxonomy». IEEE Software. 7 (1): 13–17. doi:10.1109/52.43044. S2CID 16266661.
  6. ^ a b A Survey of Reverse Engineering and Program Comprehension. Michael L. Nelson, April 19, 1996, ODU CS 551 – Software Engineering Survey.arXiv:cs/0503068v1
  7. ^ Vinesh Raja; Kiran J. Fernandes (2007). Reverse Engineering: An Industrial Perspective. Springer Science & Business Media. p. 3. ISBN 978-1-84628-856-2.
  8. ^ Jonathan Band; Masanobu Katoh (2011). Interfaces on Trial 2.0. MIT Press. p. 136. ISBN 978-0-262-29446-1.
  9. ^ a b c Chikofsky, E. J.; Cross, J. H. (January 1990). «Reverse engineering and design recovery: A taxonomy» (PDF). IEEE Software. 7: 13–17. doi:10.1109/52.43044. S2CID 16266661. Archived from the original (PDF) on 2018-04-17. Retrieved 2012-07-02.
  10. ^ a b c d e f g h Eilam, Eldad (2005). Reversing: secrets of reverse engineering. John Wiley & Sons. ISBN 978-0-7645-7481-8.
  11. ^ Internet Engineering Task Force RFC 2828 Internet Security Glossary
  12. ^ Karwowski, Waldemar; Trzcielinski, Stefan; Mrugalsk, Beata; DiNicolantonio, Massimo; Rossi, Emilio (2018). Advances in Manufacturing, Production Management and Process Control. pp. 287–288.
  13. ^ Varady, T; Martin, R; Cox, J (1997). «Reverse engineering of geometric models–an introduction». Computer-Aided Design. 29 (4): 255–268. doi:10.1016/S0010-4485(96)00054-1.
  14. ^ «Reverse Engineering».
  15. ^ Warden, R. (1992). Software Reuse and Reverse Engineering in Practice. London, England: Chapman & Hall. pp. 283–305.
  16. ^ «Working Conference on Reverse Engineering (WCRE)». uni-trier.de. Computer Science bibliography. Archived from the original on 14 March 2017. Retrieved 22 February 2018.
  17. ^ Shahbaz, Muzammil (2012). Reverse Engineering and Testing of Black-Box Software Components: by Grammatical Inference techniques. LAP LAMBERT Academic Publishing. ISBN 978-3659140730.
  18. ^ Chuvakin, Anton; Cyrus Peikari (January 2004). Security Warrior (1st ed.). O’Reilly. Archived from the original on 2006-05-22. Retrieved 2006-05-25.
  19. ^ Samuelson, Pamela & Scotchmer, Suzanne (2002). «The Law and Economics of Reverse Engineering». Yale Law Journal. 111 (7): 1575–1663. doi:10.2307/797533. JSTOR 797533. Archived from the original on 2010-07-15. Retrieved 2011-10-31.
  20. ^ «Samba: An Introduction». 2001-11-27. Retrieved 2009-05-07.
  21. ^ Lee, Newton (2013). Counterterrorism and Cybersecurity: Total Information Awareness (2nd ed.). Springer Science+Business Media. p. 110. ISBN 978-1461472049.
  22. ^ W. Cui, J. Kannan, and H. J. Wang. Discoverer: Automatic protocol reverse engineering from network traces. In Proceedings of 16th USENIX Security Symposium on USENIX Security Symposium, pp. 1–14.
  23. ^ W. Cui, M. Peinado, K. Chen, H. J. Wang, and L. Irún-Briz. Tupni: Automatic reverse engineering of input formats. In Proceedings of the 15th ACM Conference on Computer and Communications Security, pp. 391–402. ACM, Oct 2008.
  24. ^ a b P. M. Comparetti, G. Wondracek, C. Kruegel, and E. Kirda. Prospex: Protocol specification extraction. In Proceedings of the 2009 30th IEEE Symposium on Security and Privacy, pp. 110–125, Washington, 2009. IEEE Computer Society.
  25. ^ Gold, E (1978). «Complexity of automaton identification from given data». Information and Control. 37 (3): 302–320. doi:10.1016/S0019-9958(78)90562-4.
  26. ^ D. Angluin (1987). «Learning regular sets from queries and counterexamples». Information and Computation. 75 (2): 87–106. doi:10.1016/0890-5401(87)90052-6.
  27. ^ C.Y. Cho, D. Babic, R. Shin, and D. Song. Inference and Analysis of Formal Models of Botnet Command and Control Protocols, 2010 ACM Conference on Computer and Communications Security.
  28. ^ Polyglot: automatic extraction of protocol message format using dynamic binary analysis. J. Caballero, H. Yin, Z. Liang, and D. Song. Proceedings of the 14th ACM conference on Computer and communications security, pp. 317–329.
  29. ^ Wolfgang Rankl, Wolfgang Effing, Smart Card Handbook (2004)
  30. ^ T. Welz: Smart cards as methods for payment (2008), Seminar ITS-Security Ruhr-Universität Bochum
  31. ^ David C. Musker: Protecting & Exploiting Intellectual Property in Electronics Archived 2011-07-09 at the Wayback Machine, IBC Conferences, 10 June 1998
  32. ^ Yeam Gordon and Vladimir Rigmant, Tupolev Tu-4: Soviet Superfortress (Hinckley, U.K.: Midland, 2002).
  33. ^ «Redstone rocket». centennialofflight.net. Retrieved 2010-04-27.
  34. ^ «The Chinese Air Force: Evolving Concepts, Roles, and Capabilities», Center for the Study of Chinese Military Affairs (U.S), by National Defense University Press, p. 277
  35. ^ Chandrashekar, S., R. Nagappa, L. Sundaresan, and N. Ramani. 2011. Technology & Innovation in China: A Case Study of Single Crystal Superalloy Development for Aircraft Turbine Blades, R4–11. ISSSP National Institute of Advanced Studies, Bangalore. http://isssp.in/wp-content/uploads/2013/01/Technology-and-Innovation-in-China-A-case-Study-of-Single-Crystal4.pdf; and Dillon Zhou, “China J-15 Fighter Jet: Chinese Officials Defend New Fighter As Chinese Original, but Questions Remain,” Mic, December 16, 2012, https://mic.com/articles/20270/china-j-15-fighter-jet-chinese-officials-defend-new-fighter-[permanent dead link] as-chinese-original-but-questions-remain
  36. ^ Andrea Gilli and Mauro Gilli, «Why China Has Not Caught Up Yet: Military-Technological Superiority and the Limits of Imitation, Reverse Engineering, and Cyber Espionage, International Security 43:3 (2019 141-189, https://doi.org/10.1162/isec_a_00337.
  37. ^ Giorgi, Federico M. (2020). «Gene network reverse engineering: The Next Generation». Biochimica et Biophysica Acta (BBA) — Gene Regulatory Mechanisms. 1863 (6): 194523. doi:10.1016/j.bbagrm.2020.194523. hdl:11585/753853. ISSN 1874-9399. PMID 32145356. S2CID 212629142.
  38. ^ a b Mercatelli, Daniele; Scalambra, Laura; Triboli, Luca; Ray, Forest; Giorgi, Federico M. (2020). «Gene regulatory network inference resources: A practical overview». Biochimica et Biophysica Acta (BBA) — Gene Regulatory Mechanisms. 1863 (6): 194430. doi:10.1016/j.bbagrm.2019.194430. ISSN 1874-9399. PMID 31678629. S2CID 207895066.
  39. ^ Tegner, J.; Yeung, M. K. S.; Hasty, J.; Collins, J. J. (2003). «Reverse engineering gene networks: Integrating genetic perturbations with dynamical modeling». Proceedings of the National Academy of Sciences. 100 (10): 5944–5949. Bibcode:2003PNAS..100.5944T. doi:10.1073/pnas.0933416100. ISSN 0027-8424. PMC 156306. PMID 12730377.
  40. ^ Friedel, Swetlana; Usadel, Björn; von Wirén, Nicolaus; Sreenivasulu, Nese (2012). «Reverse Engineering: A Key Component of Systems Biology to Unravel Global Abiotic Stress Cross-Talk». Frontiers in Plant Science. 3: 294. doi:10.3389/fpls.2012.00294. ISSN 1664-462X. PMC 3533172. PMID 23293646.
  41. ^ Lefebvre, Celine; Rieckhof, Gabrielle; Califano, Andrea (2012). «Reverse-engineering human regulatory networks». Wiley Interdisciplinary Reviews: Systems Biology and Medicine. 4 (4): 311–325. doi:10.1002/wsbm.1159. ISSN 1939-5094. PMC 4128340. PMID 22246697.
  42. ^ «Trade Secrets 101», Feature Article, March 2011. ASME. Retrieved on 2013-10-31.
  43. ^ Baystate v. Bowers Discussion. Utsystem.edu. Retrieved on 2011-05-29.
  44. ^ Gross, Grant. (2003-06-26) Contract case could hurt reverse engineering | Developer World. InfoWorld. Retrieved on 2011-05-29.
  45. ^ Council Directive 91/250/EEC of 14 May 1991 on the legal protection of computer programs. Eur-lex.europa.eu. Retrieved on 2011-05-29.
  46. ^ DIRECTIVE 2009/24/EC OF THE EUROPEAN PARLIAMENT AND OF THE COUNCIL of 23 April 2009 on the legal protection of computer programs

Sources[edit]

  • Eilam, Eldad (2005). Reversing: Secrets of Reverse Engineering. Wiley Publishing. p. 595. ISBN 978-0-7645-7481-8.
  • Elvidge, Julia, «Using Reverse Engineering to Discover Patent Infringement,» Chipworks, Sept. 2010. Online: http://www.photonics.com/Article.aspx?AID=44063
  • Cipresso, Teodoro (2009). «Software Reverse Engineering Education». SJSU Master’s Thesis. Retrieved 2009-08-22.
  • Hausi A. Müller and Holger M. Kienle, «A Small Primer on Software Reverse Engineering,» Technical Report, University of Victoria, 17 pages, March 2009. Online: http://holgerkienle.wikispaces.com/file/view/MK-UVic-09.pdf
  • Heines, Henry, «Determining Infringement by X-Ray Diffraction,» Chemical Engineering Process, Jan. 1999 (example of reverse engineering used to detect IP infringement)
  • Huang, Andrew (2003). Hacking the Xbox: An Introduction to Reverse Engineering. No Starch Press. ISBN 978-1593270292.
  • James, Dick (January 19, 2006). «Reverse Engineering Delivers Product Knowledge; Aids Technology Spread». Electronic Design. Penton Media, Inc. Retrieved 2009-02-03.
  • Messler, Robert (2013). Reverse Engineering: Mechanisms, Structures, Systems & Materials. McGraw Hill. ISBN 978-0071825160. (introduction to hardware teardowns, including methodology, goals)
  • Raja, Vinesh; Fernandes, Kiran J. (2008). Reverse Engineering – An Industrial Perspective. Springer. p. 242. ISBN 978-1-84628-855-5.
  • Reverse Engineering for Beginners
  • Samuelson, Pamela and Scotchmer, Suzanne, «The Law and Economics of Reverse Engineering,» 111 Yale L.J. 1575 (2002). Online: http://people.ischool.berkeley.edu/~pam/papers/l&e%20reveng3.pdf
  • Schulman, Andrew; Brown, Ralf D.; Maxey, David; Michels, Raymond J.; Kyle, Jim (1994) [November 1993]. Undocumented DOS: A programmer’s guide to reserved MS-DOS functions and data structures — expanded to include MS-DOS 6, Novell DOS and Windows 3.1 (2 ed.). Reading, Massachusetts: Addison Wesley. pp. 229–241. ISBN 0-201-63287-X. (xviii+856+vi pages, 3.5″-floppy) Errata: [1][2] (NB. On general methodology of reverse engineering, applied to mass-market software: a program for exploring DOS, disassembling DOS.)
  • Schulman, Andrew; et al. (1992). Undocumented Windows: A Programmer’s Guide to Reserved Microsoft Windows API Functions. Addison Wesley. ISBN 978-0-201-60834-2. (pp. 59–188 on general methodology of reverse engineering, applied to mass-market software: examining Windows executables, disassembling Windows, tools for exploring Windows)
  • Schulman, Andrew, «Hiding in Plain Sight: Using Reverse Engineering to Uncover Software Patent Infringement,» Intellectual Property Today, Nov. 2010. Online: http://www.iptoday.com/issues/2010/11/hiding-in-plain-sight-using-reverse-engineering-to-uncover-software-patent-infringement.asp
  • Schulman, Andrew, «Open to Inspection: Using Reverse Engineering to Uncover Software Prior Art,» New Matter (Calif. State Bar IP Section), Summer 2011 (Part 1); Fall 2011 (Part 2). Online: http://www.SoftwareLitigationConsulting.com
  • Thumm, Mike (2007). «Talking Tactics» (PDF). IEEE 2007 Custom Integrated Circuits Conference (CICC). IEEE, Inc. Retrieved 2009-02-03.

Reverse engineering (also known as backwards engineering or back engineering) is a process or method through which one attempts to understand through deductive reasoning how a previously made device, process, system, or piece of software accomplishes a task with very little (if any) insight into exactly how it does so. It is essentially the process of opening up or dissecting a system to see how it works, in order to duplicate or enhance it. Depending on the system under consideration and the technologies employed, the knowledge gained during reverse engineering can help with repurposing obsolete objects, doing security analysis, or learning how something works.[1][2]

Although the process is specific to the object on which it is being performed, all reverse engineering processes consist of three basic steps: Information extraction, Modeling, and Review. Information extraction refers to the practice of gathering all relevant information for performing the operation. Modeling refers to the practice of combining the gathered information into an abstract model, which can be used as a guide for designing the new object or system. Review refers to the testing of the model to ensure the validity of the chosen abstract.[1] Reverse engineering is applicable in the fields of computer engineering, mechanical engineering, design, electronic engineering, software engineering, chemical engineering,[3] and systems biology.[4]

Overview[edit]

There are many reasons for performing reverse engineering in various fields. Reverse engineering has its origins in the analysis of hardware for commercial or military advantage.[5]: 13  However, the reverse engineering process, may not always be concerned with creating a copy or changing the artifact in some way. It may be used as part of an analysis to deduce design features from products with little or no additional knowledge about the procedures involved in their original production.[5]: 15 

In some cases, the goal of the reverse engineering process can simply be a redocumentation of legacy systems.[5]: 15 [6] Even when the reverse-engineered product is that of a competitor, the goal may not be to copy it but to perform competitor analysis.[7] Reverse engineering may also be used to create interoperable products and despite some narrowly-tailored United States and European Union legislation, the legality of using specific reverse engineering techniques for that purpose has been hotly contested in courts worldwide for more than two decades.[8]

Software reverse engineering can help to improve the understanding of the underlying source code for the maintenance and improvement of the software, relevant information can be extracted to make a decision for software development and graphical representations of the code can provide alternate views regarding the source code, which can help to detect and fix a software bug or vulnerability. Frequently, as some software develops, its design information and improvements are often lost over time, but that lost information can usually be recovered with reverse engineering. The process can also help to cut down the time required to understand the source code, thus reducing the overall cost of the software development.[9] Reverse engineering can also help to detect and to eliminate a malicious code written to the software with better code detectors. Reversing a source code can be used to find alternate uses of the source code, such as detecting the unauthorized replication of the source code where it was not intended to be used, or revealing how a competitor’s product was built.[10] That process is commonly used for «cracking» software and media to remove their copy protection,[10]: 7  or to create a possibly-improved copy or even a knockoff, which is usually the goal of a competitor or a hacker.[10]: 8 

Malware developers often use reverse engineering techniques to find vulnerabilities in an operating system to build a computer virus that can exploit the system vulnerabilities.[10]: 5  Reverse engineering is also being used in cryptanalysis to find vulnerabilities in substitution cipher, symmetric-key algorithm or public-key cryptography.[10]: 6 

There are other uses to reverse engineering:

  • Interfacing. Reverse engineering can be used when a system is required to interface to another system and how both systems would negotiate is to be established. Such requirements typically exist for interoperability.
  • Military or commercial espionage. Learning about an enemy’s or competitor’s latest research by stealing or capturing a prototype and dismantling it may result in the development of a similar product or a better countermeasure against it.
  • Obsolescence. Integrated circuits are often designed on proprietary systems and built on production lines, which become obsolete in only a few years. When systems using those parts can no longer be maintained since the parts are no longer made, the only way to incorporate the functionality into new technology is to reverse-engineer the existing chip and then to redesign it using newer tools by using the understanding gained as a guide. Another obsolescence originated problem that can be solved by reverse engineering is the need to support (maintenance and supply for continuous operation) existing legacy devices that are no longer supported by their original equipment manufacturer. The problem is particularly critical in military operations.
  • Product security analysis. That examines how a product works by determining the specifications of its components and estimate costs and identifies potential patent infringement. Also part of product security analysis is acquiring sensitive data by disassembling and analyzing the design of a system component.[11] Another intent may be to remove copy protection or to circumvent access restrictions.
  • Competitive technical intelligence. That is to understand what one’s competitor is actually doing, rather than what it says that it is doing.
  • Saving money. Finding out what a piece of electronics can do may spare a user from purchasing a separate product.
  • Repurposing. Obsolete objects are then reused in a different-but-useful manner.
  • Design. Production and design companies applied Reverse Engineering to practical craft-based manufacturing process. The companies can work on “historical” manufacturing collections through 3D scanning, 3D re-modeling and re-design. In 2013 Italian manufactures Baldi and Savio Firmino together with University of Florence optimized their innovation, design, and production processes.[12]

Common uses[edit]

Machines[edit]

As computer-aided design (CAD) has become more popular, reverse engineering has become a viable method to create a 3D virtual model of an existing physical part for use in 3D CAD, CAM, CAE, or other software.[13] The reverse-engineering process involves measuring an object and then reconstructing it as a 3D model. The physical object can be measured using 3D scanning technologies like CMMs, laser scanners, structured light digitizers, or industrial CT scanning (computed tomography). The measured data alone, usually represented as a point cloud, lacks topological information and design intent. The former may be recovered by converting the point cloud to a triangular-faced mesh. Reverse engineering aims to go beyond producing such a mesh and to recover the design intent in terms of simple analytical surfaces where appropriate (planes, cylinders, etc.) as well as possibly NURBS surfaces to produce a boundary-representation CAD model. Recovery of such a model allows a design to be modified to meet new requirements, a manufacturing plan to be generated, etc.

Hybrid modeling is a commonly used term when NURBS and parametric modeling are implemented together. Using a combination of geometric and freeform surfaces can provide a powerful method of 3D modeling. Areas of freeform data can be combined with exact geometric surfaces to create a hybrid model. A typical example of this would be the reverse engineering of a cylinder head, which includes freeform cast features, such as water jackets and high-tolerance machined areas.[14]

Reverse engineering is also used by businesses to bring existing physical geometry into digital product development environments, to make a digital 3D record of their own products, or to assess competitors’ products. It is used to analyze how a product works, what it does, what components it has; estimate costs; identify potential patent infringement; etc.

Value engineering, a related activity that is also used by businesses, involves deconstructing and analyzing products. However, the objective is to find opportunities for cost-cutting.

Printed circuit boards[edit]

[icon]

This section needs expansion. You can help by adding to it. (April 2022)

Reverse engineering of printed circuit boards involves recreating fabrication data for a particular circuit board. This is done to allow benchmarking, and support for legacy systems.

Software[edit]

In 1990, the Institute of Electrical and Electronics Engineers (IEEE) defined (software) reverse engineering (SRE) as «the process of analyzing a
subject system to identify the system’s components and their interrelationships and to create representations of the system in another form or at a higher
level of abstraction» in which the «subject system» is the end product of software development. Reverse engineering is a process of examination only, and the software system under consideration is not modified, which would otherwise be re-engineering or restructuring. Reverse engineering can be performed from any stage of the product cycle, not necessarily from the functional end product.[9]

There are two components in reverse engineering: redocumentation and design recovery. Redocumentation is the creation of new representation of the computer code so that it is easier to understand. Meanwhile, design recovery is the use of deduction or reasoning from general knowledge or personal experience of the product to understand the product’s functionality fully.[9] It can also be seen as «going backwards through the development cycle.»[15] In this model, the output of the implementation phase (in source code form) is reverse-engineered back to the analysis phase, in an inversion of the traditional waterfall model. Another term for this technique is program comprehension.[6] The Working Conference on Reverse Engineering (WCRE) has been held yearly to explore and expand the techniques of reverse engineering.[10][16] Computer-aided software engineering (CASE) and automated code generation have contributed greatly in the field of reverse engineering.[10]

Software anti-tamper technology like obfuscation is used to deter both reverse engineering and re-engineering of proprietary software and software-powered systems. In practice, two main types of reverse engineering emerge. In the first case, source code is already available for the software, but higher-level aspects of the program, which are perhaps poorly documented or documented but no longer valid, are discovered. In the second case, there is no source code available for the software, and any efforts towards discovering one possible source code for the software are regarded as reverse engineering. The second usage of the term is more familiar to most people. Reverse engineering of software can make use of the clean room design technique to avoid copyright infringement.

On a related note, black box testing in software engineering has a lot in common with reverse engineering. The tester usually has the API but has the goals to find bugs and undocumented features by bashing the product from outside.[17]

Other purposes of reverse engineering include security auditing, removal of copy protection («cracking»), circumvention of access restrictions often present in consumer electronics, customization of embedded systems (such as engine management systems), in-house repairs or retrofits, enabling of additional features on low-cost «crippled» hardware (such as some graphics card chip-sets), or even mere satisfaction of curiosity.

Binary software[edit]

Binary reverse engineering is performed if source code for a software is unavailable.[10] This process is sometimes termed reverse code engineering, or RCE.[18] For example, decompilation of binaries for the Java platform can be accomplished by using Jad. One famous case of reverse engineering was the first non-IBM implementation of the PC BIOS, which launched the historic IBM PC compatible industry that has been the overwhelmingly-dominant computer hardware platform for many years. Reverse engineering of software is protected in the US by the fair use exception in copyright law.[19] The Samba software, which allows systems that do not run Microsoft Windows systems to share files with systems that run it, is a classic example of software reverse engineering[20] since the Samba project had to reverse-engineer unpublished information about how Windows file sharing worked so that non-Windows computers could emulate it. The Wine project does the same thing for the Windows API, and OpenOffice.org is one party doing that for the Microsoft Office file formats. The ReactOS project is even more ambitious in its goals by striving to provide binary (ABI and API) compatibility with the current Windows operating systems of the NT branch, which allows software and drivers written for Windows to run on a clean-room reverse-engineered free software (GPL) counterpart. WindowsSCOPE allows for reverse-engineering the full contents of a Windows system’s live memory including a binary-level, graphical reverse engineering of all running processes.

Another classic, if not well-known, example is that in 1987 Bell Laboratories reverse-engineered the Mac OS System 4.1, originally running on the Apple Macintosh SE, so that it could run it on RISC machines of their own.[21]

Binary software techniques[edit]

Reverse engineering of software can be accomplished by various methods.
The three main groups of software reverse engineering are

  1. Analysis through observation of information exchange, most prevalent in protocol reverse engineering, which involves using bus analyzers and packet sniffers, such as for accessing a computer bus or computer network connection and revealing the traffic data thereon. Bus or network behavior can then be analyzed to produce a standalone implementation that mimics that behavior. That is especially useful for reverse engineering device drivers. Sometimes, reverse engineering on embedded systems is greatly assisted by tools deliberately introduced by the manufacturer, such as JTAG ports or other debugging means. In Microsoft Windows, low-level debuggers such as SoftICE are popular.
  2. Disassembly using a disassembler, meaning the raw machine language of the program is read and understood in its own terms, only with the aid of machine-language mnemonics. It works on any computer program but can take quite some time, especially for those who are not used to machine code. The Interactive Disassembler is a particularly popular tool.
  3. Decompilation using a decompiler, a process that tries, with varying results, to recreate the source code in some high-level language for a program only available in machine code or bytecode.

Software classification[edit]

Software classification is the process of identifying similarities between different software binaries (such as two different versions of the same binary) used to detect code relations between software samples. The task was traditionally done manually for several reasons (such as patch analysis for vulnerability detection and copyright infringement), but it can now be done somewhat automatically for large numbers of samples.

This method is being used mostly for long and thorough reverse engineering tasks (complete analysis of a complex algorithm or big piece of software). In general, statistical classification is considered to be a hard problem, which is also true for software classification, and so few solutions/tools that handle this task well.

Source code[edit]

A number of UML tools refer to the process of importing and analysing source code to generate UML diagrams as «reverse engineering.» See List of UML tools.

Although UML is one approach in providing «reverse engineering» more recent advances in international standards activities have resulted in the development of the Knowledge Discovery Metamodel (KDM). The standard delivers an ontology for the intermediate (or abstracted) representation of programming language constructs and their interrelationships. An Object Management Group standard (on its way to becoming an ISO standard as well), KDM has started to take hold in industry with the development of tools and analysis environments that can deliver the extraction and analysis of source, binary, and byte code. For source code analysis, KDM’s granular standards’ architecture enables the extraction of software system flows (data, control, and call maps), architectures, and business layer knowledge (rules, terms, and process). The standard enables the use of a common data format (XMI) enabling the correlation of the various layers of system knowledge for either detailed analysis (such as root cause, impact) or derived analysis (such as business process extraction). Although efforts to represent language constructs can be never-ending because of the number of languages, the continuous evolution of software languages, and the development of new languages, the standard does allow for the use of extensions to support the broad language set as well as evolution. KDM is compatible with UML, BPMN, RDF, and other standards enabling migration into other environments and thus leverage system knowledge for efforts such as software system transformation and enterprise business layer analysis.

Protocols[edit]

Protocols are sets of rules that describe message formats and how messages are exchanged: the protocol state machine. Accordingly, the problem of protocol reverse-engineering can be partitioned into two subproblems: message format and state-machine reverse-engineering.

The message formats have traditionally been reverse-engineered by a tedious manual process, which involved analysis of how protocol implementations process messages, but recent research proposed a number of automatic solutions.[22][23][24] Typically, the automatic approaches group observe messages into clusters by using various clustering analyses, or they emulate the protocol implementation tracing the message processing.

There has been less work on reverse-engineering of state-machines of protocols. In general, the protocol state-machines can be learned either through a process of offline learning, which passively observes communication and attempts to build the most general state-machine accepting all observed sequences of messages, and online learning, which allows interactive generation of probing sequences of messages and listening to responses to those probing sequences. In general, offline learning of small state-machines is known to be NP-complete,[25] but online learning can be done in polynomial time.[26] An automatic offline approach has been demonstrated by Comparetti et al.[24] and an online approach by Cho et al.[27]

Other components of typical protocols, like encryption and hash functions, can be reverse-engineered automatically as well. Typically, the automatic approaches trace the execution of protocol implementations and try to detect buffers in memory holding unencrypted packets.[28]

Integrated circuits/smart cards[edit]

Reverse engineering is an invasive and destructive form of analyzing a smart card. The attacker uses chemicals to etch away layer after layer of the smart card and takes pictures with a scanning electron microscope (SEM). That technique can reveal the complete hardware and software part of the smart card. The major problem for the attacker is to bring everything into the right order to find out how everything works. The makers of the card try to hide keys and operations by mixing up memory positions, such as by bus scrambling.[29][30]

In some cases, it is even possible to attach a probe to measure voltages while the smart card is still operational. The makers of the card employ sensors to detect and prevent that attack.[31] That attack is not very common because it requires both a large investment in effort and special equipment that is generally available only to large chip manufacturers. Furthermore, the payoff from this attack is low since other security techniques are often used such as shadow accounts. It is still uncertain whether attacks against chip-and-PIN cards to replicate encryption data and then to crack PINs would provide a cost-effective attack on multifactor authentication.

Full reverse engineering proceeds in several major steps.

The first step after images have been taken with a SEM is stitching the images together, which is necessary because each layer cannot be captured by a single shot. A SEM needs to sweep across the area of the circuit and take several hundred images to cover the entire layer. Image stitching takes as input several hundred pictures and outputs a single properly-overlapped picture of the complete layer.

Next, the stitched layers need to be aligned because the sample, after etching, cannot be put into the exact same position relative to the SEM each time. Therefore, the stitched versions will not overlap in the correct fashion, as on the real circuit. Usually, three corresponding points are selected, and a transformation applied on the basis of that.

To extract the circuit structure, the aligned, stitched images need to be segmented, which highlights the important circuitry and separates it from the uninteresting background and insulating materials.

Finally, the wires can be traced from one layer to the next, and the netlist of the circuit, which contains all of the circuit’s information, can be reconstructed.

Military applications[edit]

Reverse engineering is often used by people to copy other nations’ technologies, devices, or information that have been obtained by regular troops in the fields or by intelligence operations. It was often used during the Second World War and the Cold War. Here are well-known examples from the Second World War and later:

  • Jerry can: British and American forces in WW2 noticed that the Germans had gasoline cans with an excellent design. They reverse-engineered copies of those cans, which cans were popularly known as «Jerry cans.»
  • Panzerschreck: The Germans captured an American bazooka during the Second World War and reverse engineered it to create the larger Panzerschreck.
  • Tupolev Tu-4: In 1944, three American B-29 bombers on missions over Japan were forced to land in the Soviet Union. The Soviets, who did not have a similar strategic bomber, decided to copy the B-29. Within three years, they had developed the Tu-4, a nearly-perfect copy.[32]
  • SCR-584 radar: copied by the Soviet Union after the Second World War, it is known for a few modifications — СЦР-584, Бинокль-Д.
  • V-2 rocket: Technical documents for the V-2 and related technologies were captured by the Western Allies at the end of the war. The Americans focused their reverse engineering efforts via Operation Paperclip, which led to the development of the PGM-11 Redstone rocket.[33] The Soviets used captured German engineers to reproduce technical documents and plans and worked from captured hardware to make their clone of the rocket, the R-1. Thus began the postwar Soviet rocket program, which led to the R-7 and the beginning of the space race.
  • K-13/R-3S missile (NATO reporting name AA-2 Atoll), a Soviet reverse-engineered copy of the AIM-9 Sidewinder, was made possible after a Taiwanese (ROCAF) AIM-9B hit a Chinese PLA MiG-17 without exploding in September 1958.[34] The missile became lodged within the airframe, and the pilot returned to base with what Soviet scientists would describe as a university course in missile development.
  • BGM-71 TOW missile: In May 1975, negotiations between Iran and Hughes Missile Systems on co-production of the TOW and Maverick missiles stalled over disagreements in the pricing structure, the subsequent 1979 revolution ending all plans for such co-production. Iran was later successful in reverse-engineering the missile and now produces its own copy, the Toophan.
  • China has reversed engineered many examples of Western and Russian hardware, from fighter aircraft to missiles and HMMWV cars, such as the MiG-15,17,19,21 (which became the J-2,5,6,7) and the Su-33 (which became the J-15).[35] More recent analyses of China’s military growth have pointed to the inherent limitations of habitual reverse engineering for advanced weapon systems.[36]
  • During the Second World War, Polish and British cryptographers studied captured German «Enigma» message encryption machines for weaknesses. Their operation was then simulated on electromechanical devices, «bombes», which tried all the possible scrambler settings of the «Enigma» machines that helped the breaking of coded messages that had been sent by the Germans.
  • Also during the Second World War, British scientists analyzed and defeated a series of increasingly-sophisticated radio navigation systems used by the Luftwaffe to perform guided bombing missions at night. The British countermeasures to the system were so effective that in some cases, German aircraft were led by signals to land at RAF bases since they believed that they had returned to German territory.

Gene networks[edit]

Reverse engineering concepts have been applied to biology as well, specifically to the task of understanding the structure and function of gene regulatory networks. They regulate almost every aspect of biological behavior and allow cells to carry out physiological processes and responses to perturbations. Understanding the structure and the dynamic behavior of gene networks is therefore one of the paramount challenges of systems biology, with immediate practical repercussions in several applications that are beyond basic research.[37]
There are several methods for reverse engineering gene regulatory networks by using molecular biology and data science methods. They have been generally divided into six classes:[38]

The six classes of gene network inference methods, according to[38]

  • Coexpression methods are based on the notion that if two genes exhibit a similar expression profile, they may be related although no causation can be simply inferred from coexpression.
  • Sequence motif methods analyze gene promoters to find specific transcription factor binding domains. If a transcription factor is predicted to bind a promoter of a specific gene, a regulatory connection can be hypothesized.
  • Chromatin ImmunoPrecipitation (ChIP) methods investigate the genome-wide profile of DNA binding of chosen transcription factors to infer their downstream gene networks.
  • Orthology methods transfer gene network knowledge from one species to another.
  • Literature methods implement text mining and manual research to identify putative or experimentally-proven gene network connections.
  • Transcriptional complexes methods leverage information on protein-protein interactions between transcription factors, thus extending the concept of gene networks to include transcriptional regulatory complexes.

Often, gene network reliability is tested by genetic perturbation experiments followed by dynamic modelling, based on the principle that removing one network node has predictable effects on the functioning of the remaining nodes of the network.[39]
Applications of the reverse engineering of gene networks range from understanding mechanisms of plant physiology[40] to the highlighting of new targets for anticancer therapy.[41]

Overlap with patent law[edit]

Reverse engineering applies primarily to gaining understanding of a process or artifact in which the manner of its construction, use, or internal processes has not been made clear by its creator.

Patented items do not of themselves have to be reverse-engineered to be studied, for the essence of a patent is that inventors provide a detailed public disclosure themselves, and in return receive legal protection of the invention that is involved. However, an item produced under one or more patents could also include other technology that is not patented and not disclosed. Indeed, one common motivation of reverse engineering is to determine whether a competitor’s product contains patent infringement or copyright infringement.

Legality[edit]

United States[edit]

In the United States, even if an artifact or process is protected by trade secrets, reverse-engineering the artifact or process is often lawful if it has been legitimately obtained.[42]

Reverse engineering of computer software often falls under both contract law as a breach of contract as well as any other relevant laws. That is because most end-user license agreements specifically prohibit it, and US courts have ruled that if such terms are present, they override the copyright law that expressly permits it (see Bowers v. Baystate Technologies[43][44]). According to Section 103(f) of the Digital Millennium Copyright Act (17 U.S.C. § 1201 (f)), a person in legal possession of a program may reverse-engineer and circumvent its protection if that is necessary to achieve «interoperability,» a term that broadly covers other devices and programs that can interact with it, make use of it, and to use and transfer data to and from it in useful ways. A limited exemption exists that allows the knowledge thus gained to be shared and used for interoperability purposes.[a]

European Union[edit]

EU Directive 2009/24 on the legal protection of computer programs, which superseded an earlier (1991) directive,[45] governs reverse engineering in the European Union.[46][b]
</ref>

See also[edit]

  • Antikythera mechanism
  • Backward induction
  • Benchmarking
  • Bus analyzer
  • Chonda
  • Clone (computing)
  • Clean room design
  • CMM
  • Code morphing
  • Connectix Virtual Game Station
  • Counterfeiting
  • Cryptanalysis
  • Decompile
  • Deformulation
  • Digital Millennium Copyright Act (DMCA)
  • Disassembler
  • Dongle
  • Forensic engineering
  • Industrial CT scanning
  • Interactive Disassembler
  • Knowledge Discovery Metamodel
  • Laser scanner
  • List of production topics
  • Listeroid Engines
  • Logic analyzer
  • Paycheck
  • Product teardown
  • Repurposing
  • Reverse architecture
  • Round-trip engineering
  • Retrodiction
  • Sega v. Accolade
  • Software archaeology
  • Software cracking
  • Structured light digitizer
  • Value engineering

Notes[edit]

  1. ^ The section states:
    (f) Reverse Engineering.—
    (1) Notwithstanding the provisions of subsection (a)(1)(A), a person who has lawfully obtained the right to use a copy of a computer program may circumvent a technological measure that effectively controls access to a particular portion of that program for the sole purpose of identifying and analyzing those elements of the program that are necessary to achieve interoperability of an independently created computer program with other programs, and that have not previously been readily available to the person engaging in the circumvention, to the extent any such acts of identification and analysis do not constitute infringement under this title.
    (2) Notwithstanding the provisions of subsections (a)(2) and (b), a person may develop and employ technological means to circumvent a technological measure, or to circumvent protection afforded by a technological measure, in order to enable the identification and analysis under paragraph (1), or for the purpose of enabling interoperability of an independently created computer program with other programs, if such means are necessary to achieve such interoperability, to the extent that doing so does not constitute infringement under this title.
    (3) The information acquired through the acts permitted under paragraph (1), and the means permitted under paragraph (2), may be made available to others if the person referred to in paragraph (1) or (2), as the case may be, provides such information or means solely for the purpose of enabling interoperability of an independently created computer program with other programs, and to the extent that doing so does not constitute infringement under this title or violate applicable law other than this section.
    (4) For purposes of this subsection, the term 「interoperability」 means the ability of computer programs to exchange information, and of such programs mutually to use the information which has been exchanged.
  2. ^ The directive states:

    The unauthorised reproduction, translation, adaptation or transformation of the form of the code in which a copy of a computer program has been made available constitutes an infringement of the exclusive rights of the author. Nevertheless, circumstances may exist when such a reproduction of the code and translation of its form are indispensable to obtain the necessary information to achieve the interoperability of an independently created program with other programs. It has therefore to be considered that, in these limited circumstances only, performance of the acts of reproduction and translation by or on behalf of a person having a right to use a copy of the program is legitimate and compatible with fair practice and must therefore be deemed not to require the authorisation of the rightholder. An objective of this exception is to make it possible to connect all components of a computer system, including those of different manufacturers, so that they can work together. Such an exception to the author’s exclusive rights may not be used in a way which prejudices the legitimate interests of the rightholder or which conflicts with a normal exploitation of the program.

References[edit]

  1. ^ a b «What is Reverse-engineering? How Does It Work». SearchSoftwareQuality. Retrieved 2022-07-27.
  2. ^ «Reverse Engineering». ethics.csc.ncsu.edu. Retrieved 2022-07-27.
  3. ^ Thayer, Ken. «How Does Reverse Engineering Work?». globalspec. IEEE Global Spec. Retrieved 26 February 2018.
  4. ^ Villaverde, Alejandro F.; Banga, Julio R. (6 February 2014). «Reverse engineering and identification in systems biology: strategies, perspectives and challenges». Journal of the Royal Society Interface. 11 (91): 20130505. doi:10.1098/rsif.2013.0505. PMC 3869153. PMID 24307566.
  5. ^ a b c Chikofsky, E.J. & Cross, J.H., II (1990). «Reverse Engineering and Design Recovery: A Taxonomy». IEEE Software. 7 (1): 13–17. doi:10.1109/52.43044. S2CID 16266661.
  6. ^ a b A Survey of Reverse Engineering and Program Comprehension. Michael L. Nelson, April 19, 1996, ODU CS 551 – Software Engineering Survey.arXiv:cs/0503068v1
  7. ^ Vinesh Raja; Kiran J. Fernandes (2007). Reverse Engineering: An Industrial Perspective. Springer Science & Business Media. p. 3. ISBN 978-1-84628-856-2.
  8. ^ Jonathan Band; Masanobu Katoh (2011). Interfaces on Trial 2.0. MIT Press. p. 136. ISBN 978-0-262-29446-1.
  9. ^ a b c Chikofsky, E. J.; Cross, J. H. (January 1990). «Reverse engineering and design recovery: A taxonomy» (PDF). IEEE Software. 7: 13–17. doi:10.1109/52.43044. S2CID 16266661. Archived from the original (PDF) on 2018-04-17. Retrieved 2012-07-02.
  10. ^ a b c d e f g h Eilam, Eldad (2005). Reversing: secrets of reverse engineering. John Wiley & Sons. ISBN 978-0-7645-7481-8.
  11. ^ Internet Engineering Task Force RFC 2828 Internet Security Glossary
  12. ^ Karwowski, Waldemar; Trzcielinski, Stefan; Mrugalsk, Beata; DiNicolantonio, Massimo; Rossi, Emilio (2018). Advances in Manufacturing, Production Management and Process Control. pp. 287–288.
  13. ^ Varady, T; Martin, R; Cox, J (1997). «Reverse engineering of geometric models–an introduction». Computer-Aided Design. 29 (4): 255–268. doi:10.1016/S0010-4485(96)00054-1.
  14. ^ «Reverse Engineering».
  15. ^ Warden, R. (1992). Software Reuse and Reverse Engineering in Practice. London, England: Chapman & Hall. pp. 283–305.
  16. ^ «Working Conference on Reverse Engineering (WCRE)». uni-trier.de. Computer Science bibliography. Archived from the original on 14 March 2017. Retrieved 22 February 2018.
  17. ^ Shahbaz, Muzammil (2012). Reverse Engineering and Testing of Black-Box Software Components: by Grammatical Inference techniques. LAP LAMBERT Academic Publishing. ISBN 978-3659140730.
  18. ^ Chuvakin, Anton; Cyrus Peikari (January 2004). Security Warrior (1st ed.). O’Reilly. Archived from the original on 2006-05-22. Retrieved 2006-05-25.
  19. ^ Samuelson, Pamela & Scotchmer, Suzanne (2002). «The Law and Economics of Reverse Engineering». Yale Law Journal. 111 (7): 1575–1663. doi:10.2307/797533. JSTOR 797533. Archived from the original on 2010-07-15. Retrieved 2011-10-31.
  20. ^ «Samba: An Introduction». 2001-11-27. Retrieved 2009-05-07.
  21. ^ Lee, Newton (2013). Counterterrorism and Cybersecurity: Total Information Awareness (2nd ed.). Springer Science+Business Media. p. 110. ISBN 978-1461472049.
  22. ^ W. Cui, J. Kannan, and H. J. Wang. Discoverer: Automatic protocol reverse engineering from network traces. In Proceedings of 16th USENIX Security Symposium on USENIX Security Symposium, pp. 1–14.
  23. ^ W. Cui, M. Peinado, K. Chen, H. J. Wang, and L. Irún-Briz. Tupni: Automatic reverse engineering of input formats. In Proceedings of the 15th ACM Conference on Computer and Communications Security, pp. 391–402. ACM, Oct 2008.
  24. ^ a b P. M. Comparetti, G. Wondracek, C. Kruegel, and E. Kirda. Prospex: Protocol specification extraction. In Proceedings of the 2009 30th IEEE Symposium on Security and Privacy, pp. 110–125, Washington, 2009. IEEE Computer Society.
  25. ^ Gold, E (1978). «Complexity of automaton identification from given data». Information and Control. 37 (3): 302–320. doi:10.1016/S0019-9958(78)90562-4.
  26. ^ D. Angluin (1987). «Learning regular sets from queries and counterexamples». Information and Computation. 75 (2): 87–106. doi:10.1016/0890-5401(87)90052-6.
  27. ^ C.Y. Cho, D. Babic, R. Shin, and D. Song. Inference and Analysis of Formal Models of Botnet Command and Control Protocols, 2010 ACM Conference on Computer and Communications Security.
  28. ^ Polyglot: automatic extraction of protocol message format using dynamic binary analysis. J. Caballero, H. Yin, Z. Liang, and D. Song. Proceedings of the 14th ACM conference on Computer and communications security, pp. 317–329.
  29. ^ Wolfgang Rankl, Wolfgang Effing, Smart Card Handbook (2004)
  30. ^ T. Welz: Smart cards as methods for payment (2008), Seminar ITS-Security Ruhr-Universität Bochum
  31. ^ David C. Musker: Protecting & Exploiting Intellectual Property in Electronics Archived 2011-07-09 at the Wayback Machine, IBC Conferences, 10 June 1998
  32. ^ Yeam Gordon and Vladimir Rigmant, Tupolev Tu-4: Soviet Superfortress (Hinckley, U.K.: Midland, 2002).
  33. ^ «Redstone rocket». centennialofflight.net. Retrieved 2010-04-27.
  34. ^ «The Chinese Air Force: Evolving Concepts, Roles, and Capabilities», Center for the Study of Chinese Military Affairs (U.S), by National Defense University Press, p. 277
  35. ^ Chandrashekar, S., R. Nagappa, L. Sundaresan, and N. Ramani. 2011. Technology & Innovation in China: A Case Study of Single Crystal Superalloy Development for Aircraft Turbine Blades, R4–11. ISSSP National Institute of Advanced Studies, Bangalore. http://isssp.in/wp-content/uploads/2013/01/Technology-and-Innovation-in-China-A-case-Study-of-Single-Crystal4.pdf; and Dillon Zhou, “China J-15 Fighter Jet: Chinese Officials Defend New Fighter As Chinese Original, but Questions Remain,” Mic, December 16, 2012, https://mic.com/articles/20270/china-j-15-fighter-jet-chinese-officials-defend-new-fighter-[permanent dead link] as-chinese-original-but-questions-remain
  36. ^ Andrea Gilli and Mauro Gilli, «Why China Has Not Caught Up Yet: Military-Technological Superiority and the Limits of Imitation, Reverse Engineering, and Cyber Espionage, International Security 43:3 (2019 141-189, https://doi.org/10.1162/isec_a_00337.
  37. ^ Giorgi, Federico M. (2020). «Gene network reverse engineering: The Next Generation». Biochimica et Biophysica Acta (BBA) — Gene Regulatory Mechanisms. 1863 (6): 194523. doi:10.1016/j.bbagrm.2020.194523. hdl:11585/753853. ISSN 1874-9399. PMID 32145356. S2CID 212629142.
  38. ^ a b Mercatelli, Daniele; Scalambra, Laura; Triboli, Luca; Ray, Forest; Giorgi, Federico M. (2020). «Gene regulatory network inference resources: A practical overview». Biochimica et Biophysica Acta (BBA) — Gene Regulatory Mechanisms. 1863 (6): 194430. doi:10.1016/j.bbagrm.2019.194430. ISSN 1874-9399. PMID 31678629. S2CID 207895066.
  39. ^ Tegner, J.; Yeung, M. K. S.; Hasty, J.; Collins, J. J. (2003). «Reverse engineering gene networks: Integrating genetic perturbations with dynamical modeling». Proceedings of the National Academy of Sciences. 100 (10): 5944–5949. Bibcode:2003PNAS..100.5944T. doi:10.1073/pnas.0933416100. ISSN 0027-8424. PMC 156306. PMID 12730377.
  40. ^ Friedel, Swetlana; Usadel, Björn; von Wirén, Nicolaus; Sreenivasulu, Nese (2012). «Reverse Engineering: A Key Component of Systems Biology to Unravel Global Abiotic Stress Cross-Talk». Frontiers in Plant Science. 3: 294. doi:10.3389/fpls.2012.00294. ISSN 1664-462X. PMC 3533172. PMID 23293646.
  41. ^ Lefebvre, Celine; Rieckhof, Gabrielle; Califano, Andrea (2012). «Reverse-engineering human regulatory networks». Wiley Interdisciplinary Reviews: Systems Biology and Medicine. 4 (4): 311–325. doi:10.1002/wsbm.1159. ISSN 1939-5094. PMC 4128340. PMID 22246697.
  42. ^ «Trade Secrets 101», Feature Article, March 2011. ASME. Retrieved on 2013-10-31.
  43. ^ Baystate v. Bowers Discussion. Utsystem.edu. Retrieved on 2011-05-29.
  44. ^ Gross, Grant. (2003-06-26) Contract case could hurt reverse engineering | Developer World. InfoWorld. Retrieved on 2011-05-29.
  45. ^ Council Directive 91/250/EEC of 14 May 1991 on the legal protection of computer programs. Eur-lex.europa.eu. Retrieved on 2011-05-29.
  46. ^ DIRECTIVE 2009/24/EC OF THE EUROPEAN PARLIAMENT AND OF THE COUNCIL of 23 April 2009 on the legal protection of computer programs

Sources[edit]

  • Eilam, Eldad (2005). Reversing: Secrets of Reverse Engineering. Wiley Publishing. p. 595. ISBN 978-0-7645-7481-8.
  • Elvidge, Julia, «Using Reverse Engineering to Discover Patent Infringement,» Chipworks, Sept. 2010. Online: http://www.photonics.com/Article.aspx?AID=44063
  • Cipresso, Teodoro (2009). «Software Reverse Engineering Education». SJSU Master’s Thesis. Retrieved 2009-08-22.
  • Hausi A. Müller and Holger M. Kienle, «A Small Primer on Software Reverse Engineering,» Technical Report, University of Victoria, 17 pages, March 2009. Online: http://holgerkienle.wikispaces.com/file/view/MK-UVic-09.pdf
  • Heines, Henry, «Determining Infringement by X-Ray Diffraction,» Chemical Engineering Process, Jan. 1999 (example of reverse engineering used to detect IP infringement)
  • Huang, Andrew (2003). Hacking the Xbox: An Introduction to Reverse Engineering. No Starch Press. ISBN 978-1593270292.
  • James, Dick (January 19, 2006). «Reverse Engineering Delivers Product Knowledge; Aids Technology Spread». Electronic Design. Penton Media, Inc. Retrieved 2009-02-03.
  • Messler, Robert (2013). Reverse Engineering: Mechanisms, Structures, Systems & Materials. McGraw Hill. ISBN 978-0071825160. (introduction to hardware teardowns, including methodology, goals)
  • Raja, Vinesh; Fernandes, Kiran J. (2008). Reverse Engineering – An Industrial Perspective. Springer. p. 242. ISBN 978-1-84628-855-5.
  • Reverse Engineering for Beginners
  • Samuelson, Pamela and Scotchmer, Suzanne, «The Law and Economics of Reverse Engineering,» 111 Yale L.J. 1575 (2002). Online: http://people.ischool.berkeley.edu/~pam/papers/l&e%20reveng3.pdf
  • Schulman, Andrew; Brown, Ralf D.; Maxey, David; Michels, Raymond J.; Kyle, Jim (1994) [November 1993]. Undocumented DOS: A programmer’s guide to reserved MS-DOS functions and data structures — expanded to include MS-DOS 6, Novell DOS and Windows 3.1 (2 ed.). Reading, Massachusetts: Addison Wesley. pp. 229–241. ISBN 0-201-63287-X. (xviii+856+vi pages, 3.5″-floppy) Errata: [1][2] (NB. On general methodology of reverse engineering, applied to mass-market software: a program for exploring DOS, disassembling DOS.)
  • Schulman, Andrew; et al. (1992). Undocumented Windows: A Programmer’s Guide to Reserved Microsoft Windows API Functions. Addison Wesley. ISBN 978-0-201-60834-2. (pp. 59–188 on general methodology of reverse engineering, applied to mass-market software: examining Windows executables, disassembling Windows, tools for exploring Windows)
  • Schulman, Andrew, «Hiding in Plain Sight: Using Reverse Engineering to Uncover Software Patent Infringement,» Intellectual Property Today, Nov. 2010. Online: http://www.iptoday.com/issues/2010/11/hiding-in-plain-sight-using-reverse-engineering-to-uncover-software-patent-infringement.asp
  • Schulman, Andrew, «Open to Inspection: Using Reverse Engineering to Uncover Software Prior Art,» New Matter (Calif. State Bar IP Section), Summer 2011 (Part 1); Fall 2011 (Part 2). Online: http://www.SoftwareLitigationConsulting.com
  • Thumm, Mike (2007). «Talking Tactics» (PDF). IEEE 2007 Custom Integrated Circuits Conference (CICC). IEEE, Inc. Retrieved 2009-02-03.

I wanna dig inside to find a little bit of me

Slipknot

Reverse Engineering (ревёрсинг, обратная разработка) — процесс пизженья восстановления исходников из конечного продукта инженерной и/или научной деятельности, интуитивно конструируя внутреннюю механику по принципу «а какие процессы должны вызвать такое вот внешнее поведение этого продукта?». Ориентируясь на нюх, так сказать. Иногда приводит к написанию собственного сорца али моделированию/разводке/пайке железячного аналога. Много их — ибо ваистену…

В общих чертах[править]

Брайан Адамс заглядывает внутрь.

Возможно, все мы в детстве сломали немало игрушек пытаясь понять «как оно там устроено». С возрастом это проходит. Но не у всех.

Учёные пытаются дизассемблировать Вселенную, чтобы восстановить исходники Б-га, который явно наложил несколько пакеров и обфускаторов. Военные первым делом подбирают оружие на поле боя — чтобы посмотреть, как устроена эта штурмовая винтовка Stg-44 и можно ли из неё сделать Калаш, а уже потом закапывают трупы. Китайские дизайнеры успешно реверсируют дольче-габбано, чтобы произвести его больше, дешевле и хреновее. Ну а некоторые реверсируют программы, чтобы исправить в них некоторые ошибки (одна из самых распространённых — жадность разработчика) или просто посмотреть, как она устроена, что умеет, и сделать свою, с маджонгом и гейшами. Они-то и являются илитой IT.

Алсо, чуть менее, чем все советские микросхемы представляли собой аналоги забугорных, скопированные с готовых продуктов. В связи с этим в этой стране даже создан закон о правовой охране топологий интегральных микросхем, чтоб у нас в свою очередь не тырили.

Software Реверсинг[править]

Реверсинг ПО — восстановление принципов/идей/алгоритмов работы программы для исследования и/или создания аналогичного ПО. Часто применяется для:

  • Анализа вирусов/троянов/червей и прочего дерьма с целью создания средств защиты.
  • Поиска дырок в закрытом софте с целью создания вирусов/троянов/червей/сплойтов и прочего дерьма.
  • Создания описаний для форматов данных/протоколов, используемых в программах и прочем дерьме. Пример с преподской тестирующей программой относится сюда.
  • Анализа работы закрытых драйверов и прочего дерьма для создания открытых линупсовых.
  • Изготовление пиратских серверов серверных игр вроде WoW и допилка их рубанком до сходства с официальным, ясное дело, дерьмом.

Не следует путать взлом ПО с его реверсингом: для взлома достаточно разобрать принцип работы лицензионной проверки, а реверсинг — это полный разбор программы по кирпичикам и раскладывание своего мозга по уровню кошерности.

Для успешного кодопиздинга требуется знать ассемблер, иметь общее представление о криптографии, знать мунспик и теорию вероятностей — не быдлокодер ли твой предшественник? Ну и матан — например, теорию графов для анализа ветвлений. Но можно и не знать, главное — уметь быстро найти, что почитать, и резво разобраться.

Hardware Реверсинг[править]

Реверс инжиниринг дивайса

Реверсинг железа — всяких блоков управления стиральными машинами, субару импрезами, контрольно-кассовыми машинами. Обычно применяется для:

  • Скручивания одометров на прульном дерьме, патчей блоков управления подушками безопасности (чтобы быдло думало, что его 15-летнее БМВ ещё не побывало в аварии).
  • Патчей для тепло-, водо-, электросчётчиков, контрольно-кассовых машин и прочего дерьма.
  • Патчей блоков управления моторами с целью добытия большего количества дерьма лошадиных сил из двигателя и на порядок раннего экстерминатуса мотора. Алсо для снятия ограничителя скорости.
  • Снятие каких-либо ограничений, заложенных производителем в девайс (как в модемах US robotics и тому подобном дерьме).
  • Восстановление документации, если оная утеряна либо уничтожена из-за древности, но очень надо получить ещё сотню таких же устройств.
  • Поддержка жизненного цикла дорогих проприетарных девайсов, купленных планктоном, сразу же распилившим средства на их техподдержку на что-нибудь более уютненькое. Тру «форд фокус», например.

Любой разработчик и производитель имеет свою лабораторию анализа отказов для настоящего чип-реверсинга. Вот, например, фотоотчёт о лаборатории Atmel.

В той стране от безысходности вообще было принято решение об отказе от разработки собственных чипов. Копипиздинг топологии ИМС был поставлен на широкую ногу.

Инструменты[править]

Статический анализ скомпилированных программ[править]

В данном разделе представлены инструменты для «декомпиляции», в смысле превращения машинного кода в понимание, что же он такое делает. При этом сюда же включены и отладчики, потому что главная функция отладчика в контексте RE — это в первую очередь оптимизация навигации по коду.

Теперь о классификации инструментов. Есть 2 сорта инструментов — универсальные и узкоспециализированные. Узкоспециализированные оптимизированны для конкретной архитектуры. Они имеют меньшее потребление памяти и работают шустрее. Универсальные оптимизированны для code reuse. Они используют промежуточное представление и толстый middleware, в них может быть легче (если знаком с middleware) или тяжелее добавлять новые фичи, но когда это сделано, пользу получают все поддерживаемые архитектуры.

Также можно классифицировать на 2 класса по возможности вклиниться между стадиями.

1. Конвейер. Парсер формата («загрузчик») парсит заголовки и извлекает метаинформацию, метаинформация используется для правильного парсинга машинного кода в представление в памяти, специфичное для архитектуры («дизассемблер»), «лифтер» преобразует это представление в нейтральное промежуточное представление, которое оптимизируется, после преобразуется «декомпилятором» в нужный язык программирования. Конвейер можно прервать между стадиями и поковыряться в промежуточных результатах. Обычно универсальные.

2. Монолит. Тут всё вышеперечисленное слито вместе, а нейтральное представление упразднено. Не между всеми стадиями можно вклиниться. Монолиты, обычно классифицируют по последней стадии. Обычно узкоспециализированные.

Инструменты можно ещё классифицировать как интерактивные и пассивные.

Интерактивные имеют пользовательский интерфейс, позволяющий человеку управлять его работой, подключая свою естественную нейронную сеть в качестве модуля. Пассивные просто получают на вход одно и выдают другое.

Полные конвейеры / комбайны[править]

IDA[править]

Как следует из названия, интерактивный. Основной декомпилятор и дизассемблер на сегодняшний день, скомбинированный с отладчиком. Обладает множеством функций типа поддержки скриптов, графического режима или встроенных плагинов вплоть до эмулятора x86. Не тупой интерфейс — множество интуитивно понятных «горячих» клавиш и т. п. Проекту уже лет 15, и он единственный из дизассемблеров живёт активной жизнью и поныне: у других в новых версиях фичи почти не родятся. До сих пор таскает с собой DOS-GUI версию для олдфагов. Также известен нефиговой ценовой и KYC политикой.

Пишет его татарский расовый мудак по имени Ильфак Гильфанов. Детали истории создания дизассемблера покрыты мраком, но известно, что Ильфаку, как и Биллу Гейтсу с DOS, добрые люди помогли написать первые версии. И задумывался он как инструмент для восстановления прошивок HDD. Дальше, непонятно как и почему, люди разошлись, и остался он один. Потом Ильфак всплывает с версией 3.x уже от лица фирмы Datarescue, которая купила проект. Начиная с версии 4.0, у него появляется GUI, написанный на BCB! С этого времени продукт начинает приобретать массовую известность в узких кругах по двум причинам:

  • MUST HAVE
  • «Ильфак — пидорас»

Остановимся на втором пункте подробнее.

Ильфак, будучи на данном рынке монополистом, давно забил на пользователей хуй. Потому что берут и так. Любой юзер IDA, которому приходилось иметь дело с поддержкой, получал кучу отрицательных эмоций: получив продукт с кучей багов, вы предоставлены себе в их исправлении. Ошибки исправлять никто не спешит — можно легко прождать полгода, даже если баг вопиющий. Продукт практически не тестировался перед релизами и не тестится до сих пор. Юзеры IDA вынуждены хранить несколько версий, потому что в одной хорошо работает одна фича, в другой — другая, в третьей — третья.

А среди «неофициальных» юзеров Ильфак нелюбим за то, что без спроса берёт идеи. За счёт того, что IDA поставляется с SDK, юзеры могут делать свои плагины к IDA, и таки делают немало. Плагины пишутся как для того, чтобы исправить баги оригинальной функциональности, так и ради добавления своих фич для решения конкретных задач. Уровень альтруизма среди «неофициальных» юзеров высок, и исходники плагинов выкладываются на всеобщее обозрение. Так вот, примерно через полгода после появления полезных исходников это становится фичей IDA. У Ильфака на этот счёт железное алиби: «То, что тут придумали — это не новая идея, это меня пользователи попросили ещё год назад».

Вначале народная ненависть выливалась в троллинг на форуме официального русского сайта. Но потом всё быстро утихло, ибо Ильфак анально отгородил форум официальных юзеров, а с неофициальными общаться перестал. Посему примерно раз в год то китайцы, то албанцы, то русские (был интересный случай, когда народ скидывался на руборде, чтобы купить одну копию и поделиться), то немцы тырят с тренингов, кардят, хачат сервера с IDA и коммуниздят очередную версию. Чем каждый раз нереально доставляют целевой аудитории IDA. А официальные юзеры потом смотрят в закрытые форумы поддержки и скидывают цитаты баттхёрта Ильфака в публику, повышая градус веселья.

Потом Ильфак свалил с Datarescue и стал делать IDA от лица своей конторы Hex-Rays. Ходят слухи, что он нанял наконец программеров с прямыми руками, которые наконец начали чистить его говнокод. Поэтому версия 5.5 была воспринята с одобрением, и некоторые неофициальные пользователи даже начали помышлять о приобретении. Но эйфория продлилась недолго, баги снова были найдены, и всё вернулось на круги своя.

Ознакомиться с историей спионеривания можно тут. В июле 2011 года у антивирусной компании была упёрта полная версия декомпилятора версии 6.1. TEH DRAMA!

NSA Ghidra[править]

Универсальный интерактивный фреймворк от АНБ США, написанный на Java и использует Pcode для парсинга семантики инструкций, который скармливается декомпилятору и анализатору потока управления (поддерживаются типы перехода call, branch, return, terminated return, aka exit (для крашей, main и т.д.)), а также Sleigh для дизасма. Содержит в себе гораздо более качественный декомпилятор для цпушных бинарных языков (вроде x86, PPC, ARM, MIPS и прочих с указателями), но фейлится для управляемого байткода (JVM, Dalvik и прочее ООП), т.к. не пережёвывает синтаксический сахар, исключения и прочее. Содержит эмулятор, который при должном использовании становится убийцей отладчиков, поскольку те легко детектируются, а в эмулятор можно всунуть что угодно без патчинга, вплоть до перезаписи функций проверок наличия отладки и т.п. Плюс можно эмулировать для кросс-тестирования декомпиленного кода и пкода, т.к. декомпилятор может ВНЕЗАПНО допускать ошибки, приводящие к неопределённому поведению, но это так, на случай, если кому-то нужно получить функционально эквивалентный проект на C (нет, никакого ЦПП, только в C или, если загрузчик для языка так настроен (пока что только JVM, Dalvik), в Java, ибо такой сахар, как шаблоны, почти всё ООП, начиная с классов и заканчивая RAII, просто не выживает компиляцию).

Retargetable Decompiler, aka retdec[править]

Универсальный декомпилятор-конвейер от Avast. Пассивный, что означает, что потвикать результаты декомпиляции модулем «естественный интеллект общего назначения» ты не сможешь. Вернее сможешь, закинув код в Студию/Creator, но декомпилятор после этого тебе помогать откажется. Тормознутый и ужасно жрёт оперативу на мизерных бинарях на несколько мегабайт, после чего падает по OOM. Частично обхозится отключением части проходов. Очень не любит виртуальные машины — на них обрезание проходов скорее всего не поможет. Как и большинство декомпиляторов, использует под капотом LLVM. Промежуточные этапы дампятся в файлы, которые потом можно скормить другим инструментам, использующим LLVM, или наоборот, выхлоп других инструментов скормить retdec.

GUI[править]

Cutter[править]

Интерактивный GUI к другим инструментам, в основном для Radare2, но туда ещё подключили retdec и hex-rays как плагины.

Дизассемблеры[править]

Дизассемблер — это утилита, преобразующая бинарный код в ассемблерный листинг. Обычно монолиты. В простейших случаях этого вполне достаточно, и остаётся немного покурить и найти то, что нужно. В худших — это каша, и без скриптов и/или отладчика не обойтись.

Существует 3 вида дизассемблеров.

1. Дизассемблирует всё подряд между двумя адресами. Абсолютно бесполезны для реверсинга.
2. Дизассемблирует инструкции, переходя по переходам. При отсутствии контрмер, которые сильно зависят от платформы, умеют отличать код от данных и брать верные смещения. Полезны для реверсера.
3. Brute-force disassembly. То же самое, что и 2, но не ставятся в тупик контрмерами. Имеют смысл только для некоторых платформ.

Hiew (Hacker’s viewer). Небольшая утилита, для нормальных людей бесполезная, юзают лишь надрочившиеся спецы, иногда — продвинутые пользователи (как шестнадцатеричный редактор). Давно существует куча GUI-шных тулзов для тех же целей, но по славной традиции тулзу продолжают использовать…

Sourcer от компании V Communications. Стародавний мощный дизассемблер времен DOS и разных версий Windows. Позволял из .COM или .EXE файлов получать непосредственно .ASM файл, причём для различных компиляторов ассемблера, таких как TASM или MASM. Если было задано достаточное количество проходов при дизасемблировании, то с высокой степенью вероятности можно было при компилировании только что созданного .ASM файла получить исходную исполнимую программу байт-в-байт. Доставлял хорошими комментариями в листинге, скоростью работы, поддержкой разных типов процессора и, конечно, олдскульным сценовским интерфейсом. Сейчас не актуален, хотя некоторые анонимусы продолжают держать его в своём инструментарии, например, для дизассемблирования MBR жёсткого диска, Boot-сектора, специальных утилит, загружаемых с дискеты без какой-либо ОС (например утилиты перепрошивки BIOS или утилиты от производителей HDD), и прочего. То есть для низкосистемных нужд. Последней явилась на свет версия v8.01 от 2001 года. Sourcer — помним, любим, скорбим!

Отладчики[править]

Отладчик — программа для контролируемого исполнения программы или в общем случае любого произвольного куска кода, вплоть до инжектированной в другой процесс DLL. Продвинутый отладчик умеет использовать аппаратные средства отладки, ну и, конечно, дизассемблировать.

Матрица поимела тебя. Анализ кода в IDA.

IDA в линуксе или линукс в IDA?

x64dbg[править]

Основной отладчик для Windows на данный момент. Скриптуется, плагинится, но имеет отвратительно управление, к которому надо привыкать.

SoftIce[править]

Прошлый desktop-тред в бамплимите, начинаем новый…

Дебаггер, работающий на нулевом уровне, на котором можно всё. Появляется по нажатию CTRL+D, и всё остальное — программы, драйвера и даже некоторые прерывания перестают работать. Переставало идти даже «время», и задебажившийся индивид мог потом реально фалломорфировать, осознав сколько прошло времени в «реальном мире». Заодно обрубалась модемная связь, вызывая лютый багет от забытого брейкпоинта при ночном дозвоне по дайлапу. Можно трассировать что угодно: драйвер HDD, USB-антенны и т. п. А ещё там работает мышь и можно делать скрины.

SoftIce вышел на рынок как отладчик уровня ядра совершенно неожиданно для самих создателей этого ядра — MS. Позиционировался как тулза «для нахождения багов в софте», но последние весьма разнообразны: сюда можно отнести MS Office, требующий ключ активации. Немаловажное преимущество: он умеет считывать при загрузке инфу о библиотеке, в процессе отладки показывая имена, например, Kernel.FindClose+105h.

Нынче похож на свежий навоз: его уже n лет никто не обновляет. И не будет — в связи с выпилом конторы разработчиков: Numega невозбранно была проебана за 30 сребреников мудацкой Compuware. В итоге всё закончилось тотальным выпилом как нумеговских проектов, так и собственно офиса бывшей Нумеги. А остатки Девпартнера отдали какому-то ебучему реселлеру Microfocus, потому что Compuware после тотального экстерминатуса Нумеги забил на все эти ваши девпартнеры-девшмартеры болт.

Radare2[править]

Целый фреймворк для реверс-инжиниринга. Изначально hex-редактор включает в себя дизассемблер, декомпилятор… Лучше сами смотрите. Кроссплатформенный, с несколькими интерфейсами на выбор, а исходный код его открыт. Ня!

Immunity Debugger[править]

Очень популярный отладчик с поддержкой автоматизации на питоне. Но дохлый.

Остальные[править]

WinDbg — как бы быдлокодерам, испытывающим от слова «Майкрософт» жжение в области ануса, ни было обидно, это самый популярный kernel-mode отладчик со времён смерти SoftIce. Да и в user-mode Винбэг обеспечивает лютый вин, кладя болт на эти ваши Debugging API и позволяя, например, заглянуть в native code для процесса, в который уже впилен отладчик для managed code.

Syser — китайский дебагер уровня ядра с GUI. Пришёл на смену SoftIce, загнулся в 2011, проиграв войну новым 64-битным ядрам.

OllyDbg — отладчик третьего уровня, гуишный, симпатяффный, функционала выше крыши, применим для 95 % программ, а пропатчен ручками и для всех 98%. Но из-за того, что r3 среди профессионалов считатся не труъ-тулзой, подходящей скорее для скрипткидисов, чем для разбора чего-то реально сложного, автор положил на него хуй, и теперь отладчик разрабатывают новые умельцы, пафосно назвав OllyDbg 2.0. [Отечественная разработка http://www.ollydbg.de ], хоть и менее известна, чем SoftIce, вполне кошерна и к тому же бесплатна. Релизы выглядят хреново, но парни явно набираются опыта и идут в правильном русле.

Лифтеры[править]

Как уже сказано, переводят («поднимают», «отрывают») бинарники в промежуточное абстрактное представление. Промышленный фактический стандарт промежуточного представления — это биткод LLVM, файлы имеют расширение bc. LLVM — это фреймворк для построения компиляторов, содержащий в себе код для оптимизации, и всеми нами любимый clang построен на нём, как и большая часть компиляторов шейдеров для видеокарт, входящих в состав драйверов.

  • retdec — используйте лучше его для лифтинга.

ещё следует отметить

  • McSema — без IDA Pro бесполезен, так как полагается на него для дизассемблирования
  • llvm-mctoll

Остальные все сдохли.

Декомпиляторы[править]

Машинного кода[править]
Общего назначения[править]
  • См. раздел «комбайны». Остальное — лишь пародии на них.
  • Snowman
  • здесь
  • вот тут.
Специфичные для языков[править]

Некоторые компиляторы для некоторых языков генерят весьма специфический субоптимальный машинный код, который имеет определённую структуру и привязан к некоторым runtime-библиотекам. Глубоко понимая структуру этого кода можно написать декомпилятор, восстанавливающий исходный код на исходном языке относительно близко к оригиналу. При этом декомпиляторы общего назначения захлебнутся это оптимизировать.

К сожалению, свободных тут почти нет, одна дорогущая проприетарь:

  • VBDecompiler
  • VBReformer
LLVM bitcode[править]

Декомпилируют из поднятого лифтером представления.

  • retdec
  • llvm2c — работает кое-как, но на гораздо меньшем количестве бинарников, чем retdec.
Языки с байт-кодом[править]

Современные языки программирования типа Java, C# и прочего .NET’a вовсе и не требуют для своего взлома применения дизассемблеров и отладчиков. Весь исходный код легко можно получить в считанные секунды, а если кодер не применил даже обфускацию, то полученные исходники от авторских будут отличаться разве что отсутствием комментариев в первых.

.Net[править]

.NET Reflector — хороший инструмент для декомпиляции программ на C# и некоторых других языках. Авторы постоянно дорабатывают своё детище, вскорости обещают декомпилировать и другие основные языки. Изначально был бесплатен, но после появления широкой аудитории стал платным, впрочем, Reflector использовали для взлома платной версии.

ILSpy — свободный аналог рефлектора от разработчиков SharpDevelop.

dotPeek — детище небезызвестной JetBrains, к моменту выхода из альфы ставшее вполне себе годным инструментом, способным конкурировать с лидерами отрасли. Декомпилирует обфусцированную лапщичку, перед которой пасует даже знаменитый и всеми любимый .NET Reflector. Ах да, программа поставляется абсолютно бесплатно.

JustDecompile — декомпилятор от конкурентов из Telerik

JVM[править]
  • Krakatau — успешно декомпилирует то, на чём все другие декомпиляторы просто падают с ошибками, а именно программы, написанные не на Java, но тоже скомпилированные в байт-код JVM. Правда декомпилированный код содержит излишнюю информацию, которую приходится чистить руками.
  • CFR — очень неплохой декомпилятор.
  • luyten
  • JD
  • JavaDec, JavaByte, Cavaj, тысячи их… Инструментарий тут гораздо побогаче, чем для .net.
Python[править]

Эталонная реализация питона, cpython, компилирует код в байт-код, и исполняет его. Возможно распространять не исходники, а байт-код.

К счастью есть uncompyle6.

Деобфускаторы[править]

Нередко код бывает обфусцирован. Зачастую помогают деобфускаторы. Для интерпретируемых языков (за исключением perl) обычно не требуются или легко самопишутся.

Для JavaScript — JSBeautifier.

Для шарпа один из лучших — de4dot.

Парсеры «исполняемых» форматов[править]

Бинари для современных ОС содержат не только машинный код, но и информацию о том, как его необходимо правильно загружать в память. В никсах используется ELF, в винде — PE, в MacOS/gayOS — MachO.

Большинство из инструментов — библиотеки. standalone инструменты нужны больше для внешнего осмотра, все декомпиляторы/дизассемблеры/лифтеры либо пользуются чужими либами, либо имеют свою либу внутри себя.

Универсальные[править]
  • LIEF — в большинстве случаев тебе нужен именно он. Либа с широким функционалом. Жаль только, что с нуля делать бинарники не умеет, только редактировать существующие.
PE[править]
  • PE Tree
  • PETools — тулза некоего NeoX.
  • LordPE — (умеет фиксить SizeOfImage в пебе).
ELF[править]
  • libelf — умеер и в парсинг, и в конструирование. LGPL v3
  • pyelftools и статьи (1 2 3 4) от Илая Бендерски

Динамическая инструментация[править]

Инструменты из этой группы позволяют автоматически навесить на чужой код свои обработчики. Полезно, например, для логгирования, некоторые инструменты из той группы сделаны поверх инструментов из этой группы.

  • DynamoRIO
  • frida
  • systemtap — для ядра Linux.

Символьное выполнение[править]

Ты накладываешь условие на желаемое состояние программы, система вычисляет входные данные, необходимые, чтобы его достичь. Разумеется, без каких либо гарантий, задача вообще неразрешима.

  • angr

Патч-анализ и дифферы для control flow graph[править]

Вендор выпустил патч, а что в нём — не сказал. Не порядок.

  • DarunGrim Проприетарь.
  • Polypyus

Логгирование поведения[править]

Иногда нам нужно создать свою программу, взаимодействующую с определённой библиотекой с известным API, интерфейсом ядра ОС, устройством или с сетевым сервисом, обычно с сайтом. Тут незаменимы следующие инструменты:

Логгирование библиотечных вызовов[править]

  • ltrace для никсов
  • drltrace для Windows

Логгирование общения по сети[править]

  • Wireshark
  • mitmproxy
  • Telerik Fiddler («бесплатная» проприетарь, но на шарпе, см. пункт «Декомпиляторы»)

Логгирование USB[править]

  • USBPcap (Windows)
  • usbmon (Linux)

Логгирование API OS[править]

  • strace
  • Microsoft Sysinternals Process Monitor

Реверсинг файловых форматов[править]

  • Kaitai Struct — язык описания. Позволяет быстро и интуитивно понятно прототипировать парсеры, в почти реальном времени визуализировать результат и повторять до полного понимания структуры формата
  • Для сложных случаев:
    • Hobbits — продвинутая визуализация бинарей через цифровую обработку сигнала.
    • Veles — просто красивые картинки, построенные по всяким эвристикам, которые типа помогают видеть структуру в бинари, а на деле не помогают никак. По крайней мере мне не зашло.

Аппаратный реверсинг[править]

  • осциллограф с подключением к компу
  • устройства для работы с интерфейсами и сетями: UART, JTAG, SPI, I2C, CAN, Wi-Fi, Bluetooth, LoRa, ZigBee
  • glitch-kit

SDR[править]

Позволяют слушать и слать произвольные радиосигналы. Необходимы для реверсинга беспроводных протоколов.

  • rtl-sdr — дешёвый USB-донгл
  • nexmon — monitor mode + SDR из Wi-Fi чипов в телефонах и Raspberri Pi
  • hackrf, bladerf, rad1o — платы на основе FPGA

FPGA[править]

Позволяет делать многое из вышеперечисленного. По сути микросхема, определяемая прошивкой. Обычно используется для быстрой обработки сигнала.

Прочее[править]

RSATool — GUI-программа для прокачивания скила по RSA. Автор — эгоист из ТМГ (илита сцены, ни одного нюка). Для факторизации не годна, лучше юзать msieve.

Архив даташитов и документация[править]

Без этих вещей вы никогда не узнаете, что процессор Nippon-Denso NP648976 на самом деле жалкий клон Motorola 6803 с 16К ROM на борту. А когда узнаете, поймёте, что япошки никогда ничего сами не придумывали, а только умело пиздили.

Вещи, затрудняющие анализ[править]

Для борьбы с реверсингом авторы используют всяческие трюки, чтобы их творения не были доступны анализу. Чем выше жадность и хреновее функционал, тем обычно более параноидальна защита, которая в клинических случаях может даже начать мстить (удалять файлы и т. п.), если почувствует, что к её попке приближается некто с отладчиком. Интересно, что глючащая защита может сработать там, где кряком и не пахло, и тогда простому пользователю пиздецъ.

Продвинутые программы редко содержат паранойю, например, WinRar.

Выпуск эксклюзивно под анально огороженную платформу для демонстративного потребления — платформой не пользуются те, кого могла бы заинтересовать крякнутая прога или отреверсенная программа — касание технических деталей и/или использование софта, за который не заплачено, считается ниже достоинства пользователей данной платформы, как если бы генеральный директор компании с доходом миллион в неделю собственноручно занимался мытьём туалета у себя дома вместо того, чтобы нанять профессионала и заплатить ему, или ездил бы на автомобиле, который ремонтируют не в официальной дилерской мастерской. Любители сами поковыряться и нелюбители понтов просто используют другую платформу. Раз никому не нужно — нет смысла и реверсить.

Быдлокодинг. Как это ни удивительно, но быдлопроги зачастую обладают естественной защитой от анализа. Cкажем, проект на Visual Basic, скомпилированный в P-code, читать гораздо труднее, чем продукт полноценного C-программера. Даже после декомпиляции. У профессиональных программистов есть представление, какой примерно должна быть архитектура для решения той или иной задачи. Архитектура строится из известных шаблонов (которые есть даже у тех, кто никогда о них не слышал, great minds think alike). У быдлокодеров понятия обо всём этом нет, поэтому их говнокод делает неожиданные и дикие для профессионала вещи и имеет ненужные зависимости между частями, что портит жизнь как самому быдлокодеру, так и всем остальным, вынужденным в разбираться в его коде. Также сложность представляет индусский стиль программирования — быдлокодер неумело пытается защитить своё творение путём искусственного раздутия кода, хотя тот и без всякой доработки может представлять собой такую НЕХ, что даже имея оригинальные исходники, хрен поймёшь, как оно работает — чтение такого листинга может вызывать рвоту.

Дзен-кодинг — использование хитросплетений паттернов проектирования и вообще кодогенерации шибко «умным» программистом приводит к созданию не менее отвратительного кода, который что в сорцах хуй проссышь, что в асме.

Пакеры сжимают программы, чтобы они занимали меньше места на диске и распаковывались в памяти. Per se защитой не являются, однако в нераспакованном виде анализировать сжатую программу невозможно. Для известных пакеров лучше всего найти анпакер, который вернёт программу в более-менее исходное состояние. Известные — UPX, ASPack, MEW, PECompact, NSPack.

Обфускация — превращение исходного/промежуточного/конечного (нужное подчеркнуть) исполняемого кода в кашу, которую невозможно читать. Из исходной инструкции обфускатор делает пять (а то и сотню, в случае паранойи пермутации), делающих то же, что и одна, плюс ещё 200, которые вообще ничего не делают, и 28 препятствующих эмулированию или отладке. Применяется как в «хороших» программах, чтобы перенести появление кряка, так и в «плохих», типа полиморфных вирусов, стремящихся оттянуть момент своей детекции — каждая следующая копия будет непохожа на предыдущую. Олсо пытается юзаться в илитной малваре типа рустока и прочей, в расчёте на то, что антивирусные вендоры будут сосать хуйцы. Кстати, есть такой сайтик http://www.ioccc.org, где проводится конкурсы на самую запутанную программу для UNIX. Победители конкурса — истинные шедевры кодописательства и кодозапутывания. Настоятельно рекомендуются к ознакомлению.

Антиотладка — приёмы для борьбы с отладкой. Для мелкософтовского виндувса достаточно IsDebuggerPresent(). Например, уныло посмотреть поле BeingDebugged в пебе, или посмотреть значение NtGlobalFlag. Это 2 самых говнометода, илита же предпочитает еблю с rdtsc (многопроцессорные системы сосут хуйцы), ядерные сплойты и парсинг физической памяти. На каждый такой приём существует антиприём, ну и так далее. И обычно это люто, бешено глючит, бсодит, и вообще, нормальные челы не отлаживают всякую хуиту на своих компах, а заставляют давиться этим калом эмуляторы: Virtual Box, VMWare, VirtualPC и т. д.

Краденые куски — часть кода программы выпиливается, а выполнение оригинального куска выносится вовне: в протектор, на удалённый сервер, донгл и прочая. Когда хацкер делает дамп, он получает не всю программу, а лишь её часть. Кошерным примером реализации этого метода являются токены RSA SecurID.

Виртуальные машины — часть кода программы транслируется в байткоды другого (не обязательно реального) процессора, и добавляется транслятор, который эти байткоды хавает и выполняет. Некоторые протекторы, такие как «Темида», превращают один грамм исходного быдлокода в 1-3 десятка кило нового говна.

Протекторы — проги, которые защитят ваше творение, особо не заставляя думать — знай сиди и бросай формочки в дебилдере. Thinstaller, RCrypt, ASProtect, EXECryptor (привет Relayer), WL/Themida… много их. Могут содержать все вышеперечисленные пункты в невозбранном количестве и в самых невероятных сочетаниях, но обычно содержат баги в реализациях PRNG/метаморфов и прочей хуиты. Кстати, большая часть самых известных протов уже отошла в мир иной-не выдержали конкуренции с пиратами!

Обращения к взломщикам внутри исполняемого файла в виде ASCII-строк — и такое встречается часто! Начиная от «злобные дяди хакиры, ни ламайте пожалуйста маю программку, нет денег на пиво»® до всяких «yates stilL Here kinda Ooooh» и целых анекдотов про улитку в серьезных защитах. Действуют на хакеров-ломакеров сильнее, чем все вышеперечисленные приемы, заставляя последних давиться от хохота, тем самым оттягивая дату неминуемого взлома.

Немного о личных качествах самих реверсеров[править]

Вечер. Автобус. Едет. На первом сиденье сидят двое. У них коэф. интеллекта IQ=180:
— Я вчера Гамлета в оригинале читал… Такое эстетическое наслаждение…
На другом сиденье сидят ещё двое. У них IQ=140:
— Я вчера посмотрел «Андалузского пса» и нашёл коррелят с ранними картинами Пикассо…
На другом сиденье сидят двое. У них IQ=100:
— Мы с другом час назад посмотрели «От заката до рассвета». Как там тёлка говорит тёлке, что…
На другом сиденье сидят двое других. У них IQ=80:
— Слышь, брат! Помнишь, какое пойло мы в мерсе пили, когда ноги какой-то б..яди торчали в окне…
А на задней площадке стоят двое с IQ=40:
— Ну вот, вскрываю прогу твоим дебаггером…

Анекдоты — анекдотами, но реверсивщики делают много хорошего. Помимо упомянутого участия в разработке всевозможных антивирусов, именно один из них создал неофициальный кодовый патч (UCP) для Master of Orion образца 2016 г, позволивший модить игруху сверх дозволенного разработчиками. Продукт продолжает расширяться и дорабатываться. Самое забавное, что даже по строгим заокеанским законам собственник не осудил кулибина, но и не заплатил за старания, а вместо этого тупо скомуниздил несколько решений в официальный патч. Вот тебе, бабушка, и авторские права!

Ресурсы[править]

  • WASM.ru — Windows Assembler Site, ориентирован в том числе на «Отладка и дизассемблирование программ» и «Защита от предыдущего пункта». Отличная подборка статей на разные околореверсные тематики, набор исходников и утилит (впрочем, не сильно приватных), а также форум, где можно получить или поделиться знаниями в области ассемблера. В Германии забанен кровавой гэбней TrendMicro. В настоящее время ушел в вечность. Появились псевдоподия основанные на слитых базах форума, короч внимания не достойны.
  • exelab.ru — более узкоспециализированный форум.
  • exetools — некогда был неплохой сайт, где тусило немало ИЛ. Сейчас анально огородились, без инвайтов не попасть, на ftp не зайти.
  • woodmann/fravia — с чего начинается реверсинг, с картинки в твоем букваре… Самый натуральный букварь, на котором выросло поколение реверсеров конца 90-х.
  • OpenRCE, r0 Crew — ещё комьюнити реверсеров, где местами можно найти интересные тулзы, скрипты и плагины.
  • Еще один учебник для начинающих на русском
  • w:International Journal of Proof-of-Concept — на инглише. Познавательный журнал.

См. также[править]

  • Умение разбираться в чужом коде
  • ReactOS
  • Матан

uk.w:Зворотна розробка

Movax1010h.png Глубокий смысл скрыт в этих неестественных языках
Языки программирования Промышленные: 1С • BAT • C# • C • C++ • Java • JavaScript (AJAX) • Pascal • Perl • PHP • Python • Ruby • ABAP • Ассемблер • Васик • Фортран
Эзотерические: BrainFuck • Erlang • Forth • Haskell • LISP (My other car) • Prolog • Tcl • ΤΕΧ • Oracle
Профессии Быдлокодер • Программист • Тестировщик • Хакер • Хеллоуворлдщик
Методы и стили Reverse Engineering • Анти-паттерн • Выстрелить себе в ногу • Грязный хак • Код (индусский) • Костыль • Метод научного тыка • Помолясь • Свистелки и перделки • Очередь • Спортивное программирование
Прочее ++i + ++i • Deadline • %s • 640 килобайт • CMS • Dummy mode • ЕГГОГ • Foobar • God is real, unless explicitly declared as integer • GOTO • Ifconfig • KISS • RegExp • SICP • sql.ru • Xyzzy • Дискета • Инжалид дежице • КОИ-8 • Лог • Ман • Рекурсия • СУБД • Тест Тьюринга • Умение разбираться в чужом коде • Фаза Луны • Фатальный недостаток • Проблема 2000
Made in China logo.jpg Даёшь Тянынмань по всей планете
Люди Брюс Ли • Джеки Чан • Мао Цзэдун • Неизвестный бунтарь • Пол Пот • Узкоглазый • Шри Япутра • Яо Мин
Особенности Китай • Китаизация • Reverse Engineering • Буддизм (Дзен) • Великий Китайский Файерволл • Го • Иероглиф • Коммунизм • Кунг-фу • Мозг обезьяны • Пандемия (Коронавирус) • Сверхдержава • Суп из младенцев • Фэн-шуй • Чай • Социальный рейтинг
Made in China Abibas • Brick Game • Chery • Noname • TikTok • Ашанбайк • Даосизм • Изобразительное исскуство • Китайский айфон • Китайский шрифт •
Пейджер • Пиратские игры девяностых • Силумин • Тамагочи • Фейк
Мемы Арбуэ • Китайские ватты • Китайские пингвины • Китайские чиновники • Kитайский код • Китайский порномультик • Очки надо? • Последнее китайское предупреждение • Чайный гриб • Нефритовый стержень • Тоталитарное искусство • Китайские шрифты • Партия гордится тобой • Миска риса и кошка-жена
Прочее QNet • ХуйТысячи значений • Эльдорадо • Китаизация Италии • Россия как сателлит Китая • Захват России Китаем

Обра́тная разрабо́тка (обратный инжиниринг, реверс-инжиниринг; англ. reverse engineering) — исследование некоторого устройства или программы, а также документации на них с целью понять принцип его работы и, чаще всего, воспроизвести устройство, программу или иной объект с аналогичными функциями, но без копирования как такового.

Применяется обычно в том случае, если создатель оригинального объекта не предоставил информации о структуре и способе создания (производства) объекта. Использование обратной разработки может противоречить закону об авторском праве и патентному законодательству.

В настоящее время под словами «reverse engineering» чаще всего понимается т. н. «clean room reverse engineering», то есть процесс, при котором одна группа разработчиков анализирует машинный код программы (в сленге хакеров для этого процесса используется также выражение «обратный инжиниринг» или «реверсный инжиниринг»), составляет алгоритм данной программы на псевдокоде, либо, если программа является драйвером какого-либо устройства, составляет исчерпывающие спецификации интересующего устройства. После получения спецификаций другая группа разработчиков пишет собственный драйвер на основе полученных спецификаций или алгоритмов. Такой подход позволяет избежать обвинений в нарушении авторских прав на исходную программу, так как по законам, к примеру в США, подпадает под понятие «fair use», то есть добросовестного использования оригинальной программы. Результат обратной разработки редко идентичен оригиналу, что и позволяет избежать ответственности перед законом.

Содержание

  • 1 Сферы применения обратной разработки
    • 1.1 Электроника
    • 1.2 Программное обеспечение
      • 1.2.1 Базы данных
    • 1.3 Промышленность
    • 1.4 Военная промышленность
  • 2 ПО
    • 2.1 Для анализа исходного кода
  • 3 Реинжиниринг бизнес-процессов
  • 4 Примечания
  • 5 См. также
  • 6 Ссылки

Сферы применения обратной разработки

Электроника

Копирование различных электронных блоков без фактической разработки. Известно, что часть советской цифровой электроники копировалась. Например, американская серия интегральных схем 74 и её советский аналог К(Р)155.

Ещё один пример обратной разработки — создание компанией AMD процессора Intel 80386.

Программное обеспечение

Исследование и обратная разработка программ обычно осуществляются с целью дальнейшей модификации, копирования, или, например, написания генераторов ключей, алгоритм работы которых получен на основе анализа алгоритма их проверки. Также исследование программ применяется с целью получения некоторых закрытых сведений о внутреннем устройстве программы — о протоколе сетевого обмена с сервером, аппаратным средством, ключом защиты или о взаимодействии с другой программой. Ещё одна область применения — получение информации о способах экспортирования данных из многочисленных проприетарных форматов файлов[1].

С развитием Интернета популярные операционные системы и программы всё интенсивнее исследуются на предмет обнаружения в них уязвимостей или т. н. дыр. В дальнейшем найденные дыры могут использоваться для получения несанкционированного доступа к удалённому компьютеру или компьютерной сети.

Одним из широко известных примеров обратной разработки является исследование IBM, ставшее серьёзным шагом на пути развития производства IBM-совместимых компьютеров сторонними производителями. Создание сервера GNU/Linux и работающего с серверами на базе ОС Microsoft Windows) также потребовало обратной разработки используемого SMB.

Обратная разработка программного обеспечения производится с помощью следующих методик.

  1. Анализ обмена данными, наиболее распространённый в обратной разработке протоколов обмена данными, который производится с помощью анализатора шины и пакетного сниффера для прослушивания шины компьютера и компьютерной сети соответственно.
  2. Дизассемблирование с помощью дизассемблера, при котором прямой машинный код программы читается и понимается в своём чистом виде, только с помощью мнемоник машинного языка. Этот способ работает на любой компьютерной программе, но требует достаточно много времени, особенно для неспециалиста.
  3. Декомпиляция с помощью декомпилятора — процесс создания исходного кода на некотором языке программирования высокого уровня.

Базы данных

может использоваться при создании реляционной модели базы данных.

Промышленность

Обратная разработка продукта конкурента с целью узнать его устройство, принцип работы и оценить возможности создания аналога.

Военная промышленность

Jerry cans

Самыми известными фактами обратной разработки во время второй мировой войны являлись:

  • Немецкие канистры для бензина — британские и американские войска заметили, что немцы имели очень удобные канистры. Они скопировали эти канистры, и те получили название Jerry cans (от слова «gerrys» — от «Germans»).
  • Туполев Ту-4 — некоторое количество американских бомбардировщиков B-29 при совершении вылетов в Японию были вынуждены садиться в СССР. Советские военные, которые не имели подобных стратегических бомбардировщиков, решили скопировать B-29. Через несколько лет они разработали Ту-4, практически полную копию.

ПО

Для анализа исходного кода

С широким применением SADT) связано возникновение основных идей популярного ныне понятия — BPR (бизнес-процесс реинжиниринг).

Существуют программы, которые предоставляют как возможность восстановления (обратный, reverse) по исходному коду общего системного проекта (классы, связь между ними и т.п.), так и прямой генерации исходного кода на основе созданного проекта (функциональных блоков бизнес-процесса):

  • Rational Rose (фирмы Rational Software)
  • Visual Paradigma
  • StarUML

Реинжиниринг бизнес-процессов

Примечания

  1. Часто применяется, например, в отношении форматов, поддерживаемых Microsoft Office.

См. также

  • Дизассемблер
  • GNU Ferret
  • Язык ассемблера
  • Взлом программного обеспечения

Ссылки

  • AMD: 30 лет гонки за лидером.
  • Методы и технологии реинжиниринга ИС

Wikimedia Foundation.
2010.

Что такое реверс-инжиниринг

Что такое реверс-инжиниринг?

Реверс инжиниринг — это процесс анализа скомпилированного бинарного файла с целью понять, как программа работает. Программисты, как правило, пишут программы на высокоуровневых языках программирования, таких как C++ или Visual Basic. Т.к. компьютер не может напрямую исполнить код такой программы, код, написанный программистом компилируется в код, непосредственно понятный процессору. Этот код называют машинным кодом. Машинный код тяжел для восприятия и понимания, поэтому реверс-инженеру в процессе его анализа часто требуется прилагать значительные умственные усилия. 

В каких случаях реверс-инжиниринг может быть полезен?

Реверс-инжиниринг применятся во многих компьютерных областях, вот только несколько примеров такого применения:

  • Сделать возможным взаимодействие с кодом, написанным не вами;
  • Взлом платной программы, что бы бесплатно получить полную версию;
  • Исследование вирусов и малвари;
  • Нахождение и исправление ошибок в программах;
  • Добавление функционала в существующее приложение. 

В первом случае мы анализируем скомпилированную программу, к исходному коду которой у нас нет доступа, что бы понять, как с ней можно взаимодействовать и как можно использовать ее функции внутри свой программы. 

Второй случай – взлом платных программ – является достаточно распространенным явлением. Его суть заключается в отключение ограничений, выполнение регистрации и другие вещи, которые позволяют использовать коммерческий софт бесплатно. Мы обсудим это более подробно. 

Третий случай – анализ работы вирусов и малвари. Реверс-инженеринг требуется для таких задач, т.к. немного вирусописателей снабжают свои детища исходным кодом или какой-либо документацией :) Это довольно интересное направление, но оно требует большого количества знаний. 

Четвертый случай – исправление ошибок в программах. В любых больших программных продуктах как правило содержатся ошибки и уязвимости и навыки реверс-инжиниринга могут сильно помочь в их поисках и устранении. 

Последний случай из рассмотренных нами – добавление функционала в существующие приложения. Лично я думаю, что это довольно весело. Вам не нравится графика в каком-нибудь дизайнерском приложении? Измените ее. Хотите добавить пункт меню с новым функционалом в ваш любимый текстовой редактор? Добавьте. Хотите подшутить над коллегами и добавить всплывающие окна в Windows-калькулятор? Сделайте это. Мы также подробнее затронем этот вопрос позже.

Какие знания нам необходимы?

Как вы вероятно, догадаетесь, что бы быть эффективным реверс-инженером, требуется солидный багаж знаний. Но начать делать какие-то базовые вещи можно и без него. Для новичков требуется знание основ программирования (что такое оператор, что такое условие, цикл и т.д.). Также очень неплохо было бы быть знакомым с ассемблером и иметь базовое представление об архитектуре компьютера. На первых порах потребуется уделить некоторое время осваиванию инструментов, которые используются для реверс-инжиниринга. Эти инструменты оказывают большую помощь, но в свою очередь требуют знаний того, как их грамотно применять. Что бы прокачать навыки в реверс-инжиниринге как и везде требуется делать много практической работы – разбираться со снятием различных пакеров/протекторов/крипторов, изучать программы, написанные на различных языках программирования, обходить анти-отладочные приемы… список можно долго продолжать. В конце этого туториала я привел некоторые ссылки с полезными материалами. Если вы хотите стать хорошим реверс-инженером  – требуется заниматься самообразованием.

Какие инструменты использовать?

В процессе реверс-инжиниринга используется множество различных инструментов. Многие их них заточены под какую-то конкретную задачу (снятие определенного упаковщика, например). Некоторые более универсальны. Инструменты можно классифицировать следующим образом:

1. Дизассемблеры

Дизассемблеры берут машинный код, представленный в бинарном формате и отображают его в более удобной для восприятия манере. Они также облегчают процесс идентификации функций, переменных и текстовых строк. Это делает код исполняемого файла более читабельный, нежели мы просто смотрели бы на набор единиц и нулей.

Существует довольно много дизассемблеров, и из них можно выбрать удобный именно для вас и ваших задач. Лично для меня самым лучшим выбором является IDA Pro (hex-rays.com). (Примечание переводчика: обратите также внимание на бесплатный, но мощный дизассемблер Ghidra (https://ghidra-sre.org/)).

2. Отладчики

Отладчики это важнейший инструмент для реверс-инженера. В чем-то их функционал пересекается с дизассемблерами: они также представляют бинарный код в более удобном для восприятия формате. Но помимо этого они также позволяют пошагово исполнять этот код, инструкция за инструкцией, и наблюдать за результатами. Это дает хорошее понимание того, как работает программа. Наконец, некоторые отладчики позволяют изменять некоторые инструкции в коде и потом мы можем еще раз запустить программу уже с этими изменениями. В качестве примера отладчиков можно назвать Windbg, Ollydbg, x64dbg. Лично я предпочитаю Ollydbg, если только не надо отлаживать код на уровне ядра операционной системы.

3. HEX-редакторы

Хекс-редакторы позволяют видеть бинарный код как таковой, а также изменять его. Они также предоставляют такую функцию как поиск определенного набора байтов в бинарном коде. Существует несколько неплохих хекс-редаторов и они по-большей части взаимозаменяемы. В данных туториалах мы обычно не будем прибегать к их использованию, но в некоторых ситуациях хекс-редакторы могут сослужить хорошую службу.

4. Редакторы ресурсов.

Каждый бинарный файл, который должен запускаться в операционной системе содержит в самом своем начале содержит информацию для операционной системы о том, как запускать и инициализировать программу. Там содержится такая информация как сколько памяти требуется данной программе, функции из каких DLL программа использует и т.д.

Для реверс-инженера такие бинарные структуры являются очень важными, поскольку позволяют многое понять об исполняемом файле. Также если вдруг возникнет необходимость изменить поведение программы, вам может понадобится модифицировать эти структуры. Большинство исполняемых файлов также содержит секцию ресурсов. В ней находятся графические изображения, окна меню, иконки и текстовые строки. С помощью редакторов ресурсов мы можем просматривать и менять эти вещи.

5. Системные мониторы

В процессе реверсинга какой-либо программы (особенно вредоносной) часто бывает необходимо узнать, какие изменения эта программа вносит в операционную систему. Создает ли она записи в реестре? Создает ли она текстовые файлы? Запускает ли она новый процессы? Ответы на эти вопросы помогают понять системные мониторы. Примерами таких программ являются procmon, regshot и process hacker.

6. Дополнительные инструменты

Существуют также полезные инструменты, которые не попали в приведенные выше категории. Например, различные скрипты, распаковщики, определители упаковщиков и т.д. Также полезно иметь доступ к документации по API-функциям вашей целевой операционной системы, поскольку программы как правило часто используют подобные функции и реверс-инженеру необходимо знать их назначение.

Давайте начнем прямо сейчас!

Несмотря на то, что мы начинаем с минимальными знаниями мы попробуем сделать что-нибудь практическое прямо в первом туториале. Скачайте себе редактор ресурсов XN Resource Editor. Он бесплатен. Как вы, скорее всего догадались, это программа позволяет просматривать, а также модифицировать ресурсы в исполняемых файлах. Можно делать довольно много вещей: менять название пунктов меню, иконки, графические изображения и т.д. Давайте попробуем. 

Для начала запустите XN, нажмите на иконку для открытия файла и выберите файл калькулятора (Windows/System32/calc.exe). Слева вы должны увидеть список: 

Список файлов

Вы видите, что в этом списке присутствует раздел Bitmap (графические изображение, которые содержит программа), Menu (пункты меню), String Table, Icon Group и т.д. Попробуйте покликать по этим разделам. Вы можете поменять что-нибудь, но лучше сохраните измененный вариант калькулятора в другом месте, что бы не затрагивать оригинал! 

До встречи!

Дополнительные материалы

  • С чего начать изучение реверс-инжиниринга;
  • Assembly Language for X86 Processors — Хорошая книга для знакомства с ассемблером под x86;
  • PE Format — Описание структуры исполняемых файлов под Windows;
  • Windows Internals — Книга описывает внутреннее устройство операционной системы Windows;
  • Tuts4you.com — Сайт с большим количеством туториалов по реверс-инжинирингу.

Разобрали тему реверс-инжиниринга в рамках участия в Петербургской технической ярмарке, которая прошла 26 апреля 2022 года. Этапы, особенности, преимущества. Реверс-инжиниринг — инструмент для импортозамещения

Реверс-инжиниринг — понятие, задачи.

Реверс-инжиниринг — он же обратное проектирование, он же — обратный инжиниринг — процесс разработки конструкторской документации (КД) на основе исходных данных, полученных в виде готового образца изделия. То есть КД не разрабатывается с нуля, а восстанавливается по образцу путем снятия с него размеров и изучения других его параметров.

Задача реверс-инжиниринга — получить комплект технической документации в минимально возможные сроки (по сравнению с новой разработкой), по которой можно будет изготавливать изделия на любом производстве.

Реверс-инжиниринг — инструмент для импортозамещения

Этапы обратного инжиниринга

Вкратце, основные этапы данного типа работы:

  • Предоставление образца и информации о нем.
  • Проведение замеров.
  • Определение материалов.
  • Построение 3D-моделей.
  • Разработка чертежей.
  • Изготовление и испытание опытного образца.
  • Корректировка КД, при необходимости.
  • Изготовление партии.

Наглядно эти этапы представлены на изображении.

Реверс-инжиниринг — инструмент для импортозамещения

Покупка готовых деталей VS Реверс деталей

Если сравнивать реверс с закупкой готовых запчастей у иностранных производителей возникает ряд нюансов, которые необходимо взвесить. Рассмотрим ряд из них в контексте «как правило», потому что в отдельных частных случаях условия могут отличаться.

С одной стороны, при покупке готовых изделий, Заказчик тратит меньше времени на организационные вопросы. Оформил заявку на покупку, провел оплату, проконтролировал и принял поставку. При реверсе необходимо будет найти конструкторское бюро, которое разработает чертежи, организовать производство с изготовлением и испытанием опытного образца (об этом расскажем отдельно), разместить заказ на серию изделий, принять.

С другой стороны, у закупки есть ряд существенных минусов, которые стали особенно актуальны на текущий момент в свете распространения санкций от иностранных компаний и не только. К ним относятся:

  • высокая стоимость запчастей;
  • зависимости от курса валют;
  • зависимость от сроков доставки;
  • невозможность в некоторых случаях заказать изделие;
  • зависимость от одного поставщика.

Зависеть от ограничений и сторонних разрешений не хочется никому. Тем более, когда на кону финансовая стабильность предприятия.

Поэтому тренд сегодняшнего дня и один из эффективных инструментов решения этого вопроса — реверс-инжиниринг. За март количество запросов на эту услугу у нас выросло в 2 раза.

Реверс-инжиниринг — инструмент для импортозамещения

Преимущества реверс-инжиниринга

  1. Сокращение затрат — снижение стоимости изготовления изделия, при производстве партиями или сериями, за счет локализации производства, оптимизации логистики и др. факторов.
  2. Многократность воспроизведения — по документации, полученной в ходе реверс-инжиниринга, изделия можно изготавливать неограниченное количество раз на любых производствах в зависимости от вашей потребности.
  3. Надежность поставок независимо от санкционных ограничений, скачков курсов валют, одного поставщика.

Реверс-инжиниринг — инструмент для импортозамещения

Помимо этих моментов, реверс дает не такие очевидные плюсы и возможности:

  1. Возможность доработки (дизайна, технологичности отдельных узлов или деталей в целом, унификации и др.). После разработки КД в рамках реверса у Заказчика на руках остаются модели и чертежи, на основе которых можно выполнить доработку изделия, если это потребуется, а не создавать с нуля.
  2. Возможность стать поставщиком деталей, изделий сторонним предприятиям, которые нуждаются в подобной продукции.
  3. Выбор лучших — возможность изготовления на нескольких производствах с целью выбора поставщика с лучшими условиями и/или с целью диверсификации производственных мощностей.

Реверс-инжиниринг — инструмент для импортозамещения

Поэтому, если Вы столкнулись со сложностями в закупках запчастей попробуйте решить их, использовав технологию реверс-инжиниринга.

Если уже решали вопросы таким способом поделитесь результатами. Это всегда ценно.

Подробнее об этом направлении можно ознакомиться на сайте конструкторского бюро по ссылке.

Что такое обратный инжиниринг?

Revers-engineering (обратный инжиниринг или обратное проектирование) — процесс разработки конструкторской документации (КД) и/или 3D модели изделия на основе готового образца изделия. То есть КД и/или 3D модель не разрабатывают с нуля, а восстанавливается по готовому изделию, измеряя его размеры и изучая другие его параметры.

Основная цель реверс-инжиниринга — получить готовый комплект конструкторской документации (чертежи изделия, спецификации и 3D модели) на готовое изделие в минимально возможные сроки. Именно на конструкторской документации основаны процессы производства, эксплуатации, ремонта и модернизации изделий.

Процесс реверс-инжиниринга

Этапы реверс-инжиниринга

Далее кратко рассмотрим основные этапы реверс-инжиниринга. 

Предоставление исходной информации

В качестве исходных данных исполнителю (тому, кто будет предоставлять услугу обратного инжиниринга для конкретной детали) необходимо обязательно предоставить образец изделия, а также всю дополнительную информацию об изделии. Например:

  • назначение детали
  • условия эксплуатации
  • сопрягаемые детали
  • материал.

Чем больше информации об изделии вы предоставляете, тем проще будет в дальнейшем проведение работ по обратному инжинирингу.

Измерение изделия

Имеется два подхода к измерению детали. 

Ручное измерение при помощи контактных средств измерения (штангенциркуль, микрометр, координатно-измерительная машина, нутромер, профилометр и т.д.), данную методику используют для небольших деталей с простой геометрией, результат – 2D эскизы.

Измерение высоты детали штангенрейсмасом

Измерение диаметра отверстия рычажным нутромером

Измерение длины корпуса микрометром

Измерение ширины кармана штангенциркулем

Измерение отклонения от круглости в призме 

(На фото отображен процесс измерения деталей контактным способом в нашей лаборатории в г. Москве)

Бесконтактные средства измерения — сканирование изделия 3D сканером с последующей постобработкой облака точек. Данный вид измерений применяют для сложных изделий, а результатом таких измерений является облако точек, а после постобработки (дополнительной обработки) — фасетная 3D модель. 

Процесс 3D сканирования детали

Скан изделия после постобработки, фасетная 3D модель

Иногда для повышения качества измерений применяют обе методики (комбинированно). В первую очередь необходимо отсканировать изделие и произвести постобработку сканов, получить 3D модель изделия. Для уточнения высоких технических требований к изделию, производят дополнительные ручные измерения точных размеров, шероховатости, допусков формы и взаимного расположения поверхностей. Данные требования отображают на чертежах или на информационной 3D модели изделия.

Измерение шероховатости поверхности профилометром

Определение материала и механических свойств

Часто бывает необходимо определить состав и механические свойства материала изделия, ведь от этого зависят основные эксплуатационные характеристики. Для этого используются различные методы измерения, например, оптико-эмиссионный спектральный анализ химического состава материла, измерение твердости, испытание на растяжения и др. Обратите внимание на состав необходимых средств измерения в лабораториях, где вы собираетесь заказать такую услугу.

Разработка 3D модели

Основываясь на результатах измерения, инженеры разрабатывают твердотельную 3D модель изделия в специальном программном обеспечении (CAD-система).

Твердотельная модель изделия 

Разработка чертежей

В CAD-системах имеются инструменты для разработки чертежей и спецификаций изделий, но в наши дни в норму входит отображение технических требований изделия непосредственно на 3D модели, потому что это значительно снижает трудоемкость разработки конструкторской документации и повышает читаемость требований к изделию.

Классический чертеж детали

Информационная 3D модель с техническими условиями

Внесение изменений в конструкторскую документацию

При необходимости, для повышения технических параметров или технологичности конструкции изделия могут быть внесены изменения в конструкторскую документацию. Как правило, это небольшие правки конструкции, например, добавление или перенос ребер жесткости, изменение присоединительных размеров, изменение радиусов скругления и т.д. Но технический прогресс не стоит на месте, на сегодняшний день имеются специальные алгоритмы топологической оптимизации конструкции изделия, которые позволяют значительно улучшить технические характеристики изделия, например, снизить массу детали в 2-3 раза с сохранением исходной прочности.

Топологическая оптимизация конструкции рамы

Изготовление и испытание опытного образца

При необходимости для подтверждения технических параметров, далее необходимо изготовить опытный образец и провести испытания для подтверждения всех технических параметров. Альтернативный вариант, используя разработанную 3D модель изделия, произвести расчеты в системе инженерного анализа (CAE-система). Результаты расчета помогаю определить недостатки конструкции изделия и оперативно внести изменения, а также подтвердить технические характеристики. В зависимости от назначения детали и требований к надежности, расчёт в CAE-системе может заменить реальные испытания опытного образца.

Инженерные расчеты в CAM — системе

Производство партии изделий

Конструкторская документация необходима для разработки технологического процесса изготовления изделия детали. На современных производствах используют оборудование с ЧПУ, для которого необходимы управляющие программы, чтобы их разработать нужно специальное программное обеспечение (CAM-система) и 3D модель изделия.

Разработка управляющей программы для станка с ЧПУ в CAM-системе

Применение обратного инжиниринга

Основное применение реверс-инжиниринга – это получение конструкторской документации на изделие для последующего его изготовления. 

Вы закупаете комплектующие у иностранных поставщиков для сборки изделий, но из-за санкций или других причин поставки прекращены или стоимость и срок поставки значительно увеличились. Рассмотрим другой пример, у вас вышла из строя уникальная деталь в оборудовании, а поставка такой запчасти может быть невозможна или крайне долгой / дорогостоящей. Из-за простоя оборудования вы понесете большие финансовые потери. Из примеров вполне очевидно, что ваше производство и финансовая стабильность сильно зависят от сторонних ограничений и разрешений, уникальных поставщиков.

Оптимальное решение данных проблем — это при помощи обратного инжиниринга разработать конструкторскую документацию на важные для вашего производства изделия и комплектующие. Кстати говоря, часто наши заказчики с нашей помощью даже улучшают конструкцию таких изделий. Имея КД, можно разместить заказы на их производство у различных исполнителей, либо самостоятельно организовать их производство.

Преимущества реверс-инжиниринга

Преимущества обратного инжиниринга в разрезе текущих реалий:

  1. Сокращение затрат — снижение стоимости изготовления изделий, при производстве партиями или сериями, за счёт локализации производства, оптимизации логистики и др. факторов;
  2. Многократность воспроизведения — по конструкторской документации, полученной в ходе реверс-инжиниринга, изделия можно изготавливать неограниченное количество раз на любых производствах в зависимости от ваших потребностей;
  3. Надёжность поставок независимо от санкционных ограничений, скачков курсов валют, одного поставщика.

Дополнительные преимущества обратного инжиниринга:

  1. Возможность доработки дизайна, технологичности отдельных узлов или деталей в целом, унификации и др.;
  2. Возможность стать поставщиком деталей, изделий сторонним предприятиям, которые нуждаются в подобной продукции;
  3. Выбор лучших — возможность изготовления на нескольких производствах с целью выбора поставщика с лучшими условиями и/или с целью диверсификации производственных мощностей.

Вы можете заказать услугу по реверс-инжинирингу в нашей компании и получить 3Д модель или конструкторскую документацию в минимально возможные сроки при высоком качестве.

Понравилась статья? Поделить с друзьями:
  • Как пишется ребятничество
  • Как пишется ребятенок или ребетенок
  • Как пишется ребята или рябята
  • Как пишется ребята всем привет
  • Как пишется ребенок подросток