426 Introduction, 426 HTML/CSS, 426 Javascript, 435 Chap 8 Terms, 435 Chap 8 Concepts, 426 DOM and JQUERY, 426 HTTP, 426 CGI and PHP, 426 Cookies/Session State, 426 JSON/ReSTful, 426 Databases

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

<text area>

multiline text box to type in

Altering contents of elements

append(c), prepend(c) Inserts content c into each elem of selection -appendTo(e), prependTo(e) Inserts all elems of selection set into elem e

Content type for JSON HTTP resp

application/json

Altering attrib of an elem

attr() (used to get/set indiv attri or many at once -addClass,removeClass,toggleClass (alters class attrib as you would expect

XML

eXtensible Markup Langterm-20uage Addressed syntax abuse/extensibility. Gave rules for tag syntax and nesting. Semantics of tag vocabularies separately specified. Machine-verifiable.

CSS attrib vals

UNIVERSAL support Colors: aqua, black, blue, fuchsia, gray / grey, green, lime, maroon, navy, olive, purple, red, silver, teal, white, yellow WIDE support: 130 more Hex notation #rrggbb rgb function notation rgb(red,gree,blue) where red/green/blue 0-255 or percentatges

More CSS attrib vals

URL url() Lengths and sizes Numval with unit suffix px(default),pt,pc,em,cm,in,mm Percentages Keywords (small,smaller,large,larger)

HTTP mapping

URL path interpreted from a root location on local file storage, corresponding file is named resource. If path is directory, index.html if it exists. Directory listing if allowed.

Primitive Val Types (numbers)

-(Internally) floating point, -Integer literals (leading 0 is base 8, leading 0x is base 16) -Floating pt literals (standard decimal notation, scientific notation with either "e" or "E"; Formally: (+|-)[digits][.digits][(E|e)[(+|-)]digits] -NaN (not a number) and Infinity

Arrays

-0 indexed -literal syntax [e0,e1,..eN] -Missing vals are undefined -Creation by constructor new Array() new Array(arrayLength) new Array(e0,e1,eN) -Expands to largest set index (missing vals undefined) -Indexed with [] -size provided by length property: array.length

HTTP 1.1 v 1.0

-1.1 allows connection to remain open to the server for additional resource requests -1.1 has many more headers (requires "Host" header in requests

Typical use with HTML

-1st HTTP exchanges gets html page, subsequent exchanges get stylesheets, JS, Images, Ads, Media

Distributed or Hybrid Intrusion Detection

-2 problems confront IDS: The tools may not recognize new threats or radical mods of existing threats AND it is difficult to update schemes rapidly enough to deal with quickly spreading attacks. -Hackers have slowed their spread deliberately to avoid detection -Need subtler detection. -An adaptive cooperative network, local nodes use a peer-to-peer gossip protocol to inform other machines of its suspicion, in the form of a probability that the network is under attack. If a machine receives enough of these msgs so that a threshold is broken -each end host and network device (router) is considered a potential sensor and may have sensor software module installed.

Snort Rules: Rule options

-A keyword and arguments. Options separated by ; , Rule option keywords are separated from arguments with : -4 major options catagories -Meta-data (provide info about rule but don't have any affect during detection -Payload (look for data inside the packet payload and can be interrelated). -Non-payload: (Look for non-payload data) -Post-detection: Rule-specific triggers that happen after a rule has matched a packet.

JSON

-AJAX originally was going to respond with XML to: - capture structure, leverage other xml-based standards like Namespaces and Schemas - interoperate with 3rd party srvcs (standards like SOAP; Negotiated and partial interfaces) -For web apps , application developer writes both sides (mitigates need for namespaces/schemas and price of XML overhead not worth it)

More on Document

-API for doc-wide ops/info -URI -Character encoding info

Implementing 1-to-many

-Add attrib on the "many" side which is the unique identifier of the "one" side.

Event Object

-Additional info about event provided in 1st param to event handler (event object) -properties of event object depend on kind of event being handled -jQ extends event object with additional capabilities and normalizes some properties (creates its own version to pass to handler) -originalEvent property will give original event obj generated by underlying DOM or IE event.

Scheme for HIDS cont

-Agent captures each audit record from audit collection system. -A filter applied that retains only those records that are of security interest -These records reformatted into a standardized form referred to as the host audit record (HAR) -A template-driven logic module analyzes the records for bad activity. -Looks for attack pattern signatures -Looks for anomalous behavior of an indiv user based on historical profiel of that user. -When suspicous activity detected, an alert is sent to the central manager, which draws inferences from received data. -central gets LAN data

intrustion detection system (IDS)

a device or software application that monitors a network or systems for malicious activity or policy violations. Any detected activity or violation is typically reported either to an administrator or collected centrally using a security information and event management (SIEM) system.

Display and Visibility

display attr (inline block none) Sets CSS box model asssociated with an elem None hides content entirely visiblitiy attr (hidden visible(default)) Still lays out elem, but doesn't show it where display none vanishes it.

<nav>, <article>,<aside>,<header>,<footer>

div, but intended for a specific purpose.

Lifecycle of cookie

-Server sets (plants) a cookie as part of an HTTP response (Set-cookie header) -Browser stores cookie -When browser makes HTTP requests in future, info in all prev stored cookies are compared with HTTP req for "matches", and info from matched cookies are sent with req as a cookie header

PHP Syntax

-Similar to C -statements end in ; -comments: (Multi /* */ Single // or #) -Loosely typed -Vars start with $ -Spring into existence and dynamically typed

Logical vs. physical design

-So far, logical design -Need to implement this as a specific database

Interface Definition Language (IDL)

-Specifies a DOM -Language-agnostic -Defines basic data types and objects that make up the DOM

Pseudo elems

E:first-line: Applies to text within an elem E that is part of the first line rendered. E:first-letter: Applies to first letter of text within elem E Inconsistent support

Pseudoclasses

E:link Elems of type E that represent hyperlinks that haven't been followed yet (usually applies to <a>) E:visited Same as above, just have been visited E:active Elemes of type E that represent active hyperlinks (mouse pressed, not released) E:hover Elems of type E that currently have the mouse over them E: focus Elems of type E that has keyboard focus E:first-child/nchild are pseudoclasses

Form UI

Each associated with name and val which are encoded into pairs as a parameter for server-side during HTTP request; Needed for AJAX some UI elems for client-side behavior

HTTP as a stateless protocol

Each req/resp independent. No persistent conversation btwn client and server.

Statelessness

Each req/resp is independent. connection torn down after response, but may stay open for more req/replay exchange.

Subclasses of nodes

Element, Attribute, Text

Types of attribute syntax

Empty: name (when value is meaningless) Unquoted: name=value (when attr val is simple string) (no whitespace, quotes,= < >) ex: <input val=yes> Quoted: name="value" or name='value' ex.<input type = 'checkbox'>

CGI Execution Environment

Environ vars used to pass info about context of execution REQUEST_METHOD indicates GET or POST QUERY_STRING has encoded parameters if using GET CONTENT_LENGTH has size of message body if one exists PATH_INFO has extra path information.

PHP data types pt. 2

Escape sequences \n \r \t \\ \$ \" \' -Concat operator .(dot) ["this" . "and . "that" -> "This and That"]' -Can be indexed like an array of chars [$foo = 'My String' $foo[0] -> 'M' -Length: strlen() fn

Event Propagation

Events propagate up DOM tree -All matching handlers on any element in the path up to the root are invoked -Can be stopped using stopPropagation() method of event obj -.data() used to attach/retrieve arbitrary data with an element

Max-Age / Expires

If Max-Age specified: Num of secs after being set when cookie should expire. If Expires specified (date when cookie expires Expired cookies are forgotted by client If not specified, cookie thrown away when browser quits

-Variable setting

If a var name is set (assigned to), the same procedure as in look up occurs. -Matching property name in scope chain set to new value. -If property name never matches, then a property with a matching name is created in the first object in the chain and the value is set.

Specialized security and Event management (SIEM)

Imports and analyzes data from a variety of sources, sensors, and products. -Reduces false positives and speed up process, still detecting attacks

Selection: "class"

In HTML: <elem_name class = "classname" content > In CSS elem_name.classname { STUFF } -Can have more than one class by seperating with space <elem class="one two">

Web based email example

Model (Msgs, contacts, folders) View (List view, msg view, interactions with model) - When new info needed - when existing info updated - handles manipulations of view without interacting with model or controller components (sorting) Controller ( -Retrieving a list of msgs from a particular folder, -retrieving details of a specific msg -Composing/sending a message -Interaction with view -controller provides API to high-level app behavior -Invoked by view components as a resp to user interaction with app -Interaction with modle - Update/create app data/state as a result of a controller action - Not as much in the other direction

anomaly detection

Involves the collection of data relating to the behavior of legit users over a period of time. Current behavior analyzed to determine with high confidence whether this behavior is that of legit user or intruder.

rule-based heuristic identification

Involves use of rules for identifying known penetrations or penetrations that would exploit known weaknesses. Can identify suspicious behavior even when in bounds of established patterns of usage. Specific to the machine and OS. Should analyze attack tools and script from the Internet supplemented with rules by knowledgeable security personnel.

Good News

JS frameworks like jQuery provide way more powerful/convenient interface to the DOM (for both standard and de facto standard ops) unified across browsers -Important to understand that jQuery and other such frameworks op at the level of the DOM

REST in practice

Model data and srvcs exposed as RESTful web interfaces -HTTP methods are the "verbs" (GET, POST, DELETE, PUT) -Mapping of resources/srvcs to CGI URLs are the "nouns" (conventional style for this mapping that is considered "RESTful" -Cross section of method x URL mapped to CRUD operations (CREATE READ UPDATE DELETE)

Altering the DOM

Methods to make new nodes: -createElement -createTextNode -createAttribute Methjods for inserting nodes: -insertBefore -replaceChild -removeChild -appendChild

AJAX MVC pieces

Model (Database) Controller: Split btwn server and client side View: Client-side

MVC Pattern

Model- App state / data beind model objs View (UI to app, async, event-based responses to user directed actions) Controller - App logic / services; Translates interactions to model updates and / or view changes

MVC Apps

Model/View/Controller MODEL is database Controller is Server-side CGI View is Client-side progamming like Javascript

Array methods

Modifying: pop,push,reverse,shift,sort,splice,unshift Non-modyfing: concat, join, slice as of 1.6: indexOf, lastindesOf, filter, forEach, every, map, some as of 1.8: reduce, reduceRight

passive sensor

Monitors a copy of network traffic; the actual traffic does not pass through the device.

Network-based IDS (NIDS)

Monitors network traffic for particular network segments or devices and analyzes network, transport, and application protocols to identify suspicious activity.

network-based IDS (NIDS)

Monitors network traffic for particular network segments or devices and analyzes network, transport, and application protocols to identify suspicious activity.

Host-based IDS (HIDS)

Monitors the characteristics of a single host and the events occurring within that host, such as process identifiers and the syscalls they make, for evidence of bad activity.

host-based IDS

Monitors the characteristics of a single host and the events occurring within that host, wuch as process identifiers and the syscalls they make, for evidence of bad activity.

CGI via HTTP GET

Msg. body empty -Parameters encoded in URL -? in URL indicates start of params -Parameters provided as name / value pairs where = separates name from value

Semantics: <html>

Must be root, should have "lang" attribute ex. <html lang="en">

PHP DateTime

Must set timezone (date_default_timezone_set())

PHP data types

NULL -Boolean TRUE FALSE -Integers (decimal(123), hex(0x123), octal (0123) -Floating pt: (Normal (12.34) or scientific (1.234E1) -Strings (single or dbl quotes) -Var substitution will occur in double quoted strings. -$fruit = 'apples'; -"I like $fruit!" -> "I like apples!" -'I like $fruit!' -> 'I like $fruit!'

Anatomy of cookie

Name(req) Value(req) Domain Path Path Max-Age/ Expires Security flag

Protocol layering

Network protocols are built on top of one another, with a service model associated with each layer -More complicated services built on top of simpler ones

Custom data attr

New to HTML5, custom attrs prefix: "data-" Used to embed app-specific data associated with elem. No restrictions on val. ex: <span data-mascot='Tar Heels'>University of North Carolina</span>

Absolute URL

Protocol and server same as associated with page

Relative URL

Protocol and server same as page; Path formed by appending path fragment to path prefix associated with page up to the last /.

<meta>

Provides meta info about doc. Void elem (no end tag). -Best practice to include <meta> with "charset" attr to indicate char encoding -UTF-8 common for plaintext <meta charset="UTF-8"> -meta "name" and "content" <meta name="author" content="Ketan Mayer-Patel">

Attributes

Put in start tag to add info about a specific elem.

CGI via HTTP POST

Resource name only has path. -Msg body has params -Adv: URL doesn't contain param name and vals, useful if value is long -Disadv: Can't bookmark the URL in a way that includes parm info

jQuery.ajax pt. 2

Return val of $.ajax is a "jqXHR" obj (Represents AJAX request, provides info about the req as well as methods to attach handlers to diff stages of the AJAX lifetime and to diff possible results

Void elems

Some elements have no content. Just a start tag with no end <br>, <hr>, <link>, <img>

SQL

Structured Query Language -Expresses actions to be performed on a relational database. -Standardized for portability -Product specific differences and extensions still exist, but has improved a lot.

<body>

Structured content of page.

Data sources include

System call traces and Audit (log file) records (No additional collection software needed BUT audit records may not contain needed info or may not have it in a good form. Also intruders may manipulate these). -File integrity checksums -Registry access (Windows)

tag v elem

Tag: specific sequence of chars that make up just a start or end tag. Elem: The whole elem including tags and content.

base-rate fallacy

The base rate fallacy, also called base rate neglect or base rate bias, is a formal fallacy. If presented with related base rate information (i.e. generic, general information) and specific information (information pertaining only to a certain case), the mind tends to ignore the former and focus on the latter.

Client

The browser.

Set-Cookie syntax

Set-Cookie: <name>=<value>; Domain=<dvalue>; Path=<pvalue>; Max-Age=<num>; Secure; Version=1 -name/val pair must come first (must be a single token, no spaces, generally alphanum, hypen, and underscore (some other allowed but notably semi-colon not allowed))

Selection: Elem type

Simply use elem name as selector, matches all elems in doc of that type "*" is wildcard that matches any type

Inheritance

Single inheritance model -Declared with extends keyword as in: (class Foo extends Bar { -Because vars are dynamically typed and there is no "casting" operator, effectively, all methods and props declared in subclass with same name with same name as in parent class are overridden and obj refs always refer to their true type. (parent keyword can be used within methods to call methods defined in parent class)

CSS Advantages

Site-wide consistency, bandwidth saving, easier to maintain, separation of concerns.

Object-oriented PHP

PHP obj model bolted on top around ver 3 and then rewritten btwn 4 and 5, so some features odd/ not clean

Anatomy of a URL

PROTOCOL -http:// SERVER -www.cs.unc.edu PORT NUMBER -:80 (attr of tcp connection, 80 is the default and ommitted when default) PATH -/Courses/comp426-f15/index.html (slash separates, interpretation protocol-specific; Identifies resource)

Parts of Snort

Packet decoder: processes each captured packet to identify and isolate protocol headers at the data link, network, transport, and app layers. Efficient; mostly sets pointers so protocol headers can be easily extracted. Detection engine: Does the ID. Analyzes packet based on rules defined for the Snort configuration by the admin. If no rule matches the packet, its discarded. Logger: For each packet that matches a rule, the rule specifies what logging and alerting options are to be taken. When a logger option selected, the logger stores the detected packet in human readable format or in a more compact binary format in a designated log file, which the admin can later analyze. Alerter: For each detected packet, an alert can be sent. The alert option in the matching rule determines what info is included in the event notification. Can be sent to a file, a unix socket, or a database. Can be turned off during testing. Using UNIX socket, alert can be sent to a management machine elsewhere on the network.

Param encoding in CGI via http get

Param names an dvals may contain illegal chars not allowed in URL -Spaces represented by "+" -Other chars encoded using ASCII escape sequence (%## [2 hex digits]) -+,=,&, and ? also need to be encoded otherwise may be confused for their role as reserved URL chars

JavaScript

Programming language of the web, W3C, some browser specific features. Browser executes (includes DOM and Broser API in execution environ) Competitors: Plug-in based proprietary, Flash, Silverlight, Java

Difference btwn original MVC and AJAX MVC

The controller is altered to be client-side and server-side together instead of server-side only.

Mouse Events:

click, dblclick, mousedown, mouseup, mousemove, mouseenter, mouseleave, mouseover,mouseout

<head>

contains <title>, links to stylesheets and client-side JavaScript, and meta info about document (char encoding, search engine hints)

<html>

The root element, which encompasses everything else.

Inline elems

em (emphasis/italics),strong(bold) ,small,cite,abbr (hover for more info),code,sub (subscript),sup(superscript),span

Calling a fn

f(p1,..pn) -If called with too little params, unspec params get undefined -If too many, extra params stored in local variable "arguments" -value types passed by value -Object types passed by reference val -Any expression that makes a fn can be invoked -Variables declared within fn are LOCAL -Variables not declared as local are GLOBAL -If var declared with "var" anywhere in the fn body then any ref to that variable is local regardless of where the declaration or first use occurs.

width and height

for block elems

Define a function

function f1 (p1,p2,..pn){ //body } -No fn within fn -f1 is function, p1-n are parameter names Assign to varname var f1 = function (p1..pn){ //body; }; -Creates new fn obj anonymously -needs to be assigned to var to keep it

Defining fns

function name($p1,$p2){ //Fn body } -Vars used within a fn are always local unless declared as global as in : gloal $var_name -Params passed in by val for non-object data types (strings and nums) -Can force pass by reference if param is preceded by "&" when fn is defined -Arrays and objs always passed by ref val Anon form $v = function ($p1, $p2){ fn body }

&lt; and &rt; and &amp;

makes the < and > and & in html doc ignoring their usual functions in the html

creating instances

new ClassName() -Class name can be provided by a string ($cname = "ClassName"; new $cname() -Simple property initialization can be done directly in property delcaration, but if you need to do more, can provide constructor (define_construct())

Function constructor

new Function ([p1..pn],body); -Functions are objects, so use the Function constructor. -First arg is an array of params as strings. -body if fn body as a string -no used much/ costly

Primitive val types (cont'd)

null (no val) case sensitive undefined (declared, not set null or otherwise) null==undefined is true null===undefined is false

Mouse move props

offset() (returns obj with elem's position into offset from document origin) -width(), height()

<form>

parent elem within which form input elems are placed

Traverse jQ

parent(), parents() (alters selection set to be ancestors of current selection set in tree either one level or all the way to root element; accepts optional CSS selector to use as a filter) -children(),find() (alters select set to be descendants; accepts optional CSS selector to use as filter) -prev(), next() (prv and nxt sibs with possible filter -filter() (filters current selection with current filter.

Number/string conversion

parseInt(), parseFloat() Returns NaN if can't be parsed as either int or float -Automatic conv from string to num when used with numerical operators (+ is addition and concat and will force numbers to strings.)

setInterval,clearInterval

setInterval(f, delay) -Executes fn obj f ever delay milliseconds. Return value is an "interval id" that can be used with clearInterval to stop. clearInterval(id) Given interval id returned by setInterval, will stop periodic execution.

More mouse click props

shiftKey, ctrlKey, altKey, metaKey (indicates true/false if keys depressed at time of event) -target (where event occurred (for directly bound event handler, same as "this") -currentTarget (where event handler was registered (for directly bound event handler same as "this")

<script> tag

src attributes provides URL for JavaScript code. -type="text/javascript" -Can provide code as content of script tag, but best practice to avoid (sep of concerns; like why we don't put CSS into HTML) -Evaluated immediately (usually defines global fns, prototypes, top-level data structures, etc.; Usually we'll want to delay execution of main entry to client-side code until after DOM made)

Element syntax

start tag: <elem_name [attribs]> content (elems and text) end tag: </elem_name> (nothing else)

Mouse click properties

type (identifies event type) -clientX, clientY, screenX, screenY (mouse position info, client (browser window) and screen (whole screen) -timeStamp (time when event occurs measured in millis since jan 1 1970 (jQuery-specific) -button(W3C) (0=left, 1=middle, 2=right) -which (IE) (1=left,2=middle, 3=right)

Header section

-provides additional info abou requests

phpinfo()

Gens a webpage with config and superglobal info

v1, v2, v3

Look at workflowy

RESOURCE

Path portion of URL, though entire URL is legal

<title>

Titles browser window.

IP Service Model

Unreliable, best-effort delivery of messages between hosts.

Creating new elem

$(html) [Same main jQ fn used for selecting, but if arg "looks' like HTML, parses and creates new elems to match and returns jQ selection of those elements. -Typical form : $(<element></element>") use result to modify/change as necessary

Selecting elems in jQ

$(selector) -If selector "looks" like a CSS selector, then results in a jQ obj wrapped around the collection of elements from the DOM that match the selector -The .length property of the jQ obj will tell you how many you got. -You can retrieve DOM elem by indexing the jQ obj like an array Terminology: jQuery set, jQuery selection

honeypot placement

(1) Outside the external firewall, which is useful for tracking attempts to connect to unused IP addresses within scope of the network. No extra risk for internal network. no danger of compromised system behind firewall. Eases management burden by reducing alerts issued by fire-wall and internal IDS sensors (2)DMZ, the network of externally available serveric3es such as Web and mail. A typical DMZ is not fully accessible, and firewall typically blocks traffic to DMZ. (3) Fully internal. Can catch internal attacks/ misconfigged firewall forwarding impermissible traffic from Internet to network. Disadvantages are that an internally compromised system attack from the inside. Further traffic to attacker not blocked because its thought to be for the honeypot only. Also, firewall must adjust filtering to allow traffic to honeypot.

Back-end frameworks

(integrated server-side solution that allows template-based responses, database support, state management) Most use CGI to get onto web server.

PHP arrays

-All are associative, indexed by keys -Keys can be anything -Array literal forms: - Empty array: $a = array(); -Implicit numeric key form: $a = array('First', 'Second', 'Third'); -$a[0] -> 'First' ; $a[1] -> 'Second; $a[2] -> 'Third' -Explicit key/val form: -$a = array('one' => 'First', 'two' => 'Second, 'three' => 'Third') -$a['one']-> 'First' and so on -Adding to end of array: $a[] = 'Next' (end defined as highest numeric key (or 0 if no numeric keys exist) -is_array() tests for arrayness (is_array($a) -> true

Unique identifiers

-Almost always, the best way to create a unique identifier is to create an artificial one (book ID, author ID) assigned by the database itself, with no inherent semantics)

Extra Path Info

-Another way to pass info to script -Anything btwn end of CGI script name as recognized by web server and beginning of params is "extra path info" -Available through Path_INFO -Server translates this extra path info relative to web server's path mapping rules (found in PATH_TRANSLATED)

NIDS ID techniques: Signature Detection

-App layer recon and attacks: Looks for attack patterns that have been identified as targeting these protocols (like buffer overflows, pw guessing, malware transmission) -Transport layer recon and attacks: analyze TCP and UDP traffic and perhaps other transport layer protocols (Like unusual packet fragmentation, scans for vulnerable ports, SYN floods) -Network layer recon and attacks: analyze IPv4, IPv6, ICMP, and IGMP (like spoofed IP addresses and illegal IP header vals) -Unexpected app services: attempts to determine if the activity on a transport connection is consistent with the expected app protocol. (like host running unauth attack srvc) -Policy Violations: Use of inappropriate Web sites and use of forbidden app protocols.

Autocomplete encouraged a move to using AJAX to move controller functionality to the client

-Apps feel smoother and more interactive, latency hidden, avoiding page load prevents "flashing" effect and avoids cost of reconstructing DOM from scratch -Interface can be animated (can also hide latency)

Roy Fielding dissertation (2000)

-Argues for a uniform way of addressing controller services and model data in distributed apps with an MVC architecture -Limit number of "verbs" to well-defined set -Uniformly address "nouns" (stateless access, idempotent actions)

Google makes autocomplete with AJAX

-As you type, send what you have so far as a param to a cgi script on a server using XHR -Resp a list of possible completions (server-side doesn't need to be built into view and is done on demand) -When resp is received on client side, JS processes list to integrate with UI (dynamic dropdown menu or something) -Latency of req is hidden by "human" timescale of pausing while typing -big success

Operators

-Assignment:= -Comparison:==,!=,>,>=,<,<= (works with strings but order is case sensitive) -Arithmetic: (+ - * / %)(+overloaded as string concat) Unary(-- ++) Bitwise(& | ^ ~ << >> >>> (zero fill right shift) Boolean(&&, ||, !) -Ternary conditional: ? (look up)

RESTful URL mapping convention

-CGI-based URL identifies a controller (a .php script) -Extra path info idens resource (check workflowy for demo)

Variables in JS

-Case sensitive -Start with letter, underscore, or $ -Can contain letters, digits, underscore, or $ -Assign with = -Typeless -Spring into existence when assigned -Declared with var keyword (can forgo if global but BAD STYLE) -test equality with == (=== in special cases)

JSON cont

-Client-side known to be JS -Idea is that AJAX resp should be a serialized JS obj, then client-side can just deserialize the data directly into obj form and use it -JSON is that serialization -Direct sytax: {"key", value} -Val can be serialized sub-obj, number, string, or boolean -Server=side framework generally provides routines to encode/decode (In PHP: json_encode and json_decode)

Intra-session state

-Could be maintained at client, goes away when interaction with web apps ends. May not be appropriate with proprietary or sensitive info.

When a fn obj invoked...

-Current scope chain is squirreled away ("pushed on the call stack") -The scope chain that was saved as part of the fn object when it was created is restored. -A new obj is created and appended to the scope chain (the "local scope object" -Any fn parameter names are created as properties of the local scope object and set to the corresponding values passed to the function.

charCode

-Defined for keyPress events -Meaning of 'which' property changes based on event type -Can turn charCode into string with String.fromCharCode() [non printables return ""]

NIDS ID Techniques: Anomaly Detection

-Denial of Service (DOS): Anomaly detection well suited to take these out. -Scanning:A scanning attack is when an attacker probes a target network or system by sending different kinds of packets. Using resps received from target, attacker can learn many of the system's characteristics and vulnerabilities (identifies targets). Scannign is detected by atypical flow patterns at the app layer, transport layer, and network layer -Worms: Detected through abnormally high bandwidth use, unusual communications between hosts that don't typically do so, and unusual port use.

Concerns

-Difficult to alter a doc using the DOM as specified. -innerHTML were added, but even that was not enough -DOM trees build in by diff browsers for same content may not be the same (HTML5 addressed this; whitespace a problem) -Different JS implementations have quirks (event handling and how DOM standards implemented)(IE was bad; no DOM event standard compliance.) -Many de facto standard ops not actually in DOM standard (XMLHttpRequest)

Honeypots

-Divert an attacker from critical resources -collect info about attacker -Encourage attacker to stay on system long enough for response. -Filled with fabricated info.

Cookie match occurs if

-Domain matches IP address, full server name, or suffix of domain name -Path is a prefix of URL to be requested -If secure flag was set originally, then only sent if connection is secure (https vs http)

Domain rules

-Must be a suffix of the host setting the cookie -Must contain an embedded "." -Must match full server name, be the IP addr of server, or start with a "." -Must "domain match" the server it comes from (can't set a cookie from another server -If not set, then defaults to name of server. (examples on workflowy)

Snort Rules: Header elements

-Each consists of a fixed header and zero or more options. -Action: The rule action tells Snort what to do when it finds a packet that matches a rule. -Protocol: Snort proceeds in the analysis if the packet protocol matches this field (TCP, UDP, ICMP, IP) -Source IP address (specific, any, from list, any not in list) -Source Port (same specifications as source ip) -Direction: Unidirectional (->) or bidirectional (<->). Bidirectional tells Snort to consider the address/port pairs in the rule as either source followed by destination or destination followed by source. (monitor both sides of convo) -Destination IP address -Destination port

Relational databases (more)

-Each entity associated with a table -Attribs are columns of the table -Each attrib given data type -Unique identifiers are "primary keys" -Relationships are embodied as "foreign keys" (an attrib whose val is the unique identifier in another table.

Lightweight IDS

-Easily deployed on nodes of a network -Efficient operation that uses small amount of memory and processor time. -Easily configged by sys admins who need to impl a specific security solution in a short amnt of time.

Basic HTTP exchange

-Establish connection (TCP's job; needs to know hostname and portnum) -Client sends a request (who this?) -Server responds -Might repeat (if using HTTP 1.1; 1.0 only lets one request/resp per connection

Event-based programming overview

-Events are associated with elems of the doc when user interacts with it (clicks/mouse entry/exit/ mouse movement) -Event handlers are fns designed to deal with an event (called when event occurs; Info about the event encapsulated into an "event object" [Passes as a parm to the event handler; provides additional info about event] ) -Async programming (Don't know when events going to occur or what order; the point of client-side programming)

Evolution of SSP pt2.

-Evolved from page gen to interface gen as web apps developed. -Increasingly less used for gen HTML docs and twoard back-end support for AJAX-based web apps (no more full HTML pages) -HTML snippets genned and/or serialized JS objs that client-side dynamically incorporates into DOM -Known as "web services" model

More on AJAX

-Facility for making an async HTTP req without reloading a new DOM. XHR obj is provided by browser to access this functionality. Details of XHR obj differ by browser (jQ normalizes them)

Full URL

-Full urls includes protocol://server/path/to/resource

URL Encoding cont'd

-General Unicode not allowed but most browsers will substitute appropriate Unicode char if it encounters a sequence of escaped values in a URL. -When you have a choice in URL, then you can avoid using anything complicated -Internationalization always important (ongoing work to support Unicode in all Internet names) -When URL includes info from use as gen input, encoding important.

BIG CHECKLIST

-HTML -CSS -Javascipt -The DOM -jQuery -Event-based programming -HTTP -CGI -PHP -Cookies -MVC -RESTful -JSON

DOM in Javascript

-IDL abstraction specified in the DOM has to be implemented within a language -Bindings exist for all kinds of languages -In JS, the global doc obj is the implementation of the DOM document root (Methods/props expressed in IDL all implemented as methods/props of corresponding JS objs -HTMLElement is the object "type" that implements the element interface (added additional JS-specific functionality (not defined by DOM stds and can be browser specific)) -NodeList types can be indexed with Array-like syntax.

Intrusion Detection Exchange Format standards

-IDME Requirements: defines reqs for IDME Format (IDMEF). Specifies reqs for a comm protocol using IDMEF -The IDMEF: describes a data model to represent info exported by the IDSs and explains the rationale for using this model The Intrusion Definition Exchange Protocol: Describes IDXP, an app-level protocol for exchanging data between ID entities. Supports mutual-auth't, integrity, and conf. over a connection-oriented protocol.

Designing a DB

-Identify entities -Identify attributes of those entities

Principles of Intrusion Detection

-If an intrusion is detected quickly, the intruder can be identified and ejected before damage done. The less time to catch, the less damage. -An effective IDS can serve as a deterrent, thus acting to prevent intrusion attempts -Intrusion detection enables the collection of info about intrusion techniques that can be used to strengthen intrusion prevention measures

Keyboard event data

-In order for an elem to receive keyboard events, must have "focus" (must be in "taborder" -some elems in taborder by default (text inputs, text areas, buttons, etc.) Otherwise, you must provide a val for "taborder" -Event obj for keyboard events have key info instead of position info

NIDS sensor deployemnt cont'd

-May place NIDS sensor between external firewall and Internet/WAN to monitor unfiltered traffic. Advantages include: -Documents num/types of attacks originating on the Internet that targets network -high processing burden though. -May place on major backbone networks, which: -Monitors large amount of a network's traffic, thus increasing possibility of spotting attacks. - Detects unauthorized activity bu authorized users within the org's security perimeter (internal and exteral attacks) -May place a firewall and NIDS sensor to provide additional security to network facilities / critical subsystems, such as personnel and financial networks, which can: - Detect attacks targeting critical resources and systems -Allow focusing of limited resources to the network assets considered of greatest value.

Web apps as MVC

-Model is server-side( typically involves a database) -View(UI and interactivity is client-side (JS)) -Controller is (see next)

Distributed HIDS

-More effective to coordinate hosts for defense -may need to deal with diff sensor data formats and diff systems may use different sensors and approaches to gathering data. -1 or more nodes in the network will serve as collection and analysis pts for the data from the systems on the network. -Raw sensor data or summary data must be distributed across network, SO they must have integrity/ confidentiality -Can be centralized (single point of failure) or decentralized (must coordinate) -Independent of operating system/system auditing implementation.

Path rules

-Must be prefix of URL requested -If not set, defaults to path of URL up to last "/" -Example on workflowy

NIDS sensor deployment

-Need lots of sensors to make a comprehensive NIDS strategy -A common location for a NIDS sensor is just inside the external firewall. This means it: -Sees attacks, originating from outside world, that penetrate the network's perimeter defenses (external firewll) -Highlight problems with the network firewall policy/performance -Sees attacks that might target the Web or ftp server -Even If incoming attack not recognized, the IDS can sometimes recognize the outgoing traffic that results from the compromised server.

-Model/View interactions

-No direct path usually -mediated thru a controller component, which is probably the best way (provides auth't and auth'r)

Navigating DOM

-Node level properties/method for traversal: -parentNode -childNode -firstChild -lastChild -Search for elems by type.

jQuery resolutions of Microsoft issues

-Normalizes everything -Other JS frameworks do same things (normalizing event handling was motivation for JS frameworks)

More on Floats

-Not accounted for in parent's height -overflow attrib controls what happens when content exceeds height (visible, hidden, scroll, auto(works well only if height specified)) -block elem boxes extend underneath floats -clear attrib will push a block past any floats (left right both none(def)

Document Object Model (DOM)

-Object-based API for a document within the browser (standardized by w3c, we focus on DOM Core, Events, HTML)

MySQL

-Open-source, great for small to mid-sized orgs, fast, efficient, cheap, doesn't support full SQL but a good portion of it.

Relational Database

-Organized into tables -Each tables captures info about a different entity (coulmns are fields of info (attribs)) -Each row is one istance ( a specific example of the entity)

Evolution of server-side programming.

-Original serv-side mapped paths to files -Need dynamic web page gen -CGI bridged server to generating process ( a high level process to process bridge) -HTTP remained mostly the same (some new headers and conventions to support cgi but not much)

MVC - Where's the controller -

-Originally was server-side, provided by CGI, and view/controller interactions were expressed as URLs to CGI process via HTTP as a new page load -More modern web apps are split btwn client and server side (most logic on client, some on server as API to model data; security may demand some controller functionality to be put on server side even though it couldn've been on client side -View/Controller interactions expressed as URLS mapped to RESTful interfaces - Access via AJAX (no new page load, structured representation of response (XML,JSON,domain/app specific) -Controller/Model Interactions (PHP database facilities [fairly extensive and easy to use])

Drawbacks to jQ

-Overloads a lot -Same method will do vastly different things depending on number and value of arguments -Difficult to know what's going on when somebody else used a weird command.

closures in php

-PHP does have a concept of closures, but it isn't as strong as JS, PHP not usually async, so rare.

CGI big ideas

-Programming language independent -Server identifies program from URL -Rules for mapping URL's to program names and how to start program are server-specific -Implemented at the OS level (this is why comm btwn server and CGI program must be done through stdin/stdout and using environ vars)

Requirements of an IDS

-Run continually with minimal human supervision -Be fault tolerant in the sense that it must be able to recover from crashes and reinitializations -Resist subversion. The IDS must be able to monitor itself and detect if it has been modified by an attacker -Impose a minimal overhead on the system where it is running -Be able to be configured according to the security policies of the system that is being monitored -Be able to adapt to changes in system and user behavior over time. -Be able to scale to monitor a large number of hosts. -Provide graceful degradation of service in the sense that if some components of the IDS stop working for any reason, the rest of them should be affected as little as possible. -Allow dynamic reconfiguration; that is, the ability to reconfigure the IDS without having to restart it.

Debugging PHP

-Runs on server, so tricky -Inspect server log for errors -DIrect PHP to display runtime errors with two lines at beginning: error_reporting(E_ALL); ini_set('display_errors', 1); -Just runtime errors not parsing errors

IDME process

-Sensor mointors data sources -Sensor tells analyzer as an event, which characterizes an activity within a given period of time. -If of interest, analyzer sends alert to manager with info about unusual activity and specifics of occurence. -manager tells operator -response given automatically or by human operator.

CGI Server Requirements

-Server must be configured to allow CGI -Config may include restrictions (where programs can be, who can make them, files names) -Server config is specific to server software and specific server-side CGI framework being used.

3 events for distributed IDS

-Summary events: Events from various sources collected by intermediate collection points such as firewalls, IDSs, or servers that serve a specific segment of the enterprise network. Summarized for delivery to central policy system. -DDI (Distributed detection and inference) events: Alerts that are genned when the gossip traffic enables a platform to conclude that an attack is underway. -PEP (Policy Enforcement Points) events: Reside on tursted, self-defending platforms and intelligent IDSs. These systems correlate distributed info, local decisions, and indiv. device actions to detect intrusions that may not be evident at the host level.

Intruder behavior steps

-Target Acquisition and Info Gathering -Initial Access (with malware/weak pw guess/network vuln -Privilege escalation -Info Gather or System Exploitation -Maintaining Access -Covering Tracks

Fn invoked pt. 2

-The local scope obj is given an "arguments" property which is set to an array of all the parameters passed. -The fn body is scanned for any variable declarations and for each variable declared, a corresponding property is created in the local scope object. (how locally declared vars effectively mask globals with same name and explains hoisting). -fn body executed -When done, current scope chain discarded (but objects in chain exist if referenced elsewhere) AND original scop chain restored ("popped off call stack")

Fns can be result of a fn

-This creates "closure" -When a fn obj is made, all vars "in scope" are captured in a closure. -When fn is invoked, closure created when fn was defined is restored -This implies that if a fn was created in a fn, all of the local vars in effect at the time are still available (even if original fn finished) -Each time a fn is called, a new set of local vars is created just for that call. This makes recursion work.

URL Encoding

-URL charset constrainged to Alphanumeric, $-_.+!*'():;?@&/ -$,&,+,=,comma,/,:,;,?,@ reserved only for their purpose. -All others chars must be encoded -Encoding: %XX where X is a hex digit providing ASCII val of char (HTML 4 lets it include Unicode from ISO-Latin up to %FF

Anomaly HIDS

-Use system call traces to collect data -System calls determine if a process is normal or anomalous. -Call traces analyzed by a suitable decision engine (STIDE algo compares training data of syscalls to the current ones to get a mismatch ratio) -Intruder detection 95-99%, FP less than 5% -Gathering info classifying data puts moderate load on the system; Training phase takes a while.

How cookies get used

-Used as index to server-side state for CGI-based responses -Want to be able to save/restore state when handling future CGI requests that are part of same web app. (-web app back end looks for cookie -If it finds cookie, cookie val serves as some sort of key for restoring state info associated with this user -If it doesn't find it, creates sessions storage and sets key to the storage as a cookie in response) -PHP does this for you (-session_start() must be executed before genning any output (and that means even a single newline or space) -$_SESSION (anything put here will be restored)

Reasons for state needed

-User-based context -Preferences -Login status -Shopping carts -Staged interactions

RESTful interfaces

-Using AJAX to refactor the MVC model wrt where controller functionality is, client/server communication now represents controller/model interactions instead of view/controller interactions.

jQ Event Delegation

-We have a number of elems that need same behavior -If total num of elems is large or dynamic (new elems come and go), then setting up handlers is tedious -jQ event delegation takes adv of event bubbling to establish an event handler at some ancestor elem that is automatically attached to descendants that match some selector criterion (even if added to the DOM in future).

To get state from HTTP:

-We need a "state mangement facility" -This is "cookies" (from netscape in 94/95 -Implemented using HTTP headers -At first transparent to use (Couldn't disable)

Variable lookup

-When a var name is referenced, JS looks at the last object in scope chain (most recent) -If this obj has right property, is retreived. Otherwise, var name resolved against the next (moving up) obj in the chain. If never matches, "undefined variable" error.

More meta names

-application-name -author -description -generator -keywords (comma-sep list)

Trick#1: Instance specific properties/methods

-can override prototype properties/methods on an instance-specific basis. -Can use "delete" to clear instance specific property/method in order to restore prototype-based val.

Passive sensors

-connect to a transmission medium by a direct physical tap. -tap provides sensor with a copy of all network traffic carried by medium. -Has no IP, so uses a second network interface card)

documentElement property

-element node that reps the elem that encompasses all other elems and content in the doc (i.e. <html>) -Mostly, we treat the DOM tree as a tree of elems, but "technically", the DOM tree is a tree of nodes with some subset representing elements. -Text nodes intermingled with elem nodes to represent text. -Attribute nodes not in tree, but associated with elems

Resolving M-to-M

-hard, because foreign key attrib which is supposed to implement the relationship requires multiple vals, breaking 1NF -Use JUNCTION entities, which are abstract entities that provide a level of indirection for a many-to-many relationship.

PHP techniques needed to gen JSON resp

-header() Inserts HTTP header into reply, and also used to signal status codes other than "200"; Must occur before ANY output (either due to print() or because of literal mode. -Using header() to set reply status line: If first call to header() looks like an HTTP reply status line, then will be used instead of default "200 OK" -using header() to set content-type: "Content-type" header allows you to specify type of HTTP reply explicitly (otherwise text/html assumed) -using header to redirect(): "Location" header allows you to specify redirection. If this is set, automatically sets reply status as well to approx. 3xx code

Setting cookies for reply

-header() in PHP allows you to add a header to the genned HTTP reply (must come before ANY output) -header("Set-Cookie: ...") -Helper fn: (setcookie(name,value,expire, path, domain, secure)

jQ Event Delegation cont'd.

-on (events, selector, data, handler) [set data to null if n/a) -Event will fire for any descendants of elems that match selector -By specifying selector, jQ recognizes this ues of delegation and sets "this" keyword to be elem where event actually occurred. -descendant that matched the selector -makes it so you can write handler as if it were directly bound to the selected descendent and not to the ancestor where you actually registered it. -the ancestor where handler is actually registered available via event obj as delegate Target Property)

METHOD

-one of a well-defined set of operations -GET, POST, PUT, DELETE, OPTIONS, HEAD, TRACE, CONNECT -Usually POST or GET -HEAD sometimes used to get info about resource without actually getting it

Even more on Floats

-position attribute (relative absolute fixed static (def)) (top bottom left right) specifies box corners -Hard to achieve equal height column layouts

Cookie Matching

-servers DON"T retrieve cookies -Servers RECEIVE cookies that browsers send that were originally planted by the server (Set-cookie header only exists in HTTP responses, stored on disk by browser) -Info comes back in future HTTP requests -Every stored cookie considered for "matching"

Request Line

-single line -METHOD RESOURCE VERSION

Iterating over elems in jQ selection

.each(f) -Accepts fn obj f as arg (callback gets index of each item and the elem itself as parameters)(defining f as f(i,e) will capture index into i, and elem into e) -Callback is also executed in the "context" of the element (or, the "this" keyword will be set to the elem as if f were a method of each element -Works for normal arrays also (elem in this case is just whatever is in the array) [JS 1.6 has "forEach" in arrays, so not needed]

Direct binding example

.on(events, handler) -events is a space-sep list of event names =handler is a fn obj that is called when event occurs, and is executed when any event in list occurs for any element in jQ selection

Functions

1st class object data type FUNCTIONS ARE OBJECTS They can be: -assigned to vars, passed to a fn as parameter, returned from fns as a result, have properties set, and be manipulated in other ways.

Error handler

3 params -jqXHR (jqxhr obj) -textStatus (status text) -errorThrown (String describing why req failed (timeout, error, abort, parseerror)

Success handler

3 params: -data (data returned by server formatted according to dataType from above; for JSON, data is the deserialized obj) -textStatus (string describing status of resp -jqXHR (jQ XHR obj associated with req)

HTML 5 v 4

4 uses self-closing tag syntax for void and empty (<br/>). HTML5 accepts but doesn't recommend it. 5 can infer and identify optional and required tags.

Comments

<!-- STUFF -->

DOCTYPE

<!DOCTYPE html> for HTML5. Indicates that doc conforms to rules and semantics of HTML5

New to HTML

<audio> and <video> embeds, webm support Canvas <canvas>

Headers

<h1>, <h2> etc.

Text block elems

<p> (paragraph), <pre> (The <pre> tag defines preformatted text.), <blockquote>, <br>(line break)

<table> cont'd

<td> inside <tr> with elements of <tbody> Column span and rowspan specified with colspan and rowspan If <table> content a sequence of <tr> then <tbody> inferred.

Lists

<ul>,<ol> Unordered and ordered lists <li> specifies items as content <dl> Definition list <dt> or <dd> provide term and definition -Sublists nested possible

Database

A collection of structured info organized for a specific purpose.

honeypot

A decoy system designed to lure a potential attacker away from critical systems.

Protocol

A formal set of rules for communication btwn 2 processes (in http its browser and server) Who talks first? What can they say? How do they say it?

Rise of Web Apps

A move from documents to apps on the web -CSS: layout control -Javascript: Interactivity -Server-side programming:application state and control. Ex. Email, online banking, Workflowy

Normalization

A process through which a database design is cleaned up. -Well-defined set of "normal forms" which are the incremental result of this process -Not all databases equal -Experience and research has shown that certain structures and relationships are easier to maintain and process than others

security intrustion

A security event, or a combo of multiple security events that constitutes a security incident in which an intruder gains, or attempts to gain access to a system without have auth'r to do so.

intrustion detection

A security service that monitors and analyzes system events for the purpose of finding, and providing real-time or near real-time warning of, attempts to access system resources in an unauth'r manner.

jQuery

A single javascript file. -Almost all jQuery functoinality accessed through a "jQuery object" -Obj created with jQuery() (used so commonly can be make with "$") -A jQ obj usually represents a collection of DOM elements (but you can "wrap" a jQ obj around lots of things) -Most jQ obj methods operate on all of the DOM elems in the collection (same treatment applied to each elem) -Some jQ obj methods operate only on the first DOM elem in the collection. -Almost all jQ obj methods return itself or a new jQuery ob wrapped around a different or modified set of elems as the result of the method. (lets you chain jQ methods together in order to apply a succession of ops on a set of DOM elems.

Client-side Programming

Addresses a lack of dynamism and interactivity in web pages.

Server-side Programming

Addresses issues of mapping URL path to files (dynamic/custom/input dependent/rarely accessed content)

jQuery.ajax

Also $.ajax -$.ajax(url, settings) url ( url to be requested) settings (obj with props configuring the req) Lots of options but most common are -type(http method to use (GET or POST) -dataType( Expected datatype of resource, inferred if not stated (xml, json, script. html) -success (called if successful) -error (called if request not successful) -data (An obj whose props will be converted to HTTP param name/val pairs, encoded properly and appended to GET reqs ( or sent in body of POST reqs)

API

An application program interface (API) is a set of routines, protocols, and tools for building software applications. Basically, an API specifies how software components should interact

Semantics: <head>

Required to be first in <html> Typically contains title, one or more <meta> and <link> tags

Fns as methods

An obj property that happens to be a fn obj will act as a method. -Within fn, the "this" keyword will be a ref to the object thru which the fn was called -can use the same fn object as the property of two diff objects and "this" will be set to whichever object was used to call the method -"this" keyword always available in a fn, even if fn not acting as a method of an object.

Analyzers

Analyzers receive inp from one or more sensors or from other analyzers. Determines if an intrusion has occured. Output is an indication that an intrusion has occured. May provide guidance on course of action as a result of intrusion. Inputs stored for future analysis or review in a database.

Server-side tech

Angular, Node.js, Ruby on Rails, PHP, ASP.Net, Java servlets, Cold Fusion, Backend frameworks

Hacker Skill Levels

Apprentice, Journeyman, Master

PHP Operators

Arithmetic: + - * / % ++ -- Assignment: = += -= *= /= .= %= Comparison: == != > < >= <= === !== Logical: && || ! -Conditional: if and switch statements -Looping constructs (for, while, for each)

Basic style attribs

Background, text, font, list, table

Machine learning methods that were tried

Bayesian networks: encode probabilistic relationships among observed metrics. -Markov models: Dev a model with sets of states, some possibly hidden, interconnected by transition probabilities. -Neural networks: simulate human brain operation with neurons and synapse between them that classify observed data. -Fuzzy logic: Uses fuzzy set theory where reasoning is approximate, and accommodates uncertainty. -Genetic algos: Uses techniques inspired by evolutionary biology, including inheritance, mutation, selection, and recombination, to dev classification rules. -Clustering and outlier detection: Group the observed data into clusters based on some similarity or distance measure, and then identify subsequent data as either belonging to a custer or as an outlier.

Primitive val types (booleans and strings)

Booleans (true/false (0 false/ non-zero true) ("" is false/ non-empty is true) Strings -' or " for quoting -std escape chars (\n , \' ,\", \\, \t, \r -unicode escape seq (\uXXXX with X = hexdigit) -Act like arrays for character access (no char datatype, returns 1 letter string) -Length property (hello length is 5) -String comparison with == -String concatenation with + -string methods (check chrome bookmarks) -Strings are immutable (can't set indiv chars by indexing like an array. String ops create new strings, String literals automatically interned and boxed/unboxed as objects as necessary)

Default event processing

Browser might have build-in behavior associated with an event -Pressing submit button on a form will attempt to load new URL made from form target attribute, maybe combined with form data as params -Pressing backspace will go to last URL in history -preventDefault() method of event object will prevent any default event processing

Cookies are stored and managed...

Browser-specific -IE puts in "Temp Internet Files", each cookie a file -Firefox stores in user-specific profile file -Safari put in ~/Library/Cookies/Cookies.plist

Prototype property of fn objects

By default, val of prototype property is an empty object. -When you use the . operator to deref a property of an object it first looks to see if the object has that property (If so, no problem, if not, prototype obj associated with constructing fn is tested to see if it has desired property(if so, used; this keyword remains set to original obj)) -The prototype mechanism is used to provide properties and methods that will be shared across all obj of the same "type"

Selectors

By elem type, "class" HTML attrib val, "id" HTML attrib, by arbitrary HTML attrib val, and Hierarchical relationships, Pseudoclasses, Pseudoelements, combining

Trick #2

Can ad new properties/methods to obj post facto -Derefing happens dynamically at runtime, so changes to prototype obj instantly go into effect for existing obj as well (known as "open" classes "static" methods and properties -Properties/methods of the constructing fn obj mimic what we think of as "static" methods and properties in more traditional object-oriented languages like Java and C++

Journeyman

Can modify/extend toolkits to use newly discovered/bought vulnerabilities or to focus on a specific group. Harder to deflect.

CSS

Cascading Stylesheet CSS 2/3 widespread. Render controls fonts borders, layout and media-specific context (devices/readers). Usually linked to HTML files. Multiple html files can use one sheet.

CSS

Cascading style sheets. Presentation instructions for HTML, separate content from presentation. Ideal that HTML provides structure as plainly as possible, and CSS describes appearance.

HTTP Exchange

Client sends request, server replies, connection closed.

Objects

Collection of named properties {p1: v1, p2: v2) and so on. -Properties dereferenced with the . operator

Distributed or hyprid IDS

Combines info from a number of sensors, often both host and network-based, in a central analyzer that is able to better identify and respond to intrusion activity.

CGI

Common Gateway Interface -Instead of a path file, URL identifies a program to be executed -Server initiates execution of program to gen HTTP reply -Params passed to the program through the HTTP request (how depends on if request is GET or POST)

CGI

Common Gateway Interface. Maps the URL path to a program, which executes; output is named resource.

NIDS ID Techniques: Stateful Protocol Analysis

Compares observed network traffic against predetermined universal vendor supplied profiles of benign protocol traffic. Tracks network, transport, and app protocol state to ensure they progress as expected. (high resource use.

Motivation behind AJAX

Consider auto completion; difficult in old architecture

Markup

Content may play specific role wrt other content in the doc. Markup isn't content but enhances its expression Indicates Structure Specifies role of different parts of content wrt doc as a whole and other content Decorates content with attributes

Common Headers

Content-length (required if msg body has content) -Content-type (In replies, the MIME type specifier for resource (like text/html or image/gif) -Expires -User-agent -Host (required in 1.1)

cookie header

Cookie: $Version = <version>; <name>=<value> [; $Path = <path>] [; $Domain = <domain>]

Empty elem

Could have content but happens not to.

Hyperlinks <a>

Creates hyperlinks to another page (full abs, rel path

Intruder Types:

Cyber Criminals, Activists,state-sponsored orgs, others

IDME components

Data source: The raw data than an IDS uses to detect unauth'r or undesired activity -Sensor: Collects data from source. -Analyzer: Analyzes collected data for signs of unauth'r /undesired activity or events of interest to security admin -Administrator: Sets security policy of org, and makes decisions about deploying/config the IDS. May/mayn't also be operator. -Manager: ID component or process from which the operator manages the various components of the ID system. -Operator: The human that is the primary user of IDS manager.

Difference btwn web and library

Databases have organization.

Ex of headers

Date: 28 Sept 2011 4:30:00 GMT Content-type: text/html

HTML tags

Defines structure. The text in between the start and end tags is the main content which can have more tag pairs.

MVC (Model - View - Controller)

Design pattern well suited for thinking about web apps

Selection: Hierarchy

E F Elems of type F that are descendents of an elem of type E (not direct per se) E > F Elems of type F that are direct children of elem of type E E + F Elems of type F that are a subsequent sibling of element of type E E:first-child Elems of type E that are the first child of its parent E:nth-child(N) Elems of type E that are the Nth child of its parent (where N in the above represents an integer above 1) N can be keyword "odd" or "even". N can be a function.

3 ways to associate CSS with HTML

External: <link> in <head> rel set to "stylesheet" type set to "text/css" href set to URL of stylesheet (full URL or abs/rel resolved against base) Internal <style type="text/css"> element in <head> In-line: Any elem can have "style" HTML attrib. Val of style are the CSS attrib declarations to be applied. No need for selector in this case since the CSS attrib declarations are applied directly. Ugly. Don't. Priority: Inline->Internal -> External

1NF

First Normal Form -All attribs single-valued, all instances have a unique identifier. -Multi-valued attributes usually indicate need for a new entity.

Scheme for HIDS

Host agent module- An audit collection module operating as a bg process on a monitored system. collects data. LAN monitor agent module- Operates as a host agent module except that it analyzes LAN traffic and reports the results to central manager. Central manager module- Receives reports from LAN monitor and host agents and processes and correlates theses reports to detect intrusion.

Floating

Float attrib (left, right, none(default) -Removes elems from normal flow, allows text, sibs to flow around, width should be set, multiple floats will push against each other. -Floats won't be placed higher than they would have been if not floated -Layout of text/elems located between floating elems may alter floating placement

Reading API documentation

Fns that are listed with initial "." represent methods available via a jQ obj (assumption that you already created the jQuery obj) -Fns that start with "jQuery are "static" fns that don't require a jQ obj to already exist.

Header types

General, Message headers (specific to either requests or replies), and Entity headers (info about msg body)

Cookies in PHP

Get cookie info from request: ($_COOKIE indexed by cookie name)

protocol

Formal set of rules for communicating over a network, which specifies message syntax and semantics

Forms

Forms used to replace the curr page with results, now AJAX ones do async requests to back end and dynamically update curr page with results

HTTP method mapping convention

GET with a resource type path: -Return an index of the resources -Params can be used to provide filter params GET with an instance path -Retrieves representation of resource named by id POST with a resource type path -Creates resource -CGI parameters provide resource data -Result provides resource id PUT with an instance path -Updates resource named by id -CGI params provide resource data -Servers often don't support PUT (substitute with POST) DELETE with an instance path -Deletes/destroys resource named by id -Often faked as a GET with a param to indicate delete is intended (examples on workflowy)

Activists

Hack for social/political causes. Website defacement, denial of service, theft/distribution of data for negative publicity.

Note: Nest with proper tree structure. I.e close in reverse order of declaration.

Good: <div> <p> This is <span> some text. </span> </p> </div> Bad: <div> <p> This is <span> some text. </p> </span> </div>

State-sponsored orgs

Groups of hackers sponsored by governments for espionage/sabotage. Known also as Advanced Persistent Threats (APT)

HTML vs HTTP

HTML specifies syntax and semantics of web page content -HTTP is a request/resp protocol -HTTP can be used for any kind of resource, named by URL path

Types of resources

HTML, Image (JPEG GIF PNG), Text

Others

Hack for challenge/esteem/reputation

Apprentice

Hackers with minimal skill who use toolkits. majority of hackers.. Easy to defend against.

AJAX MVC Model

Has XHR mechanism, which overcomes drawbacks and lets client-side code HTTP request asynchronously. Client-side gives reponse. DOESNT replace current page with new one. Interface loads once and is dynamically changed by client-side. Communicates with back end via XHR. Supports Web-based APIs

<table>

Has optional <caption> <thead> should follow if first set of rows is headings (filled with one or more <tr> <tfoot> should follow if last set of rows are column footers <tbody> follows as table body (filled with <tr>) <th> used in tr to indicate heading cells used within thead and tfoot

<button>

Has type attributes. can have content

Master

High level of skill. Can write toolkits from scratch. Discover new vulnerabilities on their own. Some of these in state-sponsored. Near impossible to defend against.

HTML

Hypertext Markup Language Format of web pages. This structured document provides - tags, - markup, -embedded resources, -Hyperlinks

PHP

Hypertext Preprocessor -Free, easy to learn, does a lot for you (handling cookies etc.) -Template-based -URL maps to PHP file -PHP file contains mix of PHP scripting code and HTML content - PHP portions evaluated as parsed -Can dynamically gen output for result -HTML portions copied to result directly - Dynamic server-genned content that may/mayn't have a client-side component -Reflects the original model for PHP and serverside prog in general

HTTP

Hypertext Transfer Protocol Request, Map, Response; Stateless

Distributed or Hybrid Intrusion Detection pt. 2

IDSs deployed selectively may miss a network-based attack or may be slow to recognize one is underway. Multple IDSs that share provide greater coverage and are faster, esp. or slow growing attacks. -Analysis of network traffic at the host level provides an environment in which there is much less network traffic than found at a network device such as a router. Attack patterns stands out more (higher signal-to noise ratio) -Host-based detectors make use of richer set of data possibly using app data from the host as input into the local classifier.

Selection: Arbitrary HTML

IN CSS elem[attr="value"]{ } -Matches elements of type elem that have attribute set to exactly "value" (same as E#id) elem[attr~="value"]{ } -Targets elems who contain "value" as one of the attributes in their space separated list

Selection: "id"

IN HTML <elem id="idname"> IN CSS elem#idname { stuff }

Cascade

If multiple selectors apply priority is Inline > Internal > External > Default THEN >number of IDs used > number of classes used > number of elem names used > Rule of thumb weight formula weight= num of elem names in selector + num of classes * 10 + num of IDs * 100 Children inherit style from parent if not specified otherwise.

Statements

If, else if, eles -switch -for -while do ... while -break,continue -for ... in (don't use for arrays)

Scope chain

Initially, the scope chain is the "window" object.. The chain has just one object so the object window is the first and last object in the chain. -window will always be the first in the chain.

Block vs Inline

Inline "in line" with text. Left to right line by line. Block end flow and start a new layout with width of parent, height as needed.

Cyber Criminals

Individuals or members of an organized crime group with a goal of financial reward. Do id theft, theft of credentials, corporate espionage, data theft/ransoming.

false negative

Intruders NOT identified by IDS because the definitions of intruders are too strict. (page 293)

inline sensor

Inserted into a network segment so that the traffic that it is monitoring must pass through the sensor.

Drawbacks to Old Web apps

Interactive features that require server-side response not well supported, dynamic info not handled well, has latency

JSON acronym

JavaScript Object Notation

Duck Typing

Javascript is typed dynamically -Properties resolved at the same time they are dereferenced -They either exist or they don't -If they don't, dereferencing them doesn't kill the program, it just produces "undefined" -When you write a fn or method that accepts an obj as a parameter, as long as that object has the properties you expect, your code will work

signature approaches

Match a large collection of known patters of malicious data stored on a system or in transit over a network. The sigs need to be large enough to minimize false alarm rate, while detecting a large fraction of malicious data. ADV: Low cost in time/resources DISADV: Lots of effort to constantly identify and review new malware to create sigs that identify them. Can't combat zero-day attacks.

VERSION

String literal: HTTP/1.1 OR HTTP/1.0 (rare)

position()

Like offset but retrieves position info relative to parent elem

Static props, methods, and constants

Like other OO langs, can define props, methods, and constants as static. (Can be accessed with class name followed by scope operator as in: (ClassName::$static_property ; ClassName::static_method())

<link>

Links to external resources, most commonly stylesheets, but also advanced hyperlinks.

Combining Selectors

Listing selectors with a comma associates attrib declarations to each selector in list Compound selectors chain selectors together using a selector whenever an elem name is expected.

DOM Tree

Main abstraction: tree of "Nodes"

2 styles of Javascript execution during parse

OLD: relied on in-order to dynamically generate doc content during parse (rare now) NEW: Defines fns and some data structures. Attaches async handlers for interactivity. Sets up "main" entry point to be executed after doc parse complete.

Javascript

Object oriented, no classes, uses "prototypes". Not used as a standalone language. Usually used as client-side Javascript. There is server-side Javascript, but we won't do this . Functions are first-class data types (key to prototype object system as well as "closures"

Data Link Library (DLL)

On windows, interfere with abilities of HIDS, as they complicate task measurement. This should be mitigated soon

HTML 5

Overtook XML Has modern tag set, cleaner/tighter syntax, better backward compatibility Tags better support web apps (audio/video tags)

Examples of intrusion

Performing a remote root compromise of email server -Defacing a web server -Guessing and cracking passwords -Copying a database containing credit card #s -Viewing sensitive data -Running a packet sniffer -Using a permission error on an anonymous FTP server to distribute piratesd stuff -Dialing into an unsecured modem and gaining internal network access. -posing as an executive, calling help desk, resetting executive's email password, leaning new one. -Using an unattended logged-in workstation without permission.

Hyperlinks

Pointers to other docs, addressed by URL

More CGI exec environ vars

REMOTE_ADDR has IP address of client. REMOTE_HOST has hostname of client. SCRIPT_NAME has path to script that was called. SERVER_NAME has server's hostname or IP address. SERVER_SOFTWARE has name and version of server software.

RESTful interfaces (more)

REST as an idea (keep interface stateless and idempotent as much as possible) -URLs identify noun -HTTP method identifies verb (may need to hack this if server doesn't support all methods needed

CGI Alternatives

Rack,J2EE, ASP.Net

.off(events, handler)

Removes an event handler, but you need to have access to original function object that you used with .on()

Server expects back from CGI program:

Reply must be sent through SDTOUT -2 parts to reply (Any reply headers followed by blank line [A few special CGI-specific headers, like Status, which allows you to signal what you want the status line of reply to be], and a reply body) -Server will finish constructing HTTP reply (makes a "200 OK" resp unless told to do otherwise by CGI status header; May add own HTTP reply headers)

HTTP requests 3 parts

Request-line, Header section (one per line; empty line indicates end of headers), Message Body(may or may not exist, often doesn't for requests)

Embedded Resources

Requested separately from the HTML itself. Ex. Images and Stylesheets

setTimeout(f, delay), clearTimeout(id)

Same as set/clear interval, but doesn't repeat after execution.

2NF

Second normal form -Already in 1NF -Non-identifying attribs are dependent on the entity's unique identifier -If the same value appears mulitple times for a particular attribute, consider adding another entity. -In particular, if same value for same attribute for 2 different instances of an entity meaningfully relates those entities to each other.

<div>

Sectioning element https://www.w3schools.com/tags/tag_div.asp

<select>

Selection lists/ Drop down box if size 1. <option>

Sensor

Sensors are responsible for collecting data. The input of a sensor may be any part of a system that could contain evidence of an intrusion. Types of input to a sensor includes network packets, log files, and system call traces. Sensors collect and forward this info to the analyzer.

IDS 3 components

Sensors, Analyzers, UI

Request

Sent by browser to server. Names URL path, specifies a "method" to indicate what to do with resource. Provides additional info about meta-data about the requester, acceptable formats and encodings, cookies

HTTP Response

Sent from server to browser. -Status of response -info about response sent Ex. (meta-data about responder, format/enc, cache directives, cookie settings) -The named resource

Evolution of Web aspects

Separation of content and style, server-side programming, client-side programming

Super globals

Special arrays that are available globally everywhere even if not declared -$_SERVER -$_GET (params encoded as part of URL, decoded with names as keys -$_POST (params enc as part of HTTTP req body with names as keys -$_COOKIE (cookie vals extracted from HTTP req headers) -$_FILES -$_SESSION (session persistent state) -$_ENV (Our server isn't configured to populate this super global. -$_REQUEST -> Union of $_GET, $_POST, $_COOKIE (Can be easier for retrieving param info when you don't know or care whether the req was a GET or a POST) (Server somtimes configged not to include $_COOKIE in $_REQUEST due to security concerns (like in wwwp)

HTML Markup

Specifies "role" of the content (header, list item, table, paragraph)

Code structure

Statements separated by ; (can be inferred, but bad form) Blocks of code delimited by {} // Single line comment /* multiline comm */

Behavior analysis techniques

Statistical: Analysis of observed behavior using univariate, multivariable or time-series models of observed metrics Knowledge based: Approaches use an expert system that classifies observed behavior according to a set of rules that model legit behavior -Machine-learning: Approaches auto determining a suitable classification model from the training data using data mining techniques.

Adv and disadv of anomaly detection approaches

Statistical: Simple, low-cost, not much assumed behavior expected. BUT difficult to select suitable metrics to obtain a balance between false pos and false neg and not all behaviors can be modeled this way Knowledge: Robust and flexible BUT difficult and time consuming to develop high quality knowledge from the data and needs human asssitance. Machine-based: Efficient BUT resouce/time intensive. AND Flexible and adapitible and capture interdependencies BUT high cost, too many false alarms, and need assumptions about behavior.

<span></span>

The <span> tag provides a way to add a hook to a part of a text or a part of a document. Ex. <p>My mother has <span style="color:blue">blue</span> eyes.</p>

Document

The Document interface represents the entire HTML or XML document. Conceptually, it is the root of the document tree (provided by global document variable in JS), and provides the primary access to the document's data.

User Interface

The UI to an IDS lets a user view output from the system or control its behavior.

adv and disadv of stateless

The stateless design simplifies the server design because there is no need to dynamically allocate storage to deal with conversations in progress. If a client dies in mid-transaction, no part of the system needs to be responsible for cleaning the present state of the server. A disadvantage of statelessness is that it may be necessary to include additional information in every request, and this extra information will need to be interpreted by the server.

3NF

Third Normal Form -In 2NF -No attributes dependent on each other without being uniquely dependent on the id -Pull dependent attributes into their own entity.

Document Object Model

Tree-based data structure in memory. Includes basic means of manipulation. Includes the event model (click, mouse, keyboard interaction)

Signature/ Heuristic HIDS

Used in anti-malware, common on Windows systems, and incorporated into mail and web app proxies on firewalls and in NIDS. -Use a databaes of sigs. -Good for known malware, can't get zero-day attacks

Inline sensor

Used to block an attack when one is detected (intrusion detection and prevention at once)

<base>

Used to specify base URL to be used for resolving relative resource paths and absolute paths

Using new operator

Used with a fn obj which is then treated like a constructor. This constructing fn obj essentially becomes the type. -A new empty obj is created. -Fn obj is called and the this keyword is set to ref the new object instance. (fn obj should act as a constructor; Initialize properties and methods of this; No need to return anything) -Value returned by new operator is a ref to the new obj -New object is linked to fn obj used as a constructor (can test "type" of object with instanceof operator; built in object types like Object, Array, date are simply fns that act as constructors instanceof considered harmful

-alert

Useful JS built-in for displaying modal alert messages

XHTML 1.0/ HTML 4.0

Uses CSS for presentation, standardized tag sets and their usage. Interoperability milestone.

Server-side Mechanisms

Uses HTML and CGI

signature detection

Uses a set of known malicious data patterns (signatures) or attack rules (heuristics) that are compared with current behavior to decide if an intruder is there. Needs known patterns/rules.

Set-cookie syntax cont

Values can be quoted strings (but need not be if doesn't result in ambiguity) -Other fields can be in any order -Semi-colon used to sep parts of the cookie -Secure is a flag (either there as word or not at all) -Attribute names are case-insensitive -Can have more than one Set-Cookie header in an HTTP resp

Accessing props/methods

Via an obj ref ($obj -> prop name) ($obj -> method_name()) Via $this (within methods, to get to an object's own properties, $this -> prop_name ; $this-> method_name()

<img>

Void elem, alt attrib required, which is a text description in case img display impossible. title attribute provides tooltip, src attrib provides resource name (full URL,abs path, rel path)

-Microsoft diffs

W3C DOM Event Model standardizes event names/propagation/binding/object data BUT Microsoft does this stuff a little differently

Server

Web Server

More on closures

When a fn obj (say, foo) is created as part of the execution of another function (say, bar), the curr scope chain gets saved as part of fn obj (end of the scope chain is local scope obj associated with the call to bar). -That scope chain gets restored when this fn obj is invoked. -That's why local vars that were in effect at time of fn's definition (when bar executed) are still available even though that particular invocation of bar may be done.

NIDS Alert Logging

When a sensor finds violation, sends alert and logs info related to event. NIDS analysis module uses info to refine intrusion detection params and algos. -Gather timestamp (date and time), connection or session ID, and the event/alert type. -Also gather rating(priority) severity, impact, confidence) -Network, transport, and app layer protocols -Source and destination IP -Source and destination TCP or UDP ports, or ICMP types and codes -Num of bytes transmitted over connection -Decoded payload data, such as app req and resp -State-related info

false positive

When loose intrusion detection accidentally scoops up normal users as a threat.

AJAX

XMLHttpRequest obj (or XHR) -Made by Microsoft -Allows JS to issue an HTTP req and then to process the reply (reply doesn't replace current doc, and doesn't have to be HTML) A- Asyncronous (req made but JS keeps going; Reply invokes a handler in the future, like event-based UI programming) J- Javascript A-And X-XML (original idea was that resp would be some sort of structured data in XML, now usually JSON)

more input types

button reset-Reset all UI elems to default -submit- HTTP request with encoded name/val pairs from all elems and initiate web req that produce replacement page (old)

Drag mouse default override

check workflowy

Defining a class

class ClassName { // Class definition public $prop1 = "init value"; protected $prop2; private $prop3; public function m1 () {...} protected function m2() {...} private function m3() {...} }

link attributes

href: URL of resource rel: relationship of link type: Provides type info for linked resource

=Hello world=

http://www.cs.unc.edu/~kmp/comp426fall17/examples/lec06/ex1

Hello World (jQ)

http://www.cs.unc.edu/~kmp/comp426fall17/examples/lec06/ex2

Javascript regular expressions

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Associative array JS

https://www.codecademy.com/en/forum_questions/54f241b0e39efeb81000310b -Index with keys, -apple.ber means apple at index "ber" -keys can be numbers (an array works this way) or other objects

Globally valid attributes

id (allows elem to be given name, must be unique among all id attrs of an element) class (interpreted as whitespace separated list of vals) tabindex (must be int, determines focus order when tab pressed)

<input>

input elem with specific input type given by "type" attrib HTML4; button,checkbox,file,hidden,image,pw, radio,reset,submit,text HTM5 adds: color,date, datetime, datetime-local, email, month, number, range, search, tel, time, url, week. In HTML its void elem (just start tag, no content)

Input types

input type = "" text: 1-line text inp password: no security, but no display of input radio: bubles checkbox: checked attrib changes default to on file:local file selection (transmit to server) hidden: Provides a way to set name/val pair to be included in form submission without visible rendering

css()

jQ fn to get/set CSS style attribs associated with elem (need to wrap jQ obj around 'this' before trying to use css()

$(document).ready(function_object)

jQ idiom for installing a "main" fn to be run after the document has been fully parsed and is "ready".

.on()

jQuery's most general and up-to-date way of setting up event handler -bind(),unbind(),delegate(),live(), are all prior methods, but on() handlers all this stuff

preventDefault()

keeps form submission from attempting to load new URL.

Keyboard Events

keydown, keyup, keypress

keypress v. keydown v. keyup

keypress is "logical (pressed then released key) -The key combined with possibl e modifiers map to a specific charCode -keydown and up are "physical" events (depression and release) -Specific key reported as keyCode (also reported in which) -Not the same charCode [identifies actual physical key pressed and not character typed] -No interpretation of key with respect to modifiers or key board mapping

.on(events,data,handler)

lets you refer to something as eventobj.data

Document Events

load, unload

Low/high interaction honeypot

low: Consists of a software package that emulates particular IT services or systems well enough to provide a realistic initial interaction, but doesn't execute a full version of those. high: A real system, with full OS, services and app, which are instrumented and deployed where they can be accessed by attackers. (more resources and could be compromised and used against you, damage reputation)

Inter-session or session-persistent state

persists between interactions with web applications

REST acronym

representational state transfer

Form and Form UI Events

select, change, submit, reset, focus, blur

CSS rules

selector { attrib: val; } -Selector determines which elems affected -Attrib declarations specify specific vals for a particular CSS attrib


Set pelajaran terkait

Chapters 14, respiratory and skin, 15

View Set

Management of Patients with Upper Resp Tract Disorders (Ch. 18) PREPU

View Set

Confidence and self efficacy in sports performance

View Set

Arthrology, myology Part 2 1.2 (mcqs)

View Set

Social Psychology Learning Curve

View Set

MANA 3335 Chapter 13 Practice Quiz

View Set

sociology exam #2 (ch. 3, 6, 12, 14)

View Set

PF Information Literacy Lesson 1

View Set

"Mini Boss Fight" study set for CPSC 1375

View Set