søndag 20. oktober 2013

Scraping with Ruby

Lately i have been fiddling around with several libraries which simplifies the whole process of working with HTML pages in Ruby. For the simplest of HTML-handling "open-uri", a default library that comes with Ruby, should be sufficient. To handle html-code in a more complex way i have tried both Mechanize and Nokogiri to help me extract wanted information based on certain criteria i have. The process of extracting and parsing data obtained from web-sites are commonly called "scraping". There have been written numerous articles and blogs on the subject, so for the sake of it - here is yet another one:)

As an example i am going to extract electronic components from a vendor, where i want specific information of each component - information like Serial-number, Name and price are all relevant. I want to place the components in its category since i am going to fetch several different component-types, such as resistors, transistors, diodes, IC, Crystals and resonators.

Scraping

If i were to extract all this informasjon by hand it would be quite tedious work, so what isnt more fun than to create a script that simulates humans browsing through wanted paged and extracts all this informasjon for us, which again we can use to manipulate on a later time by storing into files. The way we search / scrape for relevant information is by searching for certain elements in the source-code of each page by using so called CSS-selectors. As we might know, CSS (Cascade Styling Sheets) are used to keep page styles, fonts and such separate and easily available from your code. In CSS we often rely on using selectors to mark up which part of the code each style should be declared on. By using these selectors while parsing we can extract wanted information based on which element we want the selector to grab.

As a side note i want to mention that when ever one build scraping-tools and web-crawlers we should always respect the sites "robots.txt" found in the root of web-domains (http://www.example.com/robots.txt). This file commonly tells robots how they should read a site and where they have and dont have access, read more here - Robots exclusion standard. Although we have pretty decent control over our bot and where to go so it is not a subject in this matter. Though i decided to check the robots.txt-file; They were only rejecting access to the "cgi-bin" folder.

Ruby gem
In ruby we have several gems which does the whole web-scraping process pretty easy. From simple web-scraping to more advanced html-handling liek filling out forms and to process cookies etc. In this example i do not need more than simple CSS-selectors, so i will use Nokogiri to assist me. Nokogiris authors describes it like this:

Nokogiri (鋸) is an HTML, XML, SAX, and Reader parser. Among Nokogiri’s many features is the ability to search documents via XPath or CSS3 selectors.
Okey, this is good and all that - now we need to take a look at the page and see what information we can start with.

Scrape teh page

Lets move to the main site belonging to the vendor and see what it looks like. When we go to http://www.ehobby.no the main page will show some kind of greetings, at the left we can see categories-submenu where we find the following text "Komponenter" (Components) this is a good starting point, now we need to find the tag used to display this text.

Finding elements is pretty easy when using Firebug-extention which allow us to "inpect" certain elements on a site and display the requested element in Firebug's own analysis-window as shown below.


Since this is all the information we need from the main page it surely would be alot easier if we just gave that URL to our bot instead of writing a small procedure to extract this portion of the code. Lets move on to the category-listings page where we will find our wanted categories of each component. Now we can start looking for the wanted elements and put them right into Nokogiri as CSS-selectors and extract each category. To hold only the wanted categories i created a hash with key-names of each of the wanted categories, each key holds an array as value to store each component inside.

Let us try to use Nokogiri to show show us the url to the components-type we want. The elements we can use are shown in picture below where we will see how each category is wrapped inside a div-tag with class-name "categoryListBoxContents".


By using IRB for testing purposes we don't hammer the web-site with requests as we create a Nokogiri-object of the page and search for the elements by using CSS-selector shown above. A picture of how the test-script looks like is shown below.



This will output Category-name and URL to components in each category. It is quite easy to extract the information this way as we just have to identify the elements and place those into Nokogiri, but when we do look at the resistors components-list (for example) we will see it shows only 10 results pr page, "Showing N of N (out of N products)", so we need to create a method finding out how many results we have obtained and how many pages there actually are. Firebug help us find the selector to identify these number and extract them. Below is a picture of how this info is extracted and used in a method in ruby.


All we need now is to extract each component and put it into the right hash-key of categories. To scrape the components i could use the css-selector "table .tabTable tr", but this gave me 11 results pr page - so it did actually include the text of each column on the page as well as all the 10 components. To drop out the column-text i had to look for <td>-tag inside the selector shown above, if this contained 4 elements we assume that is the column we want and place them into an array. The only problem is, because i use a very nasty split to extract the prices we dont get the right price - since i only extract one decimal (and split them at ","). But for this example i guess this is all good.

At this point we can handle the extracted data just as we want - we already have them in a container. But as the complete script will reveal, i wrote them into a simple text-file. Now all we need is a complete scrape_index-method, which are going to loop through all the categories, fill them with wanted information.

Now we have completed the scraper to extract wanted information and store it in a simple way.

This is the basics of web-scraping, script can be found on me drive

mandag 10. juni 2013

Flere NSM utfordringer

Sist post omhandlet ene og alene om utfording 6 (shellcode analysis) som Nasjonal Sikkerhetsmyndighet har gitt ut i sin blog  i et forsøk på å bemanne en rekke stillinger. . I denne posten analyserer jeg flere av de andre utfordringene jeg klarte. Utfordringene er tilgjengelig her.

Utfordring 1

Kryptert tekst-streng:
PNRFNE PVCURE RE SBE YRGG.
SVAA SYRER HGSBEQEVATRE CNN FVXXREURGFOYBTTRA GVY AFZ.
Den krypterte teksten er Cæsar cipher, eller nærmere bestemt ROT13 kryptering hvor man endrer bokstavers basis-plass i alfabetet for å kryptere tekst, f.eks som å forskyve alfabetet 13 plasser til høyre som det gjøres spesifikt i ROT13 cipher.... Ved hjelp av Ruby og String.tr-funksjonen kan vi gjøre dette på en effektiv måte.
class Rot13 def self.decode(encoded_string) encoded_string.tr("A-Za-z", "N-ZA-Mn-za-m") end end encoded_string = "PNRFNE PVCURE RE SBE YRGG.\nSVAA SYRER HGSBEQEVATRE CNN FVXXREURGFOYBTTRA GVY AFZ." print Rot13.decode(encoded_string) # # Output: # $ ruby 1.rb # CAESAR CIPHER ER FOR LETT. # FINN FLERE UTFORDRINGER PAA SIKKERHETSBLOGGEN TIL NSM.
Caesar cipher Ruby-gem

Utfordring 2

ULFC://TXBYS.AKY.FLMG.FA/GSD/QM/GGXAEVDVFSRF? 

I oppgaven ser vi en tekst-streng som ligner mistenkelig på en web-adresse. Siden den kun krypterer bokstaver velger jeg å prøve ut Vigenère cipher-tabellen og. Siden vi ikke har peiling på nøkkel-ordet som eventuelt skulle brukes i cipher kan vi først prøve å se for oss at det står "http://blogg.nsm.stat.no/" om ikke annet, så finner ihvertfall deler av nøkkelen ved å konvertere http. Det viser seg å være NSM som er nøkkel-ordet brukt til å kryptere web-adressen. Dette har jeg prøvd å illustrere i bildet under, hvor på toppen man ser nøkkel ordet, og i kolonnen til venstre ser vi dekrypterte dataene.



Vi ser at ULFC blir NSMN så da har vi nøkkel-ordet og kan fortsette kryptering, enten ved hjelp av ruby eller på papiret. Uansett vei så ender vi opp med dette når strengen er dekodet: http://blogg.nsm.stat.no/tar/du/utfordringen?

Vigenére cipher Ruby-gem

Utfordring 4

Bildet som vises frem inneholder steganografisk data og det finnes mange forskjellige metoder for å skjule informasjon  ved hjelp av steganografi. Steganografi er en måte å skjule informasjon ved at meldingen opptrer som noe helt annet, som f.eks bildet. Første hintet får man når man søker etter fil-informasjon, da ser vi en kommentar på bildet som er uleselig. Kommentaren er krypert og når jeg ser på den krypterte tekst-strengen får jeg lyst å prøve ut Base64-biblioteket i Ruby / IRB.


Kommentaren er kryptert ved hjelp av Base64 kryptering og da kan vi jo egentlig bare tippe en gang på hvilket passord man kan trenge for å ta ut dataen som ligger skjult i bildet ;) For å hente ut dataen som ligger i bildet bruker jeg et program som heter "steghide", og vi prøver med NSM som passord. Under ser vi resultatet.



Shellcode - NSM utfordring 6

Nasjonal Sikkerhetsmyndighet (NSM) har lagt ut en rekke utfordringer / oppgaver som mann kan løse. Jeg satte meg ned i helgen for lese litt på oppgavene, etter å ha lest gjennom de en gang løste jeg noen av, andre var igjen umulig for meg å løse. Denne blogg-posten omhandler "utfordring 6" hvor mann skal analysere noe som ser ut som en shellcode.

Koden vi ser er skrevet som ren maskin-kode (assembly op-codes). Slik maskin-kode kalles ofte for shellkode og blir brukt i forbindelse med utnyttelse av sårbarheter i programmer og OS. Man ønsker at shellcode skal være så liten som mulig, og er ofte bare små program-snutter, slik som vi ser i eksempel under. Navnet kommer av at man ønsker å starte ett skall/shell hvor angriperen har full tilgang til kommandoer etter at en sårbarhet er utnyttet.

Det er lett å identifisere teksten som en shellcode da jeg så noen kjente "op-codes", som xor (31) og cd 80 (unix' syscall: int 80).
31 db f7 e3 68 ff f4 f5 e2 68 fb f5
b0 f8 68 b0 fb fc ff 68 fc f5 e2 f5
68 f5 e2 b0 f6 68 e2 f5 fe f7 68 c6
f9 b0 e4 b9 90 90 90 90 31 0c 04 04
04 3c 1c 75 f7 89 e1 31 c0 b0 04 b2
1c cd 80 b0 01 cd 80
Derfor kan jeg anta at programmet er ment for ett UNIX operativ-system da vi ser nettopp den instruksjonen.

Man kan konvertere dette om til assembly manuelt ved hjelp av "X86 Opcode and instruction Reference" eller ved hjelp av ConvertShellcode.exe diskutert i denne blogg-posten av Lenny Zeltser. Når shellcoden er konvertert kan vi analysere koden ved hjelp av noe så enkelt som ett skrive-program eller om man vil gjøre dynamisk analyse av filen kan mann kompilere som vist i neste steg.


Slik ser maskinkoden ut når den er konvertert til assembly, og det er en liten programsnutt som dekrypterer en text-streng ved hjelp av en xor loop. På bildet ser vi hvilken "nøkkel" som verdiene skal utføres en logisk xor mot.. Jeg måtte ligge inn en "loop" funksjon i assembly koden, slik at JGE-instruksjonen hadde et sted å hoppe til om den IKKE er lik 28, så koden ser da slik ut:

På dette tidspunktet kan man gå mange forskjellige "veier" for å utføre videre analyse av filen. Man kan f.eks kompilere filen som vist på bildet under og kjøre den, enten direkte eller analysere den videre i en disassembler....


Men jeg følte for å koze meg litt til med utfordringen og lagde derfor ett Ruby-script som tar de krypterte dataene og xor'er de med nøkkelen som er 0x90909090. Når jeg først så disse verdiene i maskin-koden trodde jeg det var "nop"-instruksjoner men de viste seg å være verdien dataene skal utføre logisk xor med...


lørdag 25. mai 2013

A computer infested with pest.

There is this PC i am working on at the moment which at first had ransom-ware installed, and got fixed by this guy who actually thought that to install a pirated version of Windows 7 was a good idea - and gave the owner back his machine.. A couple of days later the owner gave me a call (yeah after the malware was removed!!)  and had some issues with installing common programs so he could go back to everyday use of his PC.

After installing needed software and patching the OS, i found yet another malware-sample. This was clearly a old sample, the mothership had moved on as the sample could not contact certain domain. Without wanting to do so much more, i went on and installed software. 
So now, 30 days later i am sitting with a computer in my lap which are yelling for a Genuine Windows 7-version, and installed version is Win7PRO, key supports HomePremium OEM. To make things a bit more fun the recovery partition was also deleted during the "repair". Next time, please hit ALT+F10 during computer boot-process - at least try it - before deleting it! I am not sure how the process went when this computer got "fixed", and the latter example might not even work to remove some malware-samples.

It is not every day i create Windows USB-sticks so i decided to document this funny incident. 


Todo


1. Download proper windows version
Found this blog where i could download a windows 7 version: http://answers.microsoft.com/en-us/windows/forum/windows_7-windows_install/windows-7-home-prem-oa-acer-group/d6606520-8a45-4f47-a5ed-22978f4f602d

2. Create filesystem on stick

2.1. Create a ntfs partition with fdisk

start fdisk /dev/sdb, and i performed actions shown in picture below




2.2 Create NTFS filesystem.
Install ntfsprogs and ntfs-3g from repository
sudo mkfs.ntfs -f /dev/sdb1

3. Mount windows 7 iso and USB-stick.
Iso
sudo mount -o loop Downloads/X17-58996.iso /media/cdrom0/
Usb-Stick
sudo ntfs-3g /dev/sdb1 /media/usb0

4. Copy files from ISO to USB-stick
sudo cp -R /media/cdrom0/* /media/usb0/
4.5 Make a cup of tea and chill while it copy

5. Download ms-sys-*.tar.gz from http://ms-sys.sourceforge.net/#Download, unpack, compile and install.
In order for this to work i had to install gettext-package from repository and change dir to path of downloaded ms-sys*.tar.gz file before executing command below.

sudo apt-get install gettext; tar -xzvf ms-sys-*.tar.gz ; cd ms-sys*; make && sudo make install 
Next we can create a Windows 7 MBR on the device
sudo ms-sys -7 /dev/sdb

Unmount USB-stick, cross yer fingers while booting up the computer.

6. Create partitions 
Create backup partition (i decided to use 15GB)
Create OS partition

Make things easy

If one want to do this using GUI, i would believe that gparted package from debian-based linux distros could be used to format and create file-systems needed. To copy the files i would believe that unetbootin could be used as well. I have not tried this my self - so i can not confirm this work, but it does pretty much the same so why not.


onsdag 22. mai 2013

Suspicious Domains

Malware are often trying to "phone home" to a command and control-server (C&C) or exploit a client by redirecting web-queries to a "malicious-landing-page", and often malware are relying on Domain Name System(DNS) to perform this action. By using DNS the botnet herder can move their mothership of listening C&C(s) quite easily, both by changing domain-names often to avoid detection of the IP-address of the mothership as well as well as move C&C to another node without upgrading all bots. Often these domains are created with fake credentials and used for a short period of time. Therefor one tell-tail to detect, not necessarily malicious network activity, but suspicious network activity, could be by obtaining whois information on the domain and especially "Created on" date. One could divide these results into a few "priority-levels" (1-3), where #1 is within a week, #2 is within a month and #3 within six months.

I made a tool to ease the analysis of a packet capture file (pcap) using Ruby and PacketFu-gem. The tool parses through network packets looking for DNS queries, if it receives such query it will do a simple Whois on the domain. If the domain is created within one of the three given levels shown above, it will be reported as a suspicious domain.

A simple test from a lab-environment is seen below, where we see two domains created this very week, that is a suspicious domain.

Of course, when we see the results it is quite easy to distinguish these two domain names from more common words, but the latter are often used as well - and this is at least one easy way to extract DNS queries and look for suspicious domain-names.... By using Snort a couple of days later on the same pcap-file i got confirmation on my findings, both alerted as "ET CNC Reported CnC Server IP".

I first saw this while doing analysis on one of the many different malware-samples shown in the "A botnets compromise" blog-series, where the different samples changed domain name frequently.

onsdag 6. mars 2013

Botnets compromise Pt.3

As seen in part 2 of this blog-post series, after the machine was compromised the bot was commanded to download yet another executable. This file was unpacked in the same manner as h2.exe, and seems to be packed by a custom FUD-crypter.

Hj3_unpacked.exe

MD5: 5deced762376b619560a801edaf3a722
SHA1: 2f3dbdbd4aa88ace0d3c88865523482b83401f83

Since the imports table was quite big i decide to not apply imports address table (IAT) in this post, but there are many interesting functions and again just by looking at the imports we get a good idea of this specimens capabilities.
By using strings i quickly could identify the bots capabilities and i remembered that i had done some analysis on another variant before. It is the infamous NGRbot, as we already could identify by VT-report in Part1 of this article. With the same output from strings we could identify and confirm some of the findings in IAT and get a good network- as well as host-based information on how this bot operates.


Characteristics as documented several places on teh internets.
- Injects into all running processes. When injected into explorer.exe it starts to connect to an IRC C&C.
- Spread via MSN and USB.
- Injects iframes into ftp and http traffic to redirect traffic / block legal web traffic.
- Can redirect or block DNS requests to avoid updates from AV vendors.
- Flooding UDP, SYN, Slowloris
- Proactive defence with pdef+
- Made persistent by copying it self into "C:\Documents and Settings\$user\Application Data\Gjhqhw.scr" and by adding a entry same as filename(Gjhqhw) pointing to that location in HKU\S-1-5-21-XXX\Software\Microsoft\Windows\CurrentVersion\Run. (Safe-mode needed to remove this entry, else we would not see this entry)

By setting breakpoint on kernel32.OpenProcess and kernel32.CreateRemoteThread and by redirect them to a non system process i was able to parse each and every process that got injected. This made it quite time consuming and if it is not running inside the explorer.exe it will not execute anything at all.

In the pictures we can see the domain names used to connect to the irc c&c server and  some of the supported commands. In the picture to the right we can see the location where the file is copied to in a way to make the bot more persistence.










This bot will again use api.wipmania.com to get ip and geo location. When this bot it connected to its C&C server it will get commanded to download a root kit to fully compromise a victims machine. As we see in the picture below.




More conducted analysis here:
http://resources.infosecinstitute.com/ngr-rootkit/
http://blogs.mcafee.com/mcafee-labs/ngrbot-spreads-via-chat
http://blogs.mcafee.com/mcafee-labs/ngrbot-posing-as-skype-targets-social-networking-sites

torsdag 14. februar 2013

Debian Honeywall howto

Abstract

This howto will describe how to set up a honeywall acting like a hidden gateway typically used to secure a honeynet environment from an production environment. Operating system used in this article is Debian 6.0 installed as a vm-guest.

Introduction

Honeynets are designed to get a better understanding of how an attacker exploits vulnerabilities on a network-device and to develop a better knowledge in the latest security threats.

Vulnerable devices in a honeynet, commonly called honeypots, are intentionally set up to be vulnerable to many different attacks, or by using a clean install of an OS and wait for an attacker to perform probes and hopefully perform unknown attacks on a system. The latter is often referred to as High Interaction Honeypots, while emulating services often is called Low Interaction Honeypots.

A honeywall is a hidden device acting like a bridge between different networks and are commonly used to seperate a honeypot from an production environment, with the capabilities of controlling data sent in and out as well as monitoring network traffic. It can also be used to analyse traffic during a live malware analysis to mention a few of its workspaces. The honeywall is a crucial device in a honeynet to get as much information regarding malicious activity - both before and during an actual attack.

In order to secure a honeynet network, Honeynet Project has developed several standards and requirements regarding honeynets such as data control, data capture and data collection to lower the risk of exploitation of the production environment.

You can read more about honeynet's here and to meet the requirements I followed “Honeynet Definitions, Requirements, and Standards”.

Environment

To meet the requirements in a honeynet there are several things one should keep in mind:
First the honeywall it self need three Network Interface Controllers (NIC), one connected to the external network (Router -> Internet) and one connected to the internal network (honeynet).
These two NIC's are setup as a hidden bridge, so there will not be assigned any IP-addresses to them.

Therefor to remotely control this honeywall we need another NIC for remote-management, to easily administer and get wanted information provided by the honeynet.

NICs
  • eth0 - Bridged - External network (internets)
  • eth1 - Vboxnet1 - Internal network (honeypots)
  • eth2 - Vboxnet0 - Remote management (safe network)

Data Control

Once the attacker has gained access to your honeypot one need to prevent attacks on unwanted devices, such as your production network and external devices outside your own network (eg. the internets ). To prevent this we use at least two layers of protection, as described in the "Definitions, Requirements & Standard"-link above.

To control the network-flow we will use

  • IPTables as firewall with connection limit.
  • Snort as Intrusion Prevention System (IPS) to drop malicious packets.

Data Capture

To capture probes, malicious activity and other information on the honeynet we need to set up logging capabilities.

  • TCPDump to capture all network traffic.
  • IPTables logging to capture conditions met by firewall rules.
  • Snort as Intrusion Detection System (IDS) to log malicious network traffic.
  • P0f to identify host information like applications and OS based on network packets.

Download the howto from google drive.

lørdag 9. februar 2013

A botnets compromise - Pt 2

After i unpacked h2.exe i was able to do static analysis and get a good understanding of what was going on without execute the file. It has various tricks to obfuscate the malware and made analysis harder. When executed it will connect to an irc server, join a channel and await further orders which are typical for RAT or a bot if you want.

h2_unpacked.exe
md5sum: 8359679bbfedeb343f105a1490b992ef
sha1sum: dcc583732e7e00a8f64e873bea6445742d9cd7f2


Imports:
KERNEL32.DLL: lstrcmpiA, GetProcAddress, ExitProcess, GetSystemTime, GetTickCount, lstrlenA, GetCurrentProcess, LoadLibraryA, CloseHandle,

ADVAPI32.dll: LookupPrivilegeValueA, AdjustTokenPrivileges, OpenProcessToken,

Based on the imports-table we could expect some sort of process injection as it use LookupPrivilegeValueA, AdjustTokenPrivileges, OpenProcessToken from the ADVAPI32 library.

When i first ran strings utility i got a pretty good idea of what was going on but those findings didn't add up with the imports-table above. Based on the output i would expect the malware to use privilege escalation with SeDebugPrivilege and that the bot has the ability to flood. Further on we could expect persistence by hiding it self somewhere on the harddrive with the name avmngs.exe. It will also connect to a domainname as shown in the picture below. And again, since the imports table looks quite incomplete one should lookout for  decryption loop to import library functions.




When i opened the file in IDA Freeware i found privilege escalation with SeDebugPrivilege and a Decryption loop to get encoded library strings. It calls the decryption loop with "f424" as argument. Below we can see the difference before it decrypt library names and after.


Immediately after this the malware starts to inject it self into a new process, this will make the malware harder to analyse as well as it will be much harder to detect when a machine is compromised. It parses through running processes with the help of CreateToolhelp32Snapshot and process next etc, which is pretty easy to identify. It injected small portions into explorer.exe so in order to analyse the file further i renamed the process, set a breakpoint on CreateRemoteThread and injected it into a non system process and attached OllyDBG.

Now i could continue to analyse the file and it will repeat the step to decode functions and library names as well as path's to make the malware persistent were obfuscated. Next it created a Mutex with the name cniv,s and i learned how the malware made it self persistent; namely by copying it self into C:\RECYCLER\R-1-5-21-1482476501-1644491937-6820003330-1013\avmngs.exe  and added a new entry into windows registry with the name Taskman.



The bot then tries resolve an IP to the domainname we saw in the strings-output earlier and connects to it on port 3322. The IRC server it is connecting to accepts custom made commands as we can see below. It goes through several loops to generate nickname and user information to send. The malware sends PASS eee, KCIK(NICK) nickname, and ssrr(user) and automatically joins a channel by name #dpi. When the bot has joined the channel it gets commanded to download a file with the command !dl <location>, and join another channel - namely #}. Now it just idles those channels and awaits for further instructions.




I started a netcat session listening on port 3322 and used a fakedns ruby script to simulate a real network connection to get the supported commands. The commands i found are similar to this post, as are rest of the bots functions and behavior.

In part 3 i will analyse hj3 executable that got downloaded by this bot.

mandag 28. januar 2013

Something smells fishy...

Immediately after i had replied on someones tweet i received a tweet from a unknown girl with the name of Hugh - who clearly has some issues setting up the christmas lights. Clearly a spam account of some sort. As i do not know that person or could expect that link to contain anything but shady bidnid. Thus i decided, out of pure curiosity, to run that link on a test environment and logged what was going on, hopefully i will find some fun and malicious content. 


Little girl with christmas lights problem sendt me this link

When we click that link above we expect it to redirect us to a real url, since the sender (Hugh) has compressed the url at http://is.gd. The url is actually pointing to r.eurocable.com.br (with a GET parameter as seen below), the ip-address (5.12.190.202) points to a Romanian server. Then we yet again get redirected to cioara.info which are located in Canada, this is where we get a HTTP 200 OK response.

Domain record can be found here. I also did a quick google search on this hostname just to find a few mentions regarding its twitter spam (eg: WOT reputation).

The page source-coude contains a functions called dosub(), which simply submits a form called "frm1". It submits information using http://just-perfect-gifts.com/index.php as form processing agent. The domain just-perfect-gifts.com are located on the same ip as cioara.info, namely 184.107.175.178 which was powered by a ngnix http daemon and php 5.3.18. It is registered through GoDaddy and registrar info via Domains By Proxy... We continue to jump as we load the content of http://just-perfect-gifts.com/index.php it will use <meta http-equiv="refresh"> to load the main page. 

So we end up on a page which is telling me that i have the "opportunity to make some easy money" - clearly spam message as we already saw in the Web of Trust-reputation above. I also found that the domainname was sold on flippa.com in October. The user who was selling this site was suspended from Flippa, and it is getting pretty clear at this time what is actually going on, as that spam message was a way to get a lot of views and thereby get a good rating via Google Analytics. If we see the attachment provided by the user, which is Google Analytics Reports of www.just-perfect-gifts.com. There is certainly a lot of traffic to that site as it was created in May 2012, but the average user has only been at that site a few seconds. I also found another post from the user where he/she is stating that "I am offering twitter followers and accounts."

Next i went through the source-code where i can confirm these findings as i quickly find google analytics code along with facebook-likes button and a Twitter follow button. It says "Follow @JPgifts" but links me to "https://twitter.com/MicroLeavesCash". What i noticed was how the main site was loaded over and over, until i closed the connection. This is clearly a easy way to make a lot of traffic to a site - and to make the site look more valuable one could generate traffic via false advertising and throwing links to users on social media like facebook and twitter.

Okay, ill stop it here as i feel i have wasted enough time on this boring incident, i was actually hoping it contained a malicious iframe of some sort.

tirsdag 15. januar 2013

Securing a Linux server

Summary

In conjunction with another post i am working on i decided to write a small howto on administering and securing a freshly installed Linux distribution. In this small post i am using Debian but these steps should apply to most NIX operating systems. These steps are the minimum requirements to secure your system.

Restricting User Access

Default access to home-directories are umask 022, and as seen below - the user, members of the users group and "others" (none of the above) have read and execute permissions on the user's files. 
Permissions
User
Group
Others
READ
X
X
X
WRITE
X


EXECUTE
X
X
X
               Table 1. Umask 022 permissions

To disallow members of a user's group (and others) to access all the files we can set the umask to 077, which restrict everyone else but the user it self to read, write or execute owned files....

Edit /etc/login.defs and change following settings
#Default
#UMASK          022
#Secure
UMASK           077


Create user

Add a new group
groupadd usergroup
and add user with desired options
useradd --home-dir /home/username --create-home --shell /bin/bash --gid usergroup username
then we are ready to set a password on the account
passwd username

Sudo access

Since we sooner or later are going to disable root, either by disable the user completely or by deny root via ssh, we need a regular user with sudo-capabilities to administer the server.

Install the sudo package from repository
apt-get install sudo
and add username into sudoers
echo "username ALL=(ALL) ALL" >> /etc/sudoers
or as group policy
echo "%groupname ALL=(ALL) ALL" >> /etc/sudoers

If you want too disable password prompt use instead of the above,
echo "username ALL=NOPASSWD: ALL" >> /etc/sudoers

Disable root user

To have one less account to maintain security on, one can disable the root account all together
passwd -l root

Deny root via SSH

If the latter doesn't suite your needs and you want to use the root account - at least deny root login via secure shell (ssh)
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
cat /etc/ssh/sshd_config.bak | sed s/"PermitRootLogin yes"/"PermitRootLogin no"/ > /etc/ssh/sshd_config

Securing SSH

Along with disable root access via secure shell (as shown above) there are several options to further strengthen the security on your secure shell service.
  • ListenAddress 0.0.0.0 - Set this to listen only on a specific IP-address.
  • Port 22 - Change the default SSH port. This is very useful to decrease the bruteforce attempts as most automated scripts searches for port 22 to bruteforce SSH accounts.
  • PasswordAuthentication  - Change this to no in order to only allow people with their SSH-keys in place, this is also a good way to decrease bruteforce attempts. In order for this to work, one need to create a keyfile on your clients machine (ssh-keygen) and copy your public keyfile to the SSH-server (ssh-copy-id).
  • PermitRootLogin - Default is to allow root logins via Secure Shell, change this to no, as described above.

When configuration is done, restart ssh server
sudo /etc/init.d/ssh restart 

Note: If you have more than one Network Interface Controller, ListenAddress should be configured on all services allowing it....

Automatic updates

Earlier i used crontab-daily directly to run apt-get update && apt-get upgrade, but this could in some cases break your install.
Install unattended-upgrades from repository, which was first introduced in Ubuntu.
apt-get install unattended-upgrades
and run
dpkg-reconfigure unattended-upgrades
to configure software. It will create /etc/apt/apt.conf.d/20auto-upgrades with the following preferences

APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";

The default config file (/etc/apt/apt.conf.d/50unattended-upgrades) should do just fine as it will only allow security upgrades. However if you want to upgrade packages as well as security updates uncomment  //  "${distro_id} ${distro_codename}-updates";  in the Allowed-Origins section of the config-file.

To disable automatic-reboot add this line Unattended-Upgrade::Automatic-Reboot "false";
 echo -e '\nUnattended-Upgrade::Automatic-Reboot "false";\n' >> /etc/apt/apt.conf.d/50unattended-upgrades


Basic Firewall

Iptables is the most common firewall software used in Linux systems, altough it is not very user friendly it sure is a powerfull firewall. To simplify firewall management Ubuntu introduced uncomplicated firewall (ufw), which also is available via Debian's repository.
sudo apt-get install ufw
----
Captain Blackadder: "Baldrick, deny everything."
Lieutenant George: "You are private Baldrick?"
Baldrick: "No."
Lieutenant George: "Are you not Captain Blackadder's batman?"
Baldrick: "No."
----

Ufw does pretty much the same as Baldrick by default, denying everything - oh well at least the incomming connections. Thankfully since ufw is easy to maintain, one can easily add wanted rules:
ufw allow 22 - to allow both udp & tcp traffic on secure shell's default port. One could replace port number with service names found in /etc/services.
 ufw deny 22 - Deny incomming traffic on port 22.
ufw allow 22/tcp - to allow incomming tcp traffic on secure shell's default port.

 To delete rules we simply use ufw delete <rule>, in example (if we used ufw allow 22/tcp)
ufw delete allow 22/tcp
If we only want traffic from one specific ip-address we use this syntax: ufw allow <ip-address> or ufw allow from <ip-address> to <ip-address/any> port <port-number> proto <protocol>

In example - to allow traffic from your subnet:
ufw allow from 192.168.1.0/24
abit more complicated rule might be
ufw allow from 192.168.1.110 to any port 22 proto tcp 

When we are done enable the firewall with ufw enable and ufw status verbose to check status of uncomplicated firewall.


References

http://www.debian.org/doc/manuals/securing-debian-howto/
https://help.ubuntu.com/community/UFW