package elte.java2_utikalauz5.security; /******************************************************************************* * Applet: MyLittleApplet * Purpose: The applet is created for the demostration of * security features of the Java 2 platform related to signed applets. Created * by Gábor Pécsy (pici@elte.hu) * Creation date: 14:46PM 2001.01.02 * Last modified: 15:45PM 2006.01.08 */ import java.applet.Applet; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Frame; import java.awt.Panel; import java.awt.TextArea; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.FileNotFoundException; import java.io.IOException; import java.security.Principal; import javax.security.auth.Subject; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.io.*; import com.sun.security.auth.callback.DialogCallbackHandler; /** Jogosultság tesztapplet.

Próbáljuk ki az alábbi appletet különféle fájlokon! Használatához ne feledjük megadni a következő JAAS konfigurációs fájt:
MyLittleApplet {
	elte.java2_utikalauz5.security.SampleLoginModule optional debug=true;

	// A következő két sor közül az adott platformnak megfelelőt kell megtartani:
//  com.sun.security.auth.module.UnixLoginModule required debug=true;
//  com.sun.security.auth.module.NTLoginModule required debug=true;
};
Használatához ne feledjük megadni továbbá a következő biztonsági fájt:
// Ezek a jogosultságok szüksgesek ahhoz, hogy az authentikáció és authorizáció végrehajtható legyen.
grant {
   permission javax.security.auth.AuthPermission "modifyPrincipals";
   permission javax.security.auth.AuthPermission "createLoginContext.MyLittleApplet";
   permission javax.security.auth.AuthPermission "doAsPrivileged";
   permission java.util.PropertyPermission "*", "read";
};

// Itt adunk többletjogosultságokat a testUser felhasználónak.
grant Principal SamplePrincipal "testUser" {
   permission java.io.FilePermission "${/}-", "read";
   permission java.io.FilePermission "${/}tmp${/}-", "read,write";
};
@link.forrásfájl {@docRoot}/../data/security/src MyLittleApplet.java @link.letöltés {@docRoot}/../data/security MyLittleApplet.jar @since Java 2 Útikalauz programozóknak 5.0 */ public class MyLittleApplet extends Applet implements ActionListener { private static final long serialVersionUID = 1L; Panel buttonPanel = null; Button newButton = null; Button loadButton = null; Button saveButton = null; Button clearButton = null; Button quitButton = null; TextArea fileContent = null; TextField fileName = null; Subject subject = null; static final int MAXBUFFSIZE = 1000000; public MyLittleApplet() { super(); this.subject = null; createMyLittleApplet(false); } // MyLittleApplet public MyLittleApplet(Subject subject) { super(); this.subject = subject; createMyLittleApplet(true); } // MyLittleApplet /** * Creates the UI elements of this applet. Button to Quit is added * only when the Applet is executed as an application. * @param needQuit specifies whether a Quit button should be added to * the screen. */ private void createMyLittleApplet(boolean needQuit) { this.buttonPanel = new Panel(); this.newButton = new Button("New"); this.loadButton = new Button("Load"); this.saveButton = new Button("Save"); this.clearButton = new Button("Clear"); this.fileContent = new TextArea("", 10, 80, TextArea.SCROLLBARS_BOTH); this.fileName = new TextField("", 80); this.buttonPanel.add(this.newButton); this.newButton.addActionListener(this); this.buttonPanel.add(this.loadButton); this.loadButton.addActionListener(this); this.buttonPanel.add(this.saveButton); this.saveButton.addActionListener(this); this.saveButton.setEnabled(false); this.buttonPanel.add(this.clearButton); this.clearButton.addActionListener(this); this.clearButton.setEnabled(false); if (needQuit) { this.quitButton = new Button("Quit"); this.buttonPanel.add(this.quitButton); this.quitButton.addActionListener(this); } this.fileContent.setEditable(false); this.fileContent.setText(whoAmI(this.subject)); this.fileName.setEditable(true); this.setLayout(new BorderLayout()); this.add(BorderLayout.NORTH, this.fileName); this.add(BorderLayout.CENTER, this.buttonPanel); this.add(BorderLayout.SOUTH, this.fileContent); this.validate(); } // createMyLittleApplet private void loadFile() { FileHandler inFile = new FileHandler(fileName.getText(), this.subject); try { fileContent.setText(inFile.loadFile(MyLittleApplet.MAXBUFFSIZE)); fileContent.setEditable(true); fileName.setEditable(false); saveButton.setEnabled(true); clearButton.setEnabled(true); loadButton.setEnabled(false); newButton.setEnabled(false); fileContent.requestFocus(); } catch (SecurityException e) { fileContent.setText("Exception thrown: " + e); } catch (FileNotFoundException fnfe) { this.fileContent.setText("File not found: "+ this.fileName.getText()); } catch(IOException ioe) { this.fileContent.setText("Failed to read file. Reason:" + ioe); } catch(Exception e) { this.fileContent.setText("Failure: " + e); } validate(); } // loadFile private void saveFile() throws IOException, FileNotFoundException { FileHandler outFile = new FileHandler(fileName.getText(), this.subject); try { outFile.saveFile(this.fileContent.getText()); fileContent.requestFocus(); } catch (SecurityException e) { fileContent.setText("SecurityException thrown: " + e); } catch (Exception e) { this.fileContent.setText("Failed to write file. Reason: " + e); } validate(); } // saveFile private void clearWindow() { fileName.setText(""); fileName.setEditable(true); fileName.requestFocus(); fileContent.setText(""); fileContent.setEditable(false); saveButton.setEnabled(false); clearButton.setEnabled(false); loadButton.setEnabled(true); newButton.setEnabled(true); validate(); } private void newFile() { if (fileName.getText().length() > 0) { fileContent.setText(""); fileContent.setEditable(true); fileName.setEditable(false); saveButton.setEnabled(true); clearButton.setEnabled(true); loadButton.setEnabled(false); newButton.setEnabled(false); fileContent.requestFocus(); } else { fileContent.setText("Specify a file name first!"); fileName.requestFocus(); } validate(); } // newFile public void actionPerformed(ActionEvent e) { try { if (e.getSource() == loadButton) { loadFile(); } else if (e.getSource() == newButton) { newFile(); } else if (e.getSource() == saveButton) { saveFile(); } else if (e.getSource() == clearButton) { clearWindow(); } else if (e.getSource() == quitButton) { System.exit(0); } } catch (Exception exc) { System.err.print("Unhandled exception:" + exc + "\n"); } } public void init() { } // init public void start() { } // start public void stop() { } // stop public void destroy() { } // destroy /*===================================== Application part ==========================================*/ public static void main(String args[]) { Frame myFrame = new Frame(MyLittleApplet.class.getName() + " application"); Subject subject = login(myFrame); MyLittleApplet application = new MyLittleApplet(subject); myFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); myFrame.add("Center", application); myFrame.pack(); myFrame.setVisible(true); try { application.start(); } catch( SecurityException loginFailed ) { myFrame.setVisible(false); loginFailed.printStackTrace(System.err); System.exit(-1); } } // main /** * Use JAAS to authenticate the user. * @throws LoginException */ private static Subject login(Frame parent) { try { LoginContext lc = new LoginContext("MyLittleApplet", new DialogCallbackHandler(parent)); lc.login(); return lc.getSubject(); } catch (LoginException le) { le.printStackTrace(System.err); } catch (SecurityException se) { se.printStackTrace(System.err); } return null; } private static String whoAmI(Subject subject) { if( null == subject ) { return "*** UNKNOWN ***"; } StringBuffer sb = new StringBuffer(); for( Principal p : subject.getPrincipals()) { sb.append(p.toString()).append("\n"); } return sb.toString(); } /** * This class is used to handle the files for MyLittleApplet. This is the model * for an MVC pattern, where the applet is the view and the controller. * @author pecsy * */ class FileHandler { final String name; final Subject subject; public FileHandler(String name, Subject subject) { this.name = name; this.subject = subject; } @SuppressWarnings("unchecked") private T executeAction(PrivilegedExceptionAction act) throws Exception { if( null == this.subject ) { return act.run(); } else { try { // null is used as the AccessControlContext to make sure that // only the permissions of the subject are taken into account. // We manually convert the result of the call to type T because // JAAS API hasn't been updated to use generics. return (T)Subject.doAsPrivileged(subject,act,null); } catch( PrivilegedActionException pea) { throw pea.getException(); } } } public String loadFile(final int maxLength) throws FileNotFoundException, IOException, Exception { PrivilegedExceptionAction loadFile = new PrivilegedExceptionAction() { public String run() throws IOException, Exception { File inFile = new File(name); FileInputStream fis = null; try { fis = new FileInputStream(inFile); if (fis.available() > maxLength) { throw new Exception("File too long. Size: "+fis.available()); } byte buff[] = new byte[fis.available()]; fis.read(buff); return new String(buff); } finally { if( null!=fis ) fis.close(); } } }; return this.executeAction(loadFile); } public void saveFile(final String text) throws Exception { PrivilegedExceptionAction saveFile = new PrivilegedExceptionAction() { public Object run() throws IOException { File outFile = new File(name); FileOutputStream fos = null; try { if (!outFile.canWrite()) { outFile.createNewFile(); } fos = new FileOutputStream(outFile); if (fos != null) { fos.write(text.getBytes()); } } finally { if( null != fos ) fos.close(); } return null; } }; this.executeAction(saveFile); } } } // End of class MyLittleApplet