Из Википедии, бесплатной энциклопедии
  (Перенаправлено из обфускации кода )
Перейти к навигации Перейти к поиску

В разработке программного обеспечения , запутывание является преднамеренным актом создания источника или машинного кода , который трудно для людей , чтобы понять. Подобно обфускации в естественном языке , он может использовать ненужные обходные выражения для составления операторов. Программисты могут намеренно запутать код, чтобы скрыть его цель ( безопасность через неясность ) или его логику или неявные значения, встроенные в него, в первую очередь, чтобы предотвратить подделку, сдержать обратное проектирование или даже создать головоломку.или развлекательный вызов для тех, кто читает исходный код. Это можно сделать вручную или с помощью автоматизированного инструмента, последний из которых является предпочтительным методом в промышленности. [1]

Обзор [ править ]

Архитектура и характеристики некоторых языков могут облегчить их запутывание, чем другие. [2] [3] C , [4] C ++ , [5] [6] и язык программирования Perl [7] являются примерами языков, которые легко запутать. Haskell (язык программирования) также довольно запутан [8], несмотря на то, что он сильно отличается по структуре.

Свойства, которые делают язык запутываемым, не сразу очевидны.

Рекреационная обфускация [ править ]

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

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

По словам Ника Монфора , техники могут включать:

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

Короткие запутанные программы Perl могут использоваться в подписях программистов Perl. Это JAPH (« Еще один хакер Perl »). [10]

Примеры [ править ]

Это победившая работа Международного конкурса запутанных кодов C, написанная Яном Филлиппсом в 1988 году [11] и впоследствии реконструированная Томасом Боллом. [12]

/ *  НАИМЕНЕЕ ВЕРОЯТНОСТИ ДЛЯ УСПЕШНОГО СОСТАВЛЕНИЯ:  Ian Phillipps, Cambridge Consultants Ltd., Кембридж, Англия * /#include  <stdio.h>main ( t , _ , a ) char * a ; { вернуться !0 < т ? т < 3 ?main ( -79 , -13 , a + main ( -87 , 1 - _ , main ( -86 ,  0 ,  a + 1  ))+ а )) :1 , t < _ ? main ( t + 1 ,  _ ,  a  ) : 3 ,main  (  -94 ,  -27 + t ,  a  ) && t  ==  2  ? _ < 13  ?main  (  2 ,  _ + 1 ,  "% s% d% d \ n "  ): 9 : 16 : т < 0 ? т < -72 ? main (  _ ,  t , "@n '+, #' / * {} w + / w # cdnr / +, {} r / * de} +, / * {* +, / w {% +, / w # q # n +, / # {l, +, / n {n +, / + # n +, / #; \ # q # n +, / + k #; * +, / 'r:' d * '3,} { w + K w'K: '+} e #'; dq # 'lq #' + d'K #! / + k #; \ q # 'r} eKK #} w'r} eKK {nl]' / # ; # q # n ') {) #} w') {) {nl] '/ + # n'; d} rw 'i; #) {nl]! / n {n #'; \ r {#w 'r nc {nl]' / # {l, + 'K {rw' iK {; [{nl] '/ w # q # \ \ n'wk nw' iwk {KK {nl]! / w {% ') l ## w # 'i;: {nl]' / * {q # 'ld; r'} {nlwb! / * de} 'c ;; \ {nl' - {} rw] '/ +,} # # '*} # nc,', # nw] '/ + kd'+ e} +; \ # 'rdq # w! nr '/')} +} {rl # '{n' ') #}' +} ## (!! / " ) : t <-50 ? _ == * а  ? путчар ( 31 [ а ]) :main ( -65 , _ , a + 1 ) : main (( * a  ==  '/' )  +  t ,  _ ,  a  +  1  )  :0 < т ?main  (  2 ,  2  ,  "% s" ) : * a == '/' ||main ( 0 ,main ( -61 , * a ,  "! ek; dc i @ bK '(q) - [w] *% n + r3 # l, {}: \ n uwloca-O; m .vpbks, fxntdCeghiry" ), a + 1 );}

Это программа на языке C, которая при компиляции и запуске сгенерирует 12 стихов из «12 дней Рождества» . Он содержит все строки, необходимые для стихотворения, в закодированной форме внутри кода.

Следующий пример, не выигравший в том же году, иллюстрирует творческое использование пробелов; он генерирует лабиринты произвольной длины: [13]

char * M , A , Z , E = 40 , J [ 40 ], T [ 40 ]; main ( C ) { for ( * J = A = scanf ( M = "% d" , & C ); -  E ;  J [  E ]  = T [ E  ] =  E )  printf ( "._" ); для (; ( A - = Z =! Z )  ||  ( printf ( " \ n |" )  ,  A  =  39  , C  - )  ;  Z  ||  printf  ( M  )) M [ Z ] = Z [ A - ( E  = A [ J - Z ]) &&! C &  A  ==  T [  A ] |6 << 27 < rand () ||! C &! Z ? J [ T [ E ] = T [ A ]] = E , J [ T [ A ] = A - Z ] = A , "_." : "|" ];}

ANSI-совместимые компиляторы C не позволяют перезаписывать константные строки, чего можно избежать, изменив «* M» на «M [3]» и опустив «M =».

Следующий пример, сделанный Оскаром Толедо Гутьерресом, лучшим представителем 19-го IOCCC , реализует эмулятор 8080 в комплекте с терминалом и контроллером диска, способный загружать CP / M-80 и запускать приложения CP / M: [14]

#include  <stdio.h> #define n (o, p, e) = y = (z = a (e)% 16 px% 16 po, a (e) pxpo), h (  #define s 6 [o]  #define pz = l [d (9)] | l [d (9) +1] << 8,1 <(9 [o] + = 2) || ++ 8 [o]  #define Q a (7)  #define w 254> ( 9 [o] - = 2) || --8 [o], l [d (9)] = z, l [1 + d (9)] = z >> 8  #define O)): ((  # определить b (y & 1? ~ s: s) >> "\ 6 \ 0 \ 2 \ 7" [y / 2] & 1? 0 :(  #define S)? (z- =  #define a (f) * (( 7 & f) -6? & O [f & 7]: & l [d (5)])  #define CS 5 S 3  #define D (E) x / 8! = 16 + E & 198 + E * 8! = X?  #Define B ( C) fclose ((C))  #define q (c + = 2,0 [c-2] | 1 [c-2] << 8)  #define mx = 64 & x? * C ++: a (x),  #define A (F) = fopen ((F), "rb +")  беззнаковый  символ  o [ 10 ],l [ 78114 ], * c= l , * k = l  #define d (e) o [e] + 256 * o [e-1] #define h (l) s = l >> 8 & 1 | 128 & y |! (y & 255) * 64 | 16 & z | 2, y ^ = y >> 4, y ^ = y << 2, y ^ = ~ y >> 1, s | = y & 4 + 64506 ;  е , V , v , u , x , y , z , Z ;  main ( r , U ) char ** U ; { {  {  {  }  }  }  {  {  {  }  }  }  {  {  {  }  }  }  {  {  {  }  }  }  {  {  {  }  }  }  {  {  {  }  }  }  {  {  {  }  }  }  {  {  {  }  }  }  {  {  {  }  }  }  {  {  {  }  }  }  { {  {  }  }  }  {  {  {  }  }  }  {  {  {  }  }  }  {  {  {  }  }  }  {  {  {  }  }  }  {  {  {  }  }  }  {  {  {  }  }  }  {  {  {  }  }  }  {  {  {  }  }  }  {  {  {  }  }  }  {  { {  }  }  }  {  {  {  }  }  }  {  {  {  }  }  }  {  {  {  }  }  }  {  {  ;  }  }  {  {  {  }  }  }  {  {  ;  }  }  {  {  {  }  }  }  {  {  {  }  }  }  {  {  {  }  }  }  {  {  {  }  } } { { { } } } { { { } } } { { { } } } { { { } } } { { { } } } { { { } } } { { { } } } { { { } } } { { { } } } { { { } } } { { { } } } { { { } } } { { { } } } { { { } } } { { { } } } { { { } } } { { { } } } { { { } } } { { { } } } { { { } } } { { { } } } for(v A((u A((e A((r-2?0:(V A(1[U])),"C")),system("stty raw -echo min 0"),fread(l,78114,1,e),B(e),"B")),"A")); 118-(x=*c++); (y=x/8%8,z=(x&199)-4 S 1 S 1 S 186 S 2 S 2 S 3 S 0,r=(y>5)*2+y,z=(x&207)-1 S 2 S 6 S 2 S 182 S 4)?D(0)D(1)D(2)D(3)D(4)D(5)D(6)D(7)(z=x-2 C C C CC C C C+129 S 6 S 4 S 6 S 8 S 8 S 6 S 2 S 2 S 12)?x/64-1?((0 O a(y)=a(x) O 9[o]=a(5),8[o]=a(4) O 237==*c++?((int (*)())(2-*c++?fwrite:fread))(l+*k+1[k]*256,128,1,(fseek(y=5[k]-1?u:v,((3[k]|4[k]<<8)<<7|2[k])<<7,Q=0),y)):0 O y=a(5),z=a(4),a(5)=a(3),a(4)=a(2),a(3)=y,a(2)=z O c=l+d(5) O y=l[x=d(9)],z=l[++x],x[l]=a(4),l[--x]=a(5),a(5)=y,a(4)=z O 2-*c?Z||read(0,&Z,1),1&*c++?Q=Z,Z=0:(Q=!!Z):(c++,Q=r=V?fgetc(V):-1,s=s&~1|r<0) O++c,write(1,&7[o],1) O z=c+2-l,w,c=l+q O p,c=l+z O c=l+q O s^=1 O Q=q[l] O s|=1 O q[l]=Q O Q=~Q O a(5)=l[x=q],a(4)=l[++x] O s|=s&16|9<Q%16?Q+=6,16:0,z=s|=1&s|Q>159?Q+=96,1:0,y=Q,h(s<<8)O l[x=q]=a(5),l[++x]=a(4) O x=Q%2,Q=Q/2+s%2*128,s=s&~1|x O Q=l[d(3)]O x=Q /128,Q=Q*2+s%2,s=s&~1|x O l[d(3)]=Q O s=s&~1|1&Q,Q=Q/2|Q<<7 O Q=l[d(1)]O s=~1&s|Q>>7,Q=Q*2|Q>>7 O l[d(1)]=Q O m y n(0,-,7)y) O m z=0,y=Q|=x,h(y) O m z=0,y=Q^=x,h(y) O m z=Q*2|2*x,y=Q&=x,h(y) O m Q n(s%2,-,7)y) O m Q n(0,-,7)y) Om Q n(s%2,+,7)y) O m Q n(0,+,7)y) O z=r-8?d(r+1):s|Q<<8,w O p,r-8?o[r+1]=z,r[o]=z>>8:(s=~40&z|2,Q=z>>8) O r[o]--||--o[r-1]O a(5)=z=a(5)+r[o],a(4)=z=a(4)+o[r-1]+z/256,s=~1&s|z>>8 O ++o[r+1]||r[o]++O o[r+1]=*c++,r[o]=*c++O z=c-l,w,c=y*8+l O x=q,b z=c-l,w,c=l+x) O x=q,b c=l+x) O b p,c=l+z) O a(y)=*c++O r=y,x=0,a(r)n(1,-,y)s<<8) O r=y,x=0,a(r)n(1,+,y)s<<8))));system("stty cooked echo"); B((B((V?B(V):0,u)),v)); }

An example of a JAPH:

@P=split//,".URRUU\c8R";@d=split//,"\nrekcah xinU / lreP rehtona tsuJ";sub p{@p{"r$p","u$p"}=(P,P);pipe"r$p","u$p";++$p;($q*=2)+=$f=!fork;map{$P=$P[$f^ord($p{$_})&6];$p{$_}=/ ^$P/ix?$P:close$_}keys%p}p;p;p;p;p;map{$p{$_}=~/^[P.]/&&close$_}%p;wait until$?;map{/^r/&&<$_>}%p;$_=$d[$q];sleep rand(2)if/\S/;print

This slowly displays the text "Just another Perl / Unix hacker", multiple characters at a time, with delays. An explanation can be found here.[15]

Some Python examples can be found in the official Python programming FAQ and elsewhere.[16][17][18]

Advantages of obfuscation[edit]

Faster loading time[edit]

The scripts used by web-pages have to be sent over the network to the user agent that shall run them. The smaller they are, the faster the download. In such use-cases, minification (a relatively trivial form of obfuscation) can produce real advantages.

Reduced memory usage[edit]

In antique run-time interpreted languages (more commonly known as script), like older versions of BASIC, programs executed faster and took less RAM if they used single letter variable names, avoided comments and contained only necessary blank characters (in brief, the shorter the faster).

Protection for trade secrets[edit]

Where the source code of a program must be sent to the user, for example JavaScript in a web page, any trade secret, licensing mechanism or other intellectual property contained within the program is accessible to the user. Obfuscation makes it harder to understand the code and make modifications to it.

Desktop programs sometimes include features that help to obfuscate their code. Some programs may not store their entire code on disk, and may pull a portion of their binary code via the web at runtime. They may also use compression and/or encryption, adding additional steps to the disassembly process.

Prevention of circumvention[edit]

Obfuscating the program can, in such cases, make it harder for users to circumvent license mechanisms or obtain information the program's supplier wished to hide. It can also be used to make it harder to hack multiplayer games.

Prevention of virus detection[edit]

Malicious programs may use obfuscation to disguise what they are really doing. Most users don't even read such programs; and those that do typically have access to software tools that can help them to undo the obfuscation, so this strategy is of limited efficacy.

Disadvantages of obfuscation[edit]

  • While obfuscation can make reading, writing, and reverse-engineering a program difficult and time-consuming, it will not necessarily make it impossible.[19]
  • It adds time and complexity to the build process for the developers.
  • It can make debugging issues after the software has been obfuscated extremely difficult.
  • Once code becomes abandonware and is no longer maintained, hobbyists may want to maintain the program, add mods, or understand it better. Obfuscation makes it hard for end users to do useful things with the code.
  • Certain kinds of obfuscation (i.e. code that isn't just a local binary and downloads mini binaries from a web server as needed) can degrade performance and/or require Internet.

Decompilers[edit]

A decompiler can reverse-engineer source code from an executable or library. Decompilation is sometimes called a man-at-the-end attack, based on the traditional cryptographic attack known as "man-in-the-middle". It puts source code in the hands of the user, although this source code is often difficult to read. The source code is likely to have random function and variable names, incorrect variable types, and use different logic than the original source code (due to compiler optimizations).

Cryptographic obfuscation[edit]

Recently, cryptographers have explored the idea of obfuscating code so that reverse-engineering the code is cryptographically hard. This is formalized in the many proposals for indistinguishability obfuscation, a cryptographic primitive that, if possible to build securely, would allow one to construct many other kinds of cryptography, including completely novel types that no one knows how to make. (A stronger notion, black-box obfuscation, was shown impossible in 2001 when researchers constructed programs that cannot be obfuscated in this notion.)[20][21]

Notifying users of obfuscated code[edit]

Some anti-virus softwares, such as AVG AntiVirus,[citation needed] will also alert their users when they land on a website with code that is manually obfuscated, as one of the purposes of obfuscation can be to hide malicious code. However, some developers may employ code obfuscation for the purpose of reducing file size or increasing security. The average user may not expect their antivirus software to provide alerts about an otherwise harmless piece of code, especially from trusted corporations, so such a feature may actually deter users from using legitimate software.

Certain major browsers such as Firefox and Chrome also disallow browser extensions containing obfuscated code.[22][23]

Obfuscating software[edit]

A variety of tools exist to perform or assist with code obfuscation. These include experimental research tools created by academics, hobbyist tools, commercial products written by professionals, and open-source software. Deobfuscation tools also exist that attempt to perform the reverse transformation.

Although the majority of commercial obfuscation solutions work by transforming either program source code, or platform-independent bytecode as used by Java and .NET, there are also some that work directly on compiled binaries.

Obfuscation and copyleft licenses[edit]

There has been debate on whether it is illegal to skirt copyleft software licenses by releasing source code in obfuscated form, such as in cases in which the author is less willing to make the source code available. The issue is addressed in the GNU General Public License by requiring the "preferred form for making modifications" to be made available.[24] The GNU website states "Obfuscated 'source code' is not real source code and does not count as source code."[25]

See also[edit]

  • AARD code
  • Spaghetti code
  • Write-only language
  • Decompilation
  • Esoteric programming language
  • Quine
  • Polymorphic code
  • Hardware obfuscation
  • Underhanded C Contest
  • Source-to-source compiler
  • ProGuard (Java Obfuscator)
  • Dotfuscator (.Net Obfuscator)
  • Digital rights management
  • Indistinguishability obfuscation
  • Source code beautification

Notes[edit]

  1. ^ "What is obfuscation (obfu)? - Definition from WhatIs.com". SearchSoftwareQuality. Retrieved February 1, 2019.
  2. ^ Binstock, Andrew (March 6, 2003). "Obfuscation: Cloaking your Code from Prying Eyes". Archived from the original on April 20, 2008. Retrieved November 25, 2013.
  3. ^ Atwood, Jeff (May 15, 2005). "Jeff Atwood, May 15, 2005". Codinghorror.com. Retrieved November 25, 2013.
  4. ^ "Obfuscation". Kenter.demon.nl. Archived from the original on March 4, 2016. Retrieved November 25, 2013.
  5. ^ "C++ Tutorials - Obfuscated Code - A Simple Introduction". DreamInCode.net. Retrieved November 25, 2013.
  6. ^ "C Tutorials - Obfuscated Code in C". July 7, 2011. Retrieved November 25, 2013.
  7. ^ As of 2013-11-25 18:22 GMT. "Pe(a)rls in line noise". Perlmonks.org. Retrieved November 25, 2013.
  8. ^ "Obfuscation - Haskell Wiki". February 16, 2006. Archived from the original on August 30, 2017. Retrieved March 3, 2020.
  9. ^ Montfort, Nick. "Obfuscated code" (PDF). Archived from the original (PDF) on April 24, 2019. Retrieved November 24, 2017.
  10. ^ "JAPH - Just Another Perl Hacker". pm.org. Perl Mongers. Archived from the original on May 16, 2013. Retrieved February 27, 2015.
  11. ^ "International Obfuscated C Code Winners 1988 - Least likely to compile successfully". Ioccc.org. Archived from the original on April 9, 2009. Retrieved November 25, 2013.
  12. ^ ""Reverse Engineering the Twelve Days of Christmas" by Thomas Ball". Research.microsoft.com. Archived from the original on December 13, 2007. Retrieved November 25, 2013.
  13. ^ Don Libes, Obfuscated C and Other Mysteries, John Wiley & Sons, 1993, pp 425. ISBN 0-471-57805-3
  14. ^ Óscar Toledo Gutiérrez: Intel 8080 emulator. 19th IOCCC. Best of Show.
  15. ^ "Obfuscated Perl Program". Perl.plover.com. Retrieved November 25, 2013.
  16. ^ "Obfuscating "Hello world!" – Ben Kurtovic". benkurtovic.com.
  17. ^ http://wiki.c2.com/?ObfuscatedPython
  18. ^ https://code.activestate.com/lists/python-list/16171/ "The First Annual Obfuscated Python Content"
  19. ^ ""Can We Obfuscate Programs?" by Boaz Barak". Math.ias.edu. Archived from the original on March 23, 2016. Retrieved November 25, 2013.
  20. ^ "Cryptography Breakthrough Could Make Software Unhackable". Wired. ISSN 1059-1028. Retrieved March 14, 2021.
  21. ^ Jain, Aayush; Lin, Huijia; Sahai, Amit (2020). "Indistinguishability Obfuscation from Well-Founded Assumptions". Cite journal requires |journal= (help)
  22. ^ at 05:01, Thomas Claburn in San Francisco 2 Oct 2018. "Google taking action against disguised code in Chrome Web Store". www.theregister.co.uk. Retrieved November 12, 2019.
  23. ^ Cimpanu, Catalin. "Mozilla announces ban on Firefox extensions containing obfuscated code". ZDNet. Retrieved November 12, 2019.
  24. ^ "Reasoning behind the "preferred form of the work for making modifications to it" language in the GPL". Lwn.net. Retrieved November 25, 2013.
  25. ^ "What is free software?". gnu.org. Retrieved December 18, 2014.

References[edit]

  • Seyyedhamzeh, Javad, ABCME: A Novel Metamorphic Engine, 17th National Computer Conference, Sharif University of Technology, Tehran, Iran, 2012.
  • B. Barak, O. Goldreich, R. Impagliazzo, S. Rudich, A. Sahai, S. Vadhan and K. Yang. "On the (Im)possibility of Obfuscating Programs". 21st Annual International Cryptology Conference, Santa Barbara, California, USA. Springer Verlag LNCS Volume 2139, 2001.
  • Mateas, Michael; Nick Montfort. "A Box, Darkly: Obfuscation, Weird Languages, and Code Aesthetics" (PDF). Proceedings of the 6th Digital Arts and Culture Conference, IT University of Copenhagen, 1–3 December 2005. pp. 144–153.

External links[edit]

  • A free and efficient obfuscator for JavaScript
  • open source JavaScript obfuscator for batch script
  • The International Obfuscated C Code Contest
  • antispy C/C++ Obfuscation Library for all platforms
  • Protecting Java Code Via Code Obfuscation, ACM Crossroads, Spring 1998 issue
  • Protect Your Java Code - Through Obfuscators And Beyond, April 2009
  • Dotfuscator in — Visual Studio documentation for built-in .NET obfuscation
  • Obfuscation tools for .NET, on MSDN — Obfuscation resources for .NET, on the Microsoft Developer Center.
  • Can we obfuscate programs?
  • Yury Lifshits. Lecture Notes on Program Obfuscation (Spring'2005)
  • Java obfuscators at Curlie
  • Analysis of the 12 days program
  • Analysis of the obfuscated maze generating program
  • Obfuscated Perl program with explanation
  • Analysis of javascript code obfuscation
  • c2:BlackBoxComputation