Simple Java Question: How to print a random int in one class that was generated in another?

Say that I have two classes, A and B, that are in the package Sample.

In class B, I have generated a random int b that is either a 0 or 1. I want to print int b in class A. What code should I use to do this?

Here is class B:

  package Sample;   import java.util.Random;      public class B {         Random random = new Random();         int b = random.nextInt(2); //b is either 0 or 1     } 

And I need code to go in class A here:

package Sample;   public class A {  //How do I print out the int b here?  } 

How do gadget chains work in relation to Java Deserialization attacks?


tl;dr

I would love a detailed explanation how user-controlled input goes from readObject to RCE. Java-specific.

The background

This is my attempt to add specificity to the OP question as requested in the answer here.

I have been slowly but surely breaking into web app security (from a network/infra pentesting and binary exploitation background), and am currently trying to wrap my brain around deserialization attacks, particularly Java. I have taken a few intro Java classes, and am familiar with the basic concepts of OOP, but have never done serious development work. Most of my coding experience is sysadmin-related or exploit writing (bash & python scripting), as well as reading code particularly in vuln writeups and more recently, SAST/DAST WAPTs and code reviews (new to this).

At this point, I am well aware that an application deserializing untrusted user input is very dangerous, especially in Java. However, most resources I’ve encountered thus far gloss over how the untrusted input actual results in code execution. This is what I am very interested in at a detailed level. I feel many others are in a similar position to me and would benefit from this answer.

Research I’ve done to try to understand it myself

I’ve watched Robert Seacord’s video and read portions of his whitepaper. This resource appeared really good but I think they assumed more OOP prerequisite knowledge. Ironically, someone asks a similar question to mine in Seacord’s video (I got excited at that point), but he seems to avoid discussing in-depth as he feels it would require responsible disclosure (my excitement…died).

I’ve also done some hands-on labs such as nickstaDB’s DeserLab with the associated blog post. I was able to get code execution, but don’t quite understand how I got there. The blog helped me understand a lot about the structure of the byte stream, but not how code actually gets run when readObject gets called on the stream. It references Property-Oriented Programming, and compares it to ROP which I am very familiar with. But there is still a gap in my understanding.

Bonus:

I’m also interested in why Robert Seacord felt that going in-depth on a gadget chain would mean he would have to responsibly disclose the gadget chain in some way. I have not heard of that being necessary for other languages such as .NET deserialization gadgets. I well understand ethics and responsible disclosure, I am wondering why or what characteristics of this technique could require disclosure, versus ROP techniques given they compare POP gadgets to ROP. Usually, an overarching technique (ex. ROP) doesn’t need to be responsibly disclosed, but an actual vulnerability does (ex. an overflow that led to exploitation using ROP).

Java Card with a Secure Real-Time Clock

A very long time ago, Dallas Semiconductor released the Java-Powered iButton:

Java-Powered iButton

These devices were somewhat similar in purpose to modern Java Card compliant smart cards, except for one detail: they had a built-in primary-cell battery and a secure real-time clock (RTC). The battery was estimated to be good for up to a decade.

Cryptographic iButton Assembly

Sadly, it seems that the Java-Powered iButton didn’t get market traction. However, having a programmable token with an integrated primary-battery and secure real-time clock is extremely useful since it enables the following features:

  • Active countermeasures that instantly zeroize all contained secrets if the secure element is physically tampered with or the battery is disconnected
  • Preventing operations after a certain date
  • Preventing operations before a certain date

If there is a need to have a security token with an integrated real-time clock, are there any modern solutions that don’t require custom hardware engineering? Is there a modern equivalent to the “Java-Powered iButton”?

How is Hopwood’s Java interface attack related to least common mechanism principle?

I’m trying to understand LCM and how David Hopwood’s discovery is a noteworthy example of it. This site contains two important things. First, it identifies Hopwood’s interface attack (1996) as an example of LCM, and second, it includes a description (highlighted in the screenshot below) of the issue that seems to make things more clear than anything else I could find. The problem is I don’t understand the connection between this vulnerability and LCM.

Here is a screenshot of the referenced site:


least common mechanism from princeton.edu


Hopwood made the announcement through the SRI RISKS-LIST. The full announcement released in issue 17.83 is as follows:

Date: Sat, 2 Mar 1996 23:51:49 +0000 (GMT) From: David Hopwood <david.hopwood@lady-margaret-hall.oxford.ac.uk> Subject: Java security bug (applets can load native methods)  There is a serious security bug in the class loading code for the Java development kit and Netscape (all Java-enabled versions). If an attacker can arrange for two files (a "Loader" class, and a dynamic library) to be installed in any readable directory on the client machine, he/she can by pass all of Java's security restrictions. For example, the applet can read, write and execute files on the client, with the same permissions as the user of the browser.  The only way to avoid this bug at the moment is to disable Java. In Netscape this can be done by selecting 'Disable Java' in the 'Security preferences...'section of the 'Options' menu.    This bug affects all Java implementations based on Sun's source code. It is not related to JavaScript.  Further details will be posted when Sun and Netscape have released patches.  David Hopwood david.hopwood@lmh.ox.ac.uk ------------------------------ Date: Mon, 4 Mar 1996 18:08:58 +0000 (GMT) From: David Hopwood <david.hopwood@lady-margaret-hall.oxford.ac.uk> Subject: Java security bug (applets can load native methods)  Unfortunately my news server has been off-line for the past few days.  However, I'll try to address some of the questions that were raised onstrong-java@entmp.org and in private mail about the recently-discovered bug in Java's class loading code. The same questions have probably been asked on RISKS and/or comp.lang.java as well.  Apparently I wasn't clear enough in stating that this bug allows classfiles to be loaded from _any_ directory on the client machine, not simply those on the CLASSPATH or LD_LIBRARY_PATH. This includes, for example, /tmp,~ftp/incoming, or an attacker's home directory if he/she has an account on the same system.  The attack requires two support files on the client's system: a classfile and a dynamic library. Both files must be readable by the browser, and the dynamic library must be executable (this is always true for systems that have no file permissions). The path to the classfile from the client's root directory must be known by the attacker in advance.  Code demonstrating the bug has been written and tested on Linux and Digital Unix (OSF/1). It should be portable to all POSIX systems, and with a little work, to any system that supports Java. The demonstration is very easy to extend - hiding it within any applet would require adding only two extra lines of code. Changing the C code to execute any command would be a single-line change. For that reason, the code will not be described in detail or released publically until patches are available for both Netscape2.0 and the Java Development Kit.  David Hopwood david.hopwood@lmh.ox.ac.uk 

I have a general understanding that the LCM principal says “mechanisms used to access resources should not be shared” but I’m not able to apply it very well here. I also am not familiar with Java (and I don’t think I really have to be in this instance but it seems like it would help).

My question is, “What is the shared mechanism that is used to access resources?” (Is there another way to describe the crux of the issue?)

Java assignment declaration valid or invalid [on hold]

Question: Why are the following assignments all invalid? Please can you explain why for each individual assignment. I had thought one or two of them were okay given we imported toyPackage.

Given the classes below, indicate whether the assignments are valid or invalid. Notice that we are using two packages.

package toyPackage; public class Toy { protected int size; static int max; public static final int temp = 10; }

package experiment; import toyPackage.*;

public class Driver { public static void main(String[] args) { Toy p = new Toy(); p.size = 10; /* Invalid / p.max = 20; / Invalid / Toy.max = 30; / Invalid / Toy.temp = 40; / Invalid */ } }

Método next() de la interfaz iterator en una lista de pares en Java

estoy implementando el método next() en una lista de pares, Pair Un ejemplo sería [Pair(“hola”,1),Pair(1,9)] Tengo el siguiente constructor:

public ConjuntoIterator(PositionList<Pair<E,Integer>> lista) {      if (lista == null) {             throw new IllegalArgumentException ();          }     this.lista=lista;     this.cursor=list.first();     this.prevCursor=list.prev(cursor);     avanzaCursor(); } 

El método avanzaCursor()

private void avanzaCursor() {       while(cursor != null && (cursor.element().getLeft() == null || cursor.element().getRight()<= 0)) {           cursor = list.next(cursor);           }       } 

Y aquí tengo el método next()

public E next() throws NoSuchElementException {       if (cursor == null) {             throw new NoSuchElementException();          }       E elem = cursor.element().getLeft();       cursor = list.next(cursor);       avanzaCursor();       return elem;    } 

Y mi cuestión es que no consigo resolver que el next me de la parte Integer, pues solo me da la parte de E, ¿Cómo podría hacerlo,gracias?

Mostrar datos de otra tabla relacionada con MySQL, Java web JSP

Quiero mostrar un dato en mi pagina web que se encuentra en otra tabla, por ejemplo, tengo mi base de datos relacionada de esta forma: introducir la descripción de la imagen aquí

donde mi llave foranea en mi tabla usuario es el idPerfil de la tabla perfil, por lo cual mis tablas en MySQL, ya con datos registrados se ven de esta forma: TABLA USUARIO

introducir la descripción de la imagen aquí

y mi TABLA PERFIL

introducir la descripción de la imagen aquí

lo que quiero saber es como podre hacerle para que en mi sitio web aparezca el nombrePerfil de acuerdo con la relacion, en lugar de que muestre el idPerfil 1 muestre el nombrePerfil ADMINISTRADOR lo mismo con el idPerfil 2 muestre EMPLEADO y no el idPerfil

introducir la descripción de la imagen aquí

Este es mi codigo donde mando a llamar los datos en la tabla

<c:forEach var="dato" items="$  {lista}">                                 <tr>                                     <td>$  {dato.idUsuario}</td>                                     <td>$  {dato.claveUsuario}</td>                                     <td>$  {dato.nombre}</td>                                     <td>$  {dato.apellido}</td>                                     <td>$  {dato.email}</td>                                     <td>$  {dato.contrasena}</td>                                     <td>$  {dato.idPerfil}</td>                                     <td>                                         <a href="editar.htm?id=$  {dato.idUsuario}" class="btn btn-warning">Editar</a>                                         <a href="delete.htm?id=$  {dato.idUsuario}" class="btn btn-danger">Eliminar</a>                                     </td>                                 </tr>                             </c:forEach>

faltaría agregar el campo nombrePerfil a mi tabla usuario para que lo muestre Cualquier ayuda se los agradecería

Error en la generación de label JAVA

Tengo un problema al generar el ultimo label de mi tablero de ajedrez ya que lo imprime del tamaño completo de mi panel pero no se a que se deba este error.

La otra problemática que tengo es que en las primeras dos filas de mi tablero me pone los colores exactamente iguales pero en el resto respeta el orden que le di de acuerdo a mis condicionales.

EJEMPLO

introducir la descripción de la imagen aquí

CODIGO

package otraprueba;  import java.awt.Color; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.WindowConstants; import javax.swing.border.Border;  public class OtraPrueba extends JFrame {      JPanel jpanel = (JPanel) this.getContentPane();     JLabel label[] = new JLabel[8];     JLabel tablero[][] = new JLabel[8][8];     Border border = BorderFactory.createLineBorder(Color.black, 1);     int yPosition = 0;      public static void main(String[] args) {         OtraPrueba op = new OtraPrueba();         op.setBounds(0, 0, 500, 500);         op.setVisible(true);         op.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);     }      public OtraPrueba() {         for (int i = 0; i < label.length; i++) {             label[i] = new JLabel();             label[i].setBounds(25 + (50 * i), 25, 30, 30);             label[i].setText("Q" + (i + 1));             label[i].setForeground(Color.red);             label[i].setBorder(border);             label[i].setHorizontalAlignment(SwingConstants.CENTER);             label[i].addMouseMotionListener(new MouseMotionAdapter() {                 @Override                 public void mouseDragged(MouseEvent evt) {                     myDraggingMethod(evt);//reemplaza a los metodos j1 j2 .... j8MouseDragged                 }             });             jpanel.add(label[i], null);         }          //        Inicializa el panel.         for (int i = 0; i < tablero.length; i++) {             for (int j = 0; j < tablero.length; j++) {                 tablero[i][j] = new JLabel();                 tablero[i][j].setBounds(25 + (50 * j), 25 + yPosition, 30, 30);                 tablero[i][j].setBorder(border);                 tablero[i][j].setBackground(Color.red);                  if ((i % 2 == 0) == (j % 2 == 0)) {                     tablero[i][j].setBackground(Color.white);                 } else {                     tablero[i][j].setBackground(Color.black);                 }                  tablero[i][j].setOpaque(true);                 tablero[i][j].setHorizontalAlignment(SwingConstants.CENTER);                 jpanel.add(tablero[i][j], null);             }             yPosition = 50 * i;         }     }      public void myDraggingMethod(MouseEvent evt) {         if (evt.getSource() instanceof JLabel) {             ((JLabel) evt.getSource()).setLocation(newPosition(evt)[0], newPosition(evt)[1]);         }     }      public int[] newPosition(MouseEvent evt) {         int newX, newY;         if ((evt.getXOnScreen() - 50) <= 25) {             newX = 25;         } else if ((evt.getXOnScreen() - 50) <= 75) {             newX = 75;         } else if ((evt.getXOnScreen() - 50) <= 125) {             newX = 125;         } else if ((evt.getXOnScreen() - 50) <= 175) {             newX = 175;         } else if ((evt.getXOnScreen() - 50) <= 225) {             newX = 225;         } else if ((evt.getXOnScreen() - 50) <= 275) {             newX = 275;         } else if ((evt.getXOnScreen() - 50) <= 325) {             newX = 325;         } else if ((evt.getXOnScreen() - 50) <= 375) {             newX = 375;         } else {             newX = 375;         }          if ((evt.getYOnScreen() - 50) <= 25) {             newY = 25;         } else if ((evt.getYOnScreen() - 50) <= 75) {             newY = 75;         } else if ((evt.getYOnScreen() - 50) <= 125) {             newY = 125;         } else if ((evt.getYOnScreen() - 50) <= 175) {             newY = 175;         } else if ((evt.getYOnScreen() - 50) <= 225) {             newY = 225;         } else if ((evt.getYOnScreen() - 50) <= 275) {             newY = 275;         } else if ((evt.getYOnScreen() - 50) <= 325) {             newY = 325;         } else if ((evt.getYOnScreen() - 50) <= 375) {             newY = 375;         } else {             newY = 375;         }          int retorno[] = {newX, newY};          return retorno;     }  }  

What Is The Difference Between String, Stringbuilder, And Stringbuffer In Java?

What is the difference between String, StringBuilder, and StringBuffer in Java?

Website Designing Company in Bangalore | Website Designing Companies in Bangalore | Web Designing Companies in Bangalore | Website Design Companies in Bangalore | Web Design Company in Bangalore | Web…

What Is The Difference Between String, Stringbuilder, And Stringbuffer In Java?