вторник, 16 юни 2015 г.

Close frozen ssh session

 
[enter]~. First press the Enter key, then tilde, and then add a dot and your ssh session will be closed and you can continue your work in back in freed terminal.

неделя, 17 май 2015 г.

USBCCID Dissection & B-Trust Reader/Writer ACR38T

Започвам едно разследване за което е силно вероятно да нямам никакво време да продължа, но това няма да ми попречи да документирам днешните си занимaния.

Кратка предистория:
Имам КЕП (Квалифициран Електронен Подпис) издаден от B-Trust. Като всяка институция в нашата родина тези хора са безкрайно некохерентни в използвана терминология и скачат от преводен термин на български в някакви заемки от чужд език които дори според производителя на устройството не са такива. Пример 'SO PIN' и 'Unblock PIN' са едно и също нещо според тях а на родната публика това по-скоро е известно като 'PUK'.
Понеже в случя става дума за четене на информация от SIM карта на мен ми се струва че употребата на PUK е далеч по-добра или е трябвало поне да се придъжат към терминологията на производителя 'SO PIN'. Но това е друга бира. По темата:

Рекох да си сменям пиновете на устройството и понеже съм много чевръст в пръстите успях да си сменя потребителския пас (PIN - ако се придържаме към телефонните термини) и в опит да си сменя PUK видях как attempts left полето се смалява от 3 към 0 и ме известява че видиш ли съм си блокирал картата. Добре обаче това изобщо не е вярно тъй като устройството работи, а с въведен правилен PIN даже подписва официални документи и банкови плащания.

И почвам да си мисля - SIM картата е носител на информация. Като такъв от него може да се чете. Добре обаче явно и без аутентикация от какъвто и да е тип може и да се пише (може и да е частен случай, но писането в attempts полето е възможно). Е щом е възможно аз защо не зема да си запиша там 999 и да си тествам с каквито там пароли си мисля че съм сложил.

Поразрових в нета и се оказва че тия хора в Белгия ги ползват тези устройства и за други неща и един младеж си е написал дъмпвачка:

https://github.com/xofc/Beid2html

Кода е толкова лалав че все едно аз съм го писал което не е задължително лошо понеже му разбирам какво прави. Човека ползва libusb-1.0

В неговият случай не е писано за същото устройство и съоетвено се налага да се смени usb id-то от хардкоднатото при него 1a44:0870 на 072f:90cc


След тази смяна връзката с устройството окача и той се впуска да му викне един статус:


if (libusb_bulk_transfer(udevp, 0x01, bufout, sizeof(bufout), &n, 1000) < 0)
  {
  fprintf(stderr, "bulk-out failed\n");
  perror("PC_to_RDR_GetSlotStatus");
  return;
  }

Хубаво прави ама много бързо се отказва. След като снифнах с wireshark как си говорят купешкия app и девайса се оказва, че традицията повелява не един, не два а точно 5 пъти да му искаш статус а то да се прави че не разбира. И чак след петия път да му пуснеш един пауър он:



И след пауър онът девайса вече съвсем културно връща  EJCOPv241 за Chip Operating System.

И почват да си говорят с дата блоци. Но кога ще ги разнищя те какви са...
to be continued (or not).

вторник, 25 ноември 2014 г.

Linux Bridge to act like hub

If in need to make a linux bridge very stupid and act like hub:

brctl setageing <bridgename> 0 




This command tells Linux to forget every MAC address that it sees on
the bridge, making it act as a hub.



Lets say you have a vmbr0 with eth0 and tap0 in it and have a VM started with attached tap0 (or you choose it as vmbr0). If you link eth0 to your switch's mirroring port you wont RX a great deal of the traffic because usually linux bridge acts as switch and does not recognize the VM as endpoint for the traffic.

Above command will give you a way to have a VM that listens a mirrored port (so NIDS could be on VM).

You are welcome!

сряда, 3 септември 2014 г.

Какво правим когато забравим да пуснем програмата в screen?

   reptyr is a utility for taking an existing running program and attaching it to a new terminal. Started a long-running process over ssh, but have to leave and don't want to interrupt it? Just start a screen, use reptyr to grab it, and then kill the ssh session and head on home.

Source
Info



neercs is a work-in-progress libcaca project.
Like GNU screen, it allows you to detach a session from a terminal, but provides unique features:
  • Grabbing a process that you forgot to start inside neercs
  • Great screensaver
  • 3D rotating cube to switch between full screen terms
  • Real time thumbnails of your shells
  • Special effects when closing a window
  • Various window layouts...
neercs was written by Sam Hocevar, Jean-Yves Lamoureux and Pascal Terjan. It is free software, and can be used, modified and distributed under the terms of the Do What The Fuck You Want To Public License.



четвъртък, 29 май 2014 г.

[REPOST] Using Facebook Notes to DDoS any website

Facebook Notes allows users to include <img> tags. Whenever a <img> tag is used, Facebook crawls the image from the external server and caches it. Facebook will only cache the image once however using random get parameters the cache can be by-passed and the feature can be abused to cause a huge HTTP GET flood.

Steps to re-create the bug as reported to Facebook Bug Bounty on March 03, 2014.

Step 1. Create a list of unique img tags as one tag is crawled only once

<img src=http://targetname/file?r=1></img>
<img src=http://targetname/file?r=2></img>
        ..
<img src=http://targetname/file?r=1000></img>
 
Step 2. Use m.facebook.com to create the notes. It silently truncates the notes to a fixed length.
 
Step 3. Create several notes from the same user or different user. Each note is now responsible for 1000+ http request.

Step 4. View all the notes at the same time. The target server is observed to have massive http get flood. Thousands of get request are sent to a single server in a couple of seconds. Total number of facebook servers accessing in parallel is 100+.

Initial Response: Bug was denied as they misinterpreted the bug would only cause a 404 request and is not capable of causing high impact.
After exchanging few emails I was asked to prove if the impact would be high. I fired up a target VM on the cloud and using only browsers from three laptops I was able to achieve 400+ Mbps outbound traffic for 2-3 hours.

Number of Facebook Servers: 127

Of course, the impact could be more than 400 Mbps as I was only using browser for this test and was limited by the number of browser thread per domain that would fetch the images. I created a proof-of-concept script that could cause even greater impact and sent the script along with the graph to Facebook.

On April 11, I got a reply that said
Thank you for being patient and I apologize for the long delay here. This issue was discussed, bumped to another team, discussed some more, etc.
In the end, the conclusion is that there’s no real way to us fix this that would stop “attacks” against small consumer grade sites without also significantly degrading the overall functionality.
Unfortunately, so-called “won’t fix” items aren’t eligible under the bug bounty program, so there won’t be a reward for this issue. I want to acknowledge, however, both that I think your proposed attack is interesting/creative and that you clearly put a lot of work into researching and reporting the issue last month. That IS appreciated and we do hope that you’ll continue to submit any future security issues you find to the Facebook bug bounty program.
I’m not sure why they are not fixing this. Supporting dynamic links in image tags could be a problem and I’m not a big fan of it. I think a manual upload would satisfy the need of users if they want to have dynamically generated image on the notes.

I also see a couple of other problems with this type of abuse:
  • A scenario of traffic amplification: when the image is replaced by a pdf or video of larger size, Facebook would crawl a huge file but the user gets nothing.
  • Each Note supports 1000+ links and Facebook blocks a user after creating around 100 Notes in a short span. Since there is no captcha for note creation, all of this can be automated and an attacker could easily prepare hundreds of notes using multiple users until the time of attack when all of them is viewed at once.
Although a sustained 400 Mbps could be dangerous, I wanted to test this one last time to see if it can indeed have a larger impact.
Getting rid of the browser and using the poc script I was able to get ~900 Mbps outbound traffic.

I was using an ordinary 13 MB PDF file which was fetched by Facebook 180,000+ times, number of Facebook servers involved was 112.

We can see the traffic graph is almost constant at 895 Mbps. This might be because of the maximum traffic imposed on my VM on the cloud which is using a shared Gbps ethernet port. It seems there is no restriction put on Facebook servers and with so many servers crawling at once we can only imagine how high this traffic can get.

After finding and reporting this issue, I found similar issues with Google which I blogged here. Combining Google and Facebook, it seems we can easily get multiple Gbps of GET Flood.

Facebook crawler shows itself as facebookexternalhit. Right now it seems there is no other choice than to block it in order to avoid this nuisance.

[Update1]

https://developers.facebook.com/docs/ApplicationSecurity/ mentions a way to get the list of IP addresses that belongs to Facebook crawler.

whois -h whois.radb.net ‘-i origin AS32934| grep ^route
 
Blocking the IP addresses could be more effective than blocking the useragent.

I’ve been getting a lot of response on the blog and would like to thank the DOSarrest team for acknowledging the finding with an appreciation token.

[Update 2]

POC scripts and access log can now be accessed from Github. The script is very simple and is a mere rough draft. Please use them for research and analysis purposes only.

The access logs are the exact logs I used for ~900 Mbps test. In the access logs you will find 300,000+ requests from Facebook. Previously, I only counted the facebookexternalhit/1.1, it seems that for each img tag, there are two hits i.e. one from externalhit version 1.0 and one from 1.1. I also tried Google during the test and you will find around 700 requests from Google.


Original article: http://chr13.com/2014/04/20/using-facebook-notes-to-ddos-any-website/#update
Source: http://dailyleet.com/using-facebook-notes-to-ddos-any-website/

събота, 10 май 2014 г.

Bind9 with DLZ and mysql backend... wait for it.. in Docker :)

Get yourself working docker.io installation.

Make doker file (its called Dockerfile)

#builddns image
#VERSION 0.1

FROM ubuntu:14.04
MAINTAINER Peach Lover <some@email.com>


RUN apt-get -qq update

Build image out of it

#docker build -t peach/builddns .

Start the docker container
#docker run -i -t -p 53:53/udp peach/builddns /bin/bash

Attach there and build some code






apt-get update
apt-get upgrade

apt-get install bind9 bind9utils build-essential debhelper hardening-wrapper libcap2-dev libdb-dev libdb-dev libkrb5-dev libldap2-dev libmysqlclient-dev libpq-dev libssl-dev libtool libxml2-dev mysql-client mysql-server openssl unixodbc unixodbc-dev
apt-get remove bind9
apt-get build-dep bind9

mkdir /root/bind9
cd /root/bind9
apt-get source bind9
cd bind9-9.9.5.dfsg

vi debian/rules
add the following
--with-dlz-mysql=yes

dpkg-buildpackage -rfakeroot -b

dpkg -i *.deb

vi /etc/default/bind9
OPTIONS="-u bind -n 1"

vi /etc/bind/named.conf.options
forwarders {
8.8.8.8;
8.8.4.4;
};

vi /etc/bind/named.conf.local
dlz "Mysql zone" {
database "mysql
{host=127.0.0.1 dbname=db_name user=db_user pass=db_pass}
{select zone from dns_records where zone = '$zone$'}
{select ttl, type, mx_priority, case when lower(type)='txt' then concat('\"', data, '\"') when lower(type) = 'soa' then concat_ws(' ', data, resp_person, serial, refresh, retry, expire, minimum) else data end from dns_records where zone = '$zone$' and host = '$record$'}";
};



mysql -p
create database db_name;
grant all privileges on db_name.* to db_user@localhost identified by 'db_pass';
CREATE TABLE `dns_records` ( `id` int(11) NOT NULL auto_increment, `zone` varchar(64) default NULL, `host` varchar(64) default NULL, `type` varchar(8) default NULL, `data` varchar(64) default NULL, `ttl` int(11) NOT NULL default '3600', `mx_priority` int(11) default NULL, `refresh` int(11) NOT NULL default '3600', `retry` int(11) NOT NULL default '3600', `expire` int(11) NOT NULL default '86400', `minimum` int(11) NOT NULL default '3600', `serial` bigint(20) NOT NULL default '2008082700', `resp_person` varchar(64) NOT NULL default 'resp.person.email', `primary_ns` varchar(64) NOT NULL default 'ns1.yourdns.here', `data_count` int(11) NOT NULL default '0', PRIMARY KEY (`id`), KEY `host` (`host`), KEY `zone` (`zone`), KEY `type` (`type`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

// for www.testie.local to resolve to 1.2.3.4
insert into dns_records (zone, host, type, data, mx_priority) values ('testie.local', 'www', 'A', '1.2.3.4', null);

// for testie.local to resolve to 1.2.3.4
insert into dns_records (zone, host, type, data, mx_priority) values ('testie.local', '@', 'A', '1.2.3.4', null);

// for www2.testie.local to alias to www.testie.local
// note the trailing period in the data field
insert into dns_records (zone, host, type, data, mx_priority) values ('testie.local', 'www2', 'CNAME', 'www.testie.local.', null);

// for mail for testie.local to go to testie.local
// note the trailing period in the data field
insert into dns_records (zone, host, type, data, mx_priority) values ('testie.local', '@', 'MX', 'testie.local.', '0');

# extra precaution to make sure packages dont update
for package in bind9 bind9-doc bind9-host bind9utils dnsutils ; do \
echo $package hold | dpkg --set-selections ; done




Test from your host (local on both container and hypervisor will work too since we forwarded port 53)

# dig @localhost testie.local

; <<>> DiG 9.9.5-3-Ubuntu <<>> @localhost testie.local
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 15312
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;testie.local.            IN    A

;; ANSWER SECTION:
testie.local.        3600    IN    A    1.2.3.4

;; Query time: 1 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Sat May 10 14:23:51 EEST 2014
;; MSG SIZE  rcvd: 57



BANG!


Two ways from now:
1. Clean up this container as much as possible.
Stop it. Commit and use it like that.


2. Get your debs. Get your configs. Place on the same folder as your Dockerfile and edit the Dockerfile (for config files you dont need RUN just add them to the correct places).
ADD somefile.deb /somewhere/somefile.deb
RUN dpkg -i /somewhere/somefile.deb

This will 1st copy the file then install it in the instance.

Also add
CMD ["/usr/sbin/named","-4","-u","bind","-n","1","-c","/etc/bind/named.conf","-f"]
at the end. This will be your run command when you start the container.
A nice little "-g" at the end will let you see all the logs that bind spits out when you just attach ... beware if you attach and then ^C you will stop your container instance.

build container
run it
congrats you have a brand new bind9 on a container with dlz-mysql.

Notice: since i am not planning to set mysql on the same container as bind i am not getting in depth of setting the mysql and records in the last Docker setup.

Make this yourself you lazy nerds!


сряда, 7 май 2014 г.

sysdig (поздрав за най-верния ми читател - вероятно единствения)

http://www.sysdig.org/
Sysdig is open source, system-level exploration: capture system state and activity from a running Linux instance, then save, filter and analyze.
Think of it as strace + tcpdump + lsof + awesome sauce.
With a little Lua cherry on top.

http://bencane.com/2014/04/18/using-sysdig-to-troubleshoot-like-a-boss/  - little guide

http://draios.com/fishing-for-hackers/ - What can be done with it

Слага в малкия си джоб swatch, aide и всичко което може да се изтиска от линукска система през syslog.