mardi 3 décembre 2013

St Nicolas va m'apporter ... un malware

On a reçu un super Malware cette année (faut dire qu'on est super sage) , d'après les preuves rassemblées jusqu'ici il semblerait qu'il s'agisse d'Asprox.
Histoire de mesurer l'ampleur des dégâts, j'ai écrit un script nmap pour détecter les machines infectées. L’algorithme de détection est simple comme le Malware démarre un serveur sur port 80 en TCP qui fait semblant d'être un serveur http ... On envoie donc une requête mal formée et du coup il renvoie du binaire pensant qu'il a affaire à son C&C... c'est pas sans faille (il pourrait y avoir des service légitimes écoutant sur le port 80 et n'utilisant pas le protocole HTTP) mais ça suffit pour l'instant.

description = [[
Performs a bogus GET request for the root folder ("/")
Normal http server will reply with an http status 200 or error 
Asporx will reply with around 100 byte of binary.
]]

author = "Jérémie Banier"

license = "Same as Nmap--See http://nmap.org/book/man-legal.html"

categories = {"discovery", "safe"}

require "shortport"
require "http"

portrule = shortport.http

action = function(host, port)
        local result, socket, try, catch
        socket = nmap.new_socket()

        catch = function()
                socket:close()
        end

        try = nmap.new_try(catch)
        try(socket:connect(host, port))
        try(socket:send("HTTP 1.1 GET/\n\n"))
        result = try(socket:receive_bytes(100))

        -- Check if first 4 bytes received are HTTP.
        if not string.match(result, "^HTTP") then
                return "Asprox/Kuluoz infected:" .. stdnse.tohex(result)
        end
end

Résultat: nmap reste mon outil favori de diagnostique réseau :-)

mercredi 30 octobre 2013

Create a local administrator account on every computer of the domain

I've recently implemented a Active Directory domain controller and wanted to get rid of local users ... turns out it's not such a great idea since sometimes you'll need a local admin to fix the AD connectivity... So, I wrote a little script that runs every now and then and create a local user with admin rights for debugging and such... It iterates over all the computer object it will find under the root of the AD and create the user. Beware that it only works if the machines are online, so you'll have to run it often enough to make sure every laptop has been hit at least once.
I hope you'll find it useful.

' This is a script to add local user accounts and add them to the local admin group
' Author: JBANIER Date: 28/10/2013

on error resume next

Const ADS_SCOPE_SUBTREE = 200
Const FOR_READING = 1
Const strUser = "localadmin"
Const strPassword = "localpa$$w0rd"
Dim objConnection, objCommand, objFile, strFile, strLDAP, strSelectAttr

Set objNet = WScript.CreateObject( "WScript.Network" )
Set objRootLDAP = GetObject("LDAP://rootDSE")
strPathToDomain = "LDAP://" & objRootLDAP.Get("defaultNamingContext")
strSelectAttr = "cn, operatingSystem"

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"

Set objCommand.ActiveConnection = objConnection
objCommand.CommandText = _
    "Select " & strSelectAttr & " from '" & strPathToDomain _
        & "' Where objectClass='computer'"
Wscript.Echo objCommand.CommandText
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
Set objRecordSet = objCommand.Execute

objRecordSet.MoveFirst

Do Until objRecordSet.EOF
    ' Create user
    strComputer = objRecordSet.Fields("cn").Value
    Set colAccounts = GetObject("WinNT://" & strComputer & "")
    Set objUser = colAccounts.Create("user", strUser)
    objUser.SetPassword strPassword
    objUser.SetInfo
    Wscript.Echo "Added user " & strUser & " to " & strComputer
    ' add user to admin group
    Set objLocalUser = GetObject("WinNT://" & strComputer & "/" & strUser)
    Set objLocalAdmGroup = GetObject("WinNT://" & strComputer & "/Administrators,group")
    objLocalAdmGroup.Add(objLocalUser.AdsPath)
    Wscript.Echo "Added user " & strUser & " to " & strComputer & "'s local admin group"
    objRecordSet.MoveNext
Loop

Set objConnection = Nothing
Set objCommand = Nothing
Set objFile = Nothing
Set strFile = Nothing
Set strLDAP = Nothing
Set strSelectAttr = Nothing

jeudi 17 octobre 2013

Brucon 2013, scapy or The internet in god mode.

This year I was lucky enough to be able to attend Brucon (courtesy of my employer) , my favorite workshop was this one, I've been wanting to dive into scapy but ... things kept getting in the way :-) the introduction was soft enough not to be disgusted and the challenge slowly grow to something taking a bit of work and trial and error... the final challenge was to download a file hosted on the @undeadsecurity's blog. As it turns out implementing wget in raw socket was good fun :-) Anyway for the curious here's my code:

#! /usr/bin/env python
#vim: set fileencoding=latin-1
# Author: Jérémie Banier
# Date: Oct. 1 2013
# Purpose: implement wget using scapy :-)
# Based on test add-ons sample 
# usage:
# sudo python wget.py
# a, u = wget()

import logging
# Set log level to benefit from Scapy warnings
logging.getLogger("scapy").setLevel(1)

from scapy.all import *

seq = 666

def connect_syn():
    return IP(dst='173.255.253.196')/TCP(dport=80, flags="S", seq)

def connect_ack(p):
    ack = p[TCP][0][1][TCP].seq + 1
    seq = seq + 1
    return IP(dst='blog.zonbi.org')/TCP(dport=80, flags="AP", ack=ack, seq=seq)/"GET /key.txt HTTP/1.0\r\n\r\n"

def data_ack(p):
    ack = p[TCP][0][1][TCP].seq + 1
    seq = seq + 1  
    return IP(dst='blog.zonbi.org')/TCP(dport=80, flags="A", ack=ack, seq=seq)

def disconnect_fin(p):
    ack = p[TCP][0][1][TCP].seq + 1
    seq = seq + 1  
    return IP(dst='blog.zonbi.org')/TCP(dport=80, flags="F", ack=ack, seq=seq)

def disconnect_ack(p):
    ack = p[TCP][0][1][TCP].seq + 1
    seq = seq + 1  
    return IP(dst='blog.zonbi.org')/TCP(dport=80, flags="A", ack=ack, seq=seq)

def wget():
    a, u = sr(connect_syn())
    da, du = sr(connect_ack(a))
    a, u = sr(data_ack(da)$
    a, u = sr(disconnect_fin(a))
    a, u = sr(disconnect_ack(a))
    return (da, du)

if __name__ == "__main__":
    interact(mydict=globals(), mybanner="scaget?")

When run it will launch the python/scapy shell do wget() while running wireshark to see the download taking place ... I'm sure my code isn't so robust and will fail with large file so ...

CentOS package management rollercoaster

Just a quick one liner to recover from a not so sucessfull upgrade on CentOS ...

for p in $(yum update | grep "is a duplicate"  | awk ' { print $6 }'); do rpm -e 
--nodeps --justdb  $p ; done

The package were effectively upgraded but the previous version of the package was still in the rpm database for some reason, this one liner take the duplicate (old one) and remove it's definition from the DB.

jeudi 27 juin 2013

Update IPMI/iDRAC firmware on Dell from Debian Linux



  1. This is inspired by http://jinntech.blogspot.be/2010/04/upgrading-idrac-firmware-dell-ipmi.html slightly reworked to make it work on Wheezy... Thanks to the original author for his work.
  2. install dependencies:#aptitude install ia32-libs rpm
  3. Change /bin/sh to be bash, since this is what the script expect (my take, if you want bash, just #!/bin/bash)# ln -s /bin/bash /bin/sh 
  4. extract the archive:#bash ESM_Firmware_CMDN0_LN32_1.95_A00.BIN --extract .
  5. A bit of hackery to get sub tools to work ...#export LD_LIBRARY_PATH=/root/ipmi_upgrade/hapi/opt/dell/dup/lib/
    and assuming the archive was extracted in /root/ipmi_upgrade ...
  6. Run the actual update tool:./bmcfwul -i=payload/firmimg.d6
    which should give something along the lines of:

   iDRAC6 Firmware Upgrade Utility Version:  1.4.02.119
   Copyright 2009 Dell Inc. All Rights Reserved.
   Please wait... -instsvcdrv: unrecognized service
   Firmware Version                                  Current      Image      
    iDRAC6 ................... Firmware Version      1.70.21      1.95.05    
                               Bootloader version    1.13.7       1.13.7      

and voilà... ipmi is upgraded :-)


mercredi 10 avril 2013

Mais pourquoi ça marche plus ?

Depuis peu mon serveur X n'utilise plus le driver nvidia avec les conséquences qu'on imagine ; plus d’accélération hardware pour la 3D, plus de hdmi ... et pourtant tout est pour le mieux d'après le GUI d'Ubuntu  (12.10)...
Par contre, la version en ligne de commande est moins catégorique:

#sudo jockey-text --list --no-dbus 
WARNING:root:Invalid custom handler module /usr/share/jockey/handlers/fglrx.py
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/jockey/detection.py", line 950, in get_handlers
    execfile(mod, symb)
  File "/usr/share/jockey/handlers/fglrx.py", line 11, in <module>
    from NvidiaDetector.alternatives import Alternatives
ImportError: No module named NvidiaDetector.alternatives
WARNING:root:Invalid custom handler module /usr/share/jockey/handlers/nvidia.py
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/jockey/detection.py", line 950, in get_handlers
    execfile(mod, symb)
  File "/usr/share/jockey/handlers/nvidia.py", line 12, in <module>
    from NvidiaDetector.nvidiadetector import NvidiaDetection
ImportError: No module named NvidiaDetector.nvidiadetector
Un petit "find" trouve le module dans /usr/lib/python3/dist-packages/NvidiaDetector en revanche le script jockey-text lui utilise toujours python2 ... après un petit sudo cp -rp /usr/lib/python3/dist-packages/NvidiaDetector /usr/lib/python2.7/dist-packages tout revient dans l'ordre:
#sudo sudo jockey-text --list --no-dbus 
xorg:nvidia_current - NVIDIA accelerated graphics driver (Proprietary, Disabled, Not in use)
kmod:nvidia_experimental_304 - Experimental NVIDIA binary Xorg driver, kernel module and VDPAU library (Proprietary, Disabled, Not in use)
kmod:nvidia_experimental_310 - Experimental NVIDIA binary Xorg driver, kernel module and VDPAU library (Proprietary, Disabled, Not in use)
xorg:nvidia_current_updates - NVIDIA accelerated graphics driver (post-release updates) (Proprietary, Enabled, In use)

Du coup de nouvelles entrées sont apparues xorg:nvidia... ou avant il n'y avait que les kmod:nvidia... ensuite jockey-text -e xorg:nvidia_current_updates pour réactiver les bon drivers et hop ça remarche :-)

la commande utile du jour:
/usr/lib/nux/unity_support_test -p
OpenGL vendor string:   NVIDIA Corporation
OpenGL renderer string: NVS 4200M/PCIe/SSE2
OpenGL version string:  4.2.0 NVIDIA 304.51

Not software rendered:    yes
Not blacklisted:          yes
GLX fbconfig:             yes
GLX texture from pixmap:  yes
GL npot or rect textures: yes
GL vertex program:        yes
GL fragment program:      yes
GL vertex buffer object:  yes
GL framebuffer object:    yes
GL version is 1.4+:       yes

Unity 3D supported:       yes

jeudi 28 mars 2013

Bitlocker drive encryption and Samba4 ... Will it work ?

I've recently installed a Samba 4 server to handle the 30 windows PC lying around the office and while poking around with what the new toy could do, I wanted to know if it was possible to configure the drive encryption and have a recovery mechanism using the Samba / A.D. server...
It still a running story but here are my progress so far.


The schema needed for BitLocker is not present by default (samba 4.0.3), you can download it (BitLockerTPMSchemaExtension.ldf) from the Microsoft Website, since they are nice enough to provide it for "older" setup.
Then on the Samba server, you'll need to load the new schema using ldbmodify, although there's a couple of gotchas...
  • The file downloaded is in Windows (CR/LF) format and needs to be converted using dos2unix utility, if you don't you'll get "amusing" errors :-S
  • It then needs to be adapted to your need; cat BitLockerTPMSchemaExtension.ldf | sed 's/DC=X/DC=company,DC=com/' > bitlocker.ldif
  • and then loaded into Samba: /etc/init.d/samba4 stop ; ldbmodify -H /usr/local/samba/private/sam.ldb --option="dsdb:schema update allowed=true" bitlocker.ldif; /etc/init.d/samba4 start;
If all worked well; you should see something like this:
[ ok ] Stopping Samba 4 daemon: samba.
Modified 10 records successfully
[ ok ] Starting Samba 4 daemon: samba.

Now all I need is to configure the client PC to use the new schema ... 

Hadoop / Spark2 snippet that took way too long to figure out

This is a collection of links and snippet that took me way too long to figure out; I've copied them here with a bit of documentation in...