Newline Character

Writing Shellcode II

James C. Foster , Mike Price , in Sockets, Shellcode, Porting, & Coding, 2005

Analysis

In lines 1 through 4, we clean the registers using XOR.

In lines 5 and 6, we jump to the string section and call the code section. As explained earlier, the call instruction pushes the instruction pointer on the stack and then jumps to the code.

In line 11, within the code section, we pop the address of the stack into the ECX register, which now holds the pointer required for the second argument of the write system call.

In Unes 12 and 13, we put the file descriptor number of stdout into the BL register and the number of characters we want to write in the DL register. Now all arguments of the system call are ready. The number identifying the write system call is put into the AL register in line 13.

In line 14, we call the kernel to have the system executed.

Now we need to do an exit(O), because otherwise the code will start an infinite loop. Since exit(O) only requires one argument that has to be 0, we decrease the BL register (line 12), which still contains 1 (it was put there in line 8) with one byte and put the exit system call number in AL (line 14). Finally, exit is called and the program should terminate after the string "Hello, world!" is written to stdout. Let's compile and execute this assembly code to see if it works:

1 [[email protected]]# nasm -o write write.S

2 [[email protected]]# s-proc -e write

3 Calling code ...

4 Hello, world![[email protected]]#

Line 4 of the output tells us we forgot to add a new line at the end of the "Hello, world!" string.This can be fixed by replacing the string in the shellcode at line 17 with this:

db"Hello, world!',0x0a

Note that 0x0a is the hex value of a newline character. We also have to add 1 to the number of bytes we want to write at line 13 because otherwise the newline character isn't written. So replace line 13 with this:

mov dl,14

Let's recompile the assembly code and have a look:

[[email protected]]# nasm -o write-with-newline write-with-newline.S

[[email protected]]# s-proc -e write-with-newline

Calling code ...

Hello, world!

[[email protected]]#

As you may glean from the previous example, our newline character is printed and makes things look much better. In Example 9.2, we'll use the write system call on FreeBSD to display the string Morning!\n by pushing the string on the stack.

Example 9.2

The Write System Call in FreeBSD

1 xoreax,eax

2 cdq

3 push byte OxOa

4 push 0x21676e69;!gni

5 push 0x6e726f4d ;nroM

6 mov

7 push byte 0x9

8 push

9 push byte 0x1

10 push eax

11 mov al,0x4

12 int

13 push edx

14 moval,0x1

15 int 0x80

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9781597490054500158

Introduction to MATLAB Programming

Stormy Attaway , in MATLAB (Fifth Edition), 2019

3.3.2.1 Printing Vectors and Matrices

For a vector, if a conversion character and the newline character are in the format specifier, it will print in a column regardless of whether the vector itself is a row vector or a column vector.

>> vec = 2:5;

>> fprintf('%d', vec)

2

3

4

5

Without the newline character, it would print in a row, but the next prompt would appear on the same line:

>> fprintf('%d', vec)

2345   >>

However, in a script, a separate newline character could be printed to avoid this problem. It is also much better to separate the numbers with spaces.

printvec.m

% This demonstrates printing a vector

vec = 2:5;

fprintf('%d ',vec)

fprintf('')

>> printvec

2   3   4   5

>>

If the number of elements in the vector is known, that many conversion characters can be specified and then the newline:

>> fprintf('%d %d %d %d', vec)

2   3   4   5

>>

This is not very general, however, and is therefore not preferable.

For matrices, MATLAB unwinds the matrix column by column. For example, consider the following 2 × 3 matrix:

>>   mat = [5   9   8;   4   1   10]

mat =

5   9   8

4   1   10

Specifying one conversion character and then the newline character will print the elements from the matrix in one column. The first values printed are from the first column, then the second column, and so on.

>> fprintf('%d', mat)

5

4

9

1

8

10

If three of the %d conversion characters are specified, the fprintf will print three numbers across on each line of output, but again the matrix is unwound column-by-column. It again prints first the two numbers from the first column (across on the first row of output), then the first value from the second column, and so on.

>> fprintf('%d %d %d', mat)

5   4   9

1   8   10

If the transpose of the matrix is printed, however, using the three %d conversion characters, the matrix is printed as it appears when created.

>> fprintf('%d %d %d', mat')   % Note the transpose

5   9   8

4   1   10

For vectors and matrices, even though formatting cannot be specified, the disp function may be easier to use in general than fprintf because it displays the result in a straightforward manner. For example,

>> mat = [15 11 14; 7 10 13]

mat =

15   11   14

7   10   13

>> disp(mat)

15   11   14

7   10   13

>> vec = 2:5

vec =

2   3   4   5

>> disp(vec)

2   3   4   5

Note that when loops are covered in Chapter 5, formatting the output of matrices will be easier. For now, however, disp works well.

Note: there is another output function, display, which is generally not used by programmers and therefore will not be used in this text. The display function is used internally by MATLAB when an assignment statement is not suppressed. The display function is called implicitly in this case; it shows the variable name and the assignment operator, and generally, then calls the disp function to display the expression. The disp function does not show the variable name.

>> var = 33

var =

33

>> display(var)

var =

33

>> var

var =

33

>> disp(var)

33

When printing expressions, the output from disp and display may or may not be the same, depending on the type of the expression.

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9780128154793000039

Introduction to XQuery 1.0

Jim Melton , Stephen Buxton , in Querying XML, 2006

10.10.4 Text Output Method

The text output method is used to serialize Data Model instances into their string values, without any escaping. Serializers are allowed to serialize newline characters as any character used on the chosen platform as conventional line endings.

Serializers are required to use the encoding parameter to identify the mechanism to be used in converting the characters of a Data Model instance string value into a sequence of octets. The UTF-8 and UTF-16 encodings are mandated for all serializers, and serializers may support any other encodings their markets require. Similarly, serializers are required to use the normalization-form parameter to determine what Unicode normalization is performed during serialization. Values of NFC (Normalization Form C) and none must be supported, but other forms may be supported in addition.

We recommend that you consult the Serialization spec to learn the effects of other serialization parameters.

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9781558607118500113

Navigating the File System, Basic I/O and Sockets

Clif Flynt , in Tcl/Tk (Third Edition), 2012

4.4 Input/Output in TCL

It is difficult to perform any serious computer programming without accepting data and delivering results. Tcl abstracts the input and output commands into two input commands and one output command. Using these three commands, you can read or write to any file, pipe, device, or socket supported by tclsh or wish. A GUI-based wish script can perform user I/O through various graphics widgets but will use these three commands to access files, pipes to other programs, or sockets.

All I/O in Tcl is done through channels. A channel is an I/O device abstraction similar to an I/O stream in C. The Tcl channel device abstraction is extended beyond the stream abstraction to include sockets and pipes. The Tcl channel provides a uniform abstract model of the UNIX, Mac OS, and MS Windows socket calls, so they can be treated as streams.

The Tcl commands that open a channel return a handle that can be used to identify that channel. A channel handle can be passed to an I/O command to specify which channel should accept or provide data. These channels are predefined in Tcl, as follows.

stdin  Standard input: keyboard or a redirected file.

stdout  Standard output: usually the screen.

stderr  Error output: usually the screen. Note that Mac OS before OS/X and MS Windows do not distinguish between stdout and stderr.

4.4.1 Output

The puts command sends output to a channel. It requires a string to output as an argument. By default, this command will append a newline character to the string.

Syntax:puts ?-nonewline? ?channel? outputString

  Send a string to a channel.

?-nonewline?   Do not append a newline character to the output.

?channel?   Send output to this channel. If this argument is not used, send to standard output.

outputString   The data to send.

Example 8

% puts "Hello, "; puts "World "

Hello,

World

% puts -nonewline "Hello, "; puts "World"

Hello, World

4.4.2 Input

The Tcl commands that input data are the gets and read commands. The gets command will read a single line of input from a channel and strip off any newline character. The gets command may return the data that was read or the number of characters that were read. The read command will read a requested number of characters, or until the end of data. The read command always returns the data that was read.

The gets command is best for interactive I/O, since it will read a single line of data from a user. The read command is best used when there is a large body of text to read in a single read command, such as a file or socket, or when there is a need for single-character I/O.

Syntax:gets channelID ?varName?

  Read a line of data from a channel up to the first newline character. The newline character is discarded.

channelID   Read from this channel.

?varName?   If this variable name is present, gets will store the data in this variable, and will return the number of characters read. If this argument is not present, gets will return the line of data.

Example 9

  % gets stdin # A user types "Hello, World" at keyboard.

Hello, World

% gets stdin inputString # A user types "Hello, World" at keyboard.

12

% puts $inputString

Hello, World

A Tcl script can invoke the read command to read a specified number of characters, or to read data until an End-Of-File is encountered. If a script invokes the read command to read a specified number of characters and read encounters an End-Of-File before reading the requested number of characters, the read command will return the available characters and not generate an error. The read command returns the characters read. The read command may strip off the final newline character but by default leaves newlines intact.

Syntax:read channelID numBytes

  Read a specified number of characters from a channel.

channelID   The channel from which to read data.

numBytes   The number of bytes to read.

Syntax:read ?-nonewline? channelID

  Read data from a channel until an End-Of-File (EOF) condition.

?-nonewline?   Discard the last character if it is a newline.

channelID   The channel from which to read data.

Example 10

# Read from stdin until an End-Of-File is encountered

#

% read stdin # A user types Hello, World EOF

Hello, World

# Read 5 characters from stdin

% read stdin 5 # A user types Hello, World

Hello

When the output channel is the standard output device, Tcl buffers text until it has a complete line (until a newline character appears). To print a prompt and allow a user to enter text on the same line, you must either reset the buffering with fconfigure or use the flush (see Section 4.5.2) command to force Tcl to generate output.

Example 11

Script Example

puts -nonewline "What is your name? "

flush stdout

gets stdin name ;# User types name

puts "Hello, $name. Shall we play a game?"

Script Output

What is your name? Dr. Falken

Hello, Dr. Falken. Shall we play a game?

4.4.3 Creating a Channel

A Tcl script can create a channel with either the open or socket command. The open command can be used to open a channel to a file, a device, or a pipe to another program. The socket command can be used to open a client socket to a server or to open a server socket that will listen for clients.

Syntax:open fileName ?access? ?permissions?

Open a file, device, or pipe as a channel and return a handle to be used to access this channel.

fileName   The name of the file or device to open.

  If the first character of the name is a pipe (|), the filename argument is a request to open a pipe connection to a command. The first word in the file name will be the command name, and subsequent words will be arguments to the command.

?access?   How this file will be accessed by the channel. The access option may be one of:

r  Open file for read-only access.

r+  Open file for read and write access. File must already exist.

w  Open file for write-only access. Truncate file if it exists.

w+  Open file for read and write access. Truncate the file if it exists, or create it if it does not exist.

a  Open file for write-only access. New data will be appended to the file. For versions of Tcl before 8.3, the file must already exist. With Tcl8.3, the behavior was changed to create a new file if it does not already exist.

a+  Open file for read and write access. Create the file if it does not exist. Append data to an existing file.

?permissions?   If a new file is created, this parameter will be used to set the file permissions. The permissions argument will be an integer, with the same bit definitions as the argument to the creat system call on the operating system being used.

Example 12

Script Example

# Open a file for writing - Note square brackets cause the Tcl command

# to be evaluated, and the channel handle returned by open

# is assigned to the variable outputFile.

set outputFile [open "testfile" "w"]

# send a line to the output file.

puts $outputFile "This is line 1"

puts $outputFile "This is line 2"

puts $outputFile "This is line 3"

# Close the file.

close $outputFile

# Reopen the file for reading

set inputFile [open "testfile" "r"]

# Read a line of text

set numBytes [gets $inputFile string]

# Display the line read

puts "Gets returned $numBytes characters in the string: $string"

# Read the rest of the file

set string2 [read $inputFile]

puts "Read: $string2"

# Announce intent

puts "\nOpening a Pipe\n"

# and open a pipe to the ls command

set pipe [open "|ls /" "r"]

# Equivalent command under MS-Windows is:

# set pipe [open "!command.com /c dir" "r"]

# read the output of the ls command:

while {![eof $pipe]} {

set length [gets $pipe lsLine]

puts "$lsLine is $length characters long"

}

Script Output

Gets returned 14 characters in the string: This is line 1

Read: This is line 2

This is line 3

Opening a Pipe

bin is 3 characters long

boot is 4 characters long

bsd is 3 characters long

dev is 3 characters long

...

4.4.4 Closing Channels

The Tcl interpreter supports having multiple channels open simultaneously. The exact number is defined at compile time and by the underlying operating system. In order to process many files, your script will need to close channels after it has completed processing them.

Syntax:close channel

  Close a channel.

channel  The handle for the channel to be closed.

When a file that was opened for write access is closed, any data in the output buffer is written to the channel before it is closed.

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B978012384717100004X

Introduction to Tk Graphics

Clif Flynt , in Tcl/Tk (Third Edition), 2012

11.6.2 The button Widget

The button widget will evaluate a script when a user clicks it with the mouse. The script may be any set of Tcl commands, including procedure calls. By default, a script attached to a widget will be evaluated in the global scope. The scope in which a widget's -command script will be evaluated can be modified with the namespace current, namespace code or the TclOO self command.

Syntax: button buttonName ?option1? ?option2? …

Create a button widget.
buttonName The name to be assigned to the widget.
?options? Valid options for button include:
-font fontDescr Defines the font to use for this button. Font descriptors are discussed in the next chapter.
-command script A script to evaluate when the button is clicked.
-text displayTxt The text that will appear in this button. A newline character ( \n) can be embedded in this text to create multi-line buttons.

The example shows two sets of code, one in global scope and one in a namespace. Each of these generate the same GUI with the same behavior. Note the use of namespace current, namespace code and the -textvariable option in the second code example.

Example 6

Script Example (Global Scope)

set myLabel [label .l1 -text "This is the beginning text"]

set myButton [button .b1 -text "click to modify label"\

-command \

"$myLabel configure -text {The Button was Clicked}"]

grid $myLabel

grid $myButton

Script Example (Within a namespace)

namespace eval demo {

variable labelText "This is the beginning text"

set myLabel [label .l1 \

-textvariable [namespace current]::labelText]

set myButton [button .b1 -text "click to modify label"\

-command [namespace code \

{set labelText {The Button was Clicked}}]]

grid $myLabel

grid $myButton

}

Script Output

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9780123847171000117

Data Streams

Daniel Shiffman , in Learning Processing (Second Edition), 2015

19-5 Multi-user communication, Part 1: The server

The broadcast example demonstrates one-way communication where a server broadcasts a message and many clients receive that message. The broadcast model, however, does not allow a client to turn around and send a reply back to the server. In this section, I will cover how to create a sketch that involves communication between multiple clients facilitated by a server.

Let's explore how a chat application works. Five clients (you and four friends) connect to a server. One client types a message: "Hey everyone!" That message is sent to the server, which relays it back to all five clients. Most multi-user applications function in a similar fashion (though it's also possible for applications to communicate directly without a server, which is known as peer-to-peer. A multiplayer online game, for example, would likely have clients sending information related to their whereabouts and actions to a server that broadcasts that data back to all other clients playing the game.

A multi-user application can be developed in Processing using the network library. To demonstrate, I will create a networked, shared whiteboard. As a client drags its mouse around the screen, the sketch will send (x,y) coordinates to the server that passes them back to any other connected clients. Everyone connected will be able to see the drawing actions of everyone else.

In addition to learning how to communicate between multiple clients, this example will explore how to send multiple values. How can a client send two values (an x and a y coordinate) and have the server know which one is which?

The first step toward a solution involves developing a protocol for communication between the clients. In what format is the information sent and how is that information received and interpreted? Luckily for you, the time you spent learning how to create, manage, and parse String objects in Chapter 20 and Chapter 18 will provide all the tools you need.

Assume a client wants to send the mouse location: mouseX = 100 and mouseY = 125. I need to format that information as a string in a way that is convenient to decipher. One possibility is as follows:

"The first number before the comma is the x location, the second number after the comma is 125. The data ends where an newline character (\n) appears."

In code, it would appear as follows:

String dataToSend = "100,125\n";

or, more generally:

String dataToSend = mouseX + "," + mouseY + "\n";

Here, I have developed a protocol for sending and receiving data. The integer values for mouseX and mouseY are encoded as a string during sending (number, followed by comma, followed by number, followed by newline). They will have to be decoded upon receipt, and I will get to that later. While most examples typically use a newline or carriage return to mark the end of a message (as you saw in the first section of this chapter), it is by no means required and you can design and implement any messaging protocol you so choose as long as it matches up in the client and server code.

What is really sent?

Data sent across a network is sent as a sequential list of individual bytes. Recalling the discussion of data types in Chapter 4, a byte is an 8-bit number, that is, a number made up of eight 0's and 1's or a value between 0 and 255.

Let's assume I want to send the number 42. I have two options:

client.write(42); // sending the byte 42

In the line above, I am really sending the actual byte 42.

client.write("42"); // sending the String "42"

In the line above, I am sending a string. That string is made up of two characters, a '4' and a '2'. I am sending two bytes! Those bytes are determined via the ASCII (American Standard Code for Information Interchange) code, a standardized means for encoding characters. The character 'A' is byte 65, the character 'B' 66, and so on. The character '4' is byte 52 and '2' is 50.

When the sketch reads the data, it's up to me to know whether to interpret the bytes coming in as literal numeric values or as ASCII codes for characters. This accomplished by choosing the appropriate read() function.

int val = client.read(); // Matches up with client.write(42);

String s = client.readString(); // Matches up with client.write("42");

int num = int(s); // Convert to an integer

I am now ready to create a server to receive the messages from the client. It will be the client's job to format those messages with my protocol. The job of the server remains simple: (1) receive the data and (2) relay the data. This is similar to the approach I took in Section 19-2 on page 428.

Step 1. Receiving data.

Client client = server.available();

if (client ! = null) {

incomingMessage = client.readStringUntil('\n');

}

Note how, again, the newline character ('\n') is used to mark the end of the incoming data. I am simply following the protocol established during sending. I am able to do this because I am designing both the server and the client.

Once that data is read, I am ready to add:

Step 2. Relaying data back out to clients.

Here is the full server with some bells and whistles. A message is displayed onscreen when new clients connect as well as when the server receives data.

Example 19-5

Multi-user server

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9780123944436500196

Tips and Techniques

Clif Flynt , in Tcl/Tk (Third Edition), 2012

19.2 TCL as a Glue Language: The exec Command

Although almost any application can be written in Tcl, not all applications should be written in Tcl. Some applications should be written using Tcl with an extension, and some should be written using Tcl as a glue language to join other standalone programs.

Scripting languages are extremely useful for applications that require gluing several pieces of functionality into a new application. They are less well suited to creating base functionality such as the following.

Arithmetic-based algorithms (generating checksums or compressing files)

Large data applications (subsampling images)

Controlling hardware (device drivers)

Tcl/Tk's strength is how easy it makes merging several libraries and standalone programs into a complex application. This merging can be done by creating new Tcl extensions or by using Tcl to glue several standalone programs into a new application. If the functionality you need involves several functions and is available in an existing library, it is probably best to make a Tcl extension wrapper to access the library. See Chapter 15 on writing extensions and Chapter 18 on the SWIG and CriTcl packages for automating creating extensions from libraries.

The extensions you create can either be linked into a new interpreter or merged at runtime with the load command. Note that you can use the load command only if your operating system supports dynamically loaded libraries (.so under Linux and Solaris, .dll under Windows). If standalone applications exist that perform a subset of what you need, you can use these existing applications with a Tcl script to control and extend them to perform the tasks you need done.

Many applications are easily written using Tcl and extensions for some functionality, and invoking standalone programs for other functionality. For example, I've used a Tk script to control the PPP connections on a UNIX system. It used the BLT extension to create an activity bar chart, invoked several standalone programs to initiate PPP connections and monitor the activity, and had some Tcl code to collect the data from various sources and report the number of connection hours.

The caveat with calling standalone programs from your script is that it can limit the portability of the script. For instance, a script that uses ps to monitor active processes and display the top CPU users will require different ps arguments for BSD and System V-based UNIXes and will not run at all on a Macintosh or Windows platform.

The command that lets you merge existing standalone programs into a new application is the exec command. The exec command will invoke new programs in a subprocess and return the program output to the Tcl interpreter as the result of the command. If the subtask exits with a non-zero status (an error status), the exec command will generate an error. You can invoke a single program with the exec command, or a series of commands where the output of one program becomes the input to the next program with the UNIX pipe symbol (|). The argument to the exec command is either an exec option, a command to execute as a subprocess, an argument for the commands, or a pipeline descriptor.

Syntax: exec ?-options? arg1 ?arg2…argn?

Execute arguments in a subprocess.
-options The exec command supports two options:
-keepnewline Normally, a trailing newline character is deleted from the program output returned by the exec command. If this argument is set, the trailing newline is retained.
-- Denotes the last option. All subsequent arguments will be treated as subprocess program names or arguments.
arg* These arguments can be either a program name, a program argument, or a pipeline descriptor. There are many pipeline descriptors. Some of the commonly used ones are:
| Separates distinct programs in the command line. The standard output of the program on the left side of the pipe symbol (—) will be used as the standard input for the program on the right of the pipe symbol.
< fileName The first program in the list will use the content of fileName as the standard input.
> fileName The standard output from the last program in the list will be written to fileName .

The following examples create compressed archives of files in a directory under UNIX or Windows using the exec command.

19.2.1 Creating a G-zipped tar Archive under UNIX

Example 7

Script Example

# This script is called with the name of a directory to

#   archive as the first argument in the command line,

#   and the name of the archive as the second argument.

set directory [lindex $argv 0]

set archive [lindex $argv 1]

# Get a list of the files to include in the archive.

set fllst [glob $directory/*]

# Create the tar archive, and gzip it.

eval exec tar -cvf $archive $fllst

exec gzip $archive

19.2.2 Creating a Zip Archive under Windows

Example 8

# This script is called with the name of a directory to

#   archive as the first argument in the command line,

#   and the name of the archive as the second argument.

set directory [lindex $argv 0]

set zipfile [lindex $argv 1]

# The file "distfiles" will contain a list of files for

#   this archive.

set outfl [open distfiles "w"]

# Get a list of the files to include in the archive.

set fllst [glob $directory/*]

# And write that list into the contents file, one

# filename per line

foreach fl $fllst {

  puts $outfl "$fl"

}

close $outfl

# Execute the winzip program to make an archive.

eval "exec C:/winzip/winzip32.exe -a $zipfile @distfiles"

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9780123847171000191

Loop Statements and Vectorizing Code

Stormy Attaway , in MATLAB (Fifth Edition), 2019

5.2 Nested for Loops

The action of a loop can be any valid statement(s). When the action of a loop is another loop, this is called a nested loop .

The general form of a nested for loop is as follows:

for loopvarone = rangeone     outer loop

% actionone includes the inner loop

for loopvartwo = rangetwo     inner loop

actiontwo

end

end

The first for loop is called the outer loop ; the second for loop is called the inner loop . The action of the outer loop consists (in part; there could be other statements) of the entire inner loop.

As an example, a nested for loop will be demonstrated in a script that will print a box of stars (⁎). Variables in the script will specify how many rows and columns to print. For example, if rows has the value 3 and columns has the value 5, a 3   ×   5 box would be printed. As lines of output are controlled by printing the newline character, the basic algorithm is as follows.

For every row of output:

Print the required number of stars

Move the cursor down to the next line (print '\n')

printstars.m

% Prints a box of stars

% How many will be specified by two variables

% for the number of rows and columns

rows = 3;

columns = 5;

% loop over the rows

for i   =   1:rows

% for every row loop to print ⁎'s and then one \n

for j   =   1:columns

fprintf('⁎')

end

fprintf('\n')

end

Executing the script displays the output:

>> printstars

⁎⁎⁎⁎⁎

⁎⁎⁎⁎⁎

⁎⁎⁎⁎⁎

The variable rows specifies the number of rows to print, and the variable columns specifies how many stars to print in each row. There are two loop variables: i is the loop variable over the rows and j is the loop variable over the columns. As the number of rows is known and the number of columns is known (given by the variables rows and columns), for loops are used. There is one for loop to loop over the rows, and another to print the required number of stars for every row.

The values of the loop variables are not used within the loops, but are used simply to iterate the correct number of times. The first for loop specifies that the action will be repeated "rows" times. The action of this loop is to print stars and then the newline character. Specifically, the action is to loop to print columns stars (e.g., five stars) across on one line. Then, the newline character is printed after all five stars to move the cursor down to the next line.

In this case, the outer loop is over the rows, and the inner loop is over the columns. The outer loop must be over the rows because the script is printing a certain number of rows of output. For each row, a loop is necessary to print the required number of stars; this is the inner for loop.

When this script is executed, first the outer loop variable i is initialized to 1. Then, the action is executed. The action consists of the inner loop and then printing the newline character. So, while the outer loop variable has the value 1, the inner loop variable j iterates through all of its values. As the value of columns is 5, the inner loop will print a single star five times. Then, the newline character is printed and then the outer loop variable i is incremented to 2. The action of the outer loop is then executed again, meaning the inner loop will print five stars, and then the newline character will be printed. This continues, and, in all, the action of the outer loop will be executed rows times.

Notice that the action of the outer loop consists of two statements (the for loop and an fprintf statement). The action of the inner loop, however, is only a single fprintf statement.

The fprintf statement to print the newline character must be separate from the other fprintf statement that prints the star character. If we simply had

fprintf('⁎\n')

as the action of the inner loop (without the separate fprintf), this would print a long column of 15 stars, not a 3   ×   5 box.

Quick Question!

How could this script be modified to print a triangle of stars instead of a box such as the following:

 

  ⁎⁎

  ⁎⁎⁎

Answer:

In this case, the number of stars to print in each row is the same as the row number (e.g., one star is printed in row 1, two stars in row 2, and so on). The inner for loop does not loop to columns, but to the value of the row loop variable (so we do not need the variable columns):

printtristars.m

% Prints a triangle of stars

% How many will be specified by a variable

% for the number of rows

rows = 3;

for i   =   1:rows

% inner loop just iterates to the value of i

for j   =   1:i

fprintf('⁎')

end

fprintf('\n')

end

In the previous examples, the loop variables were just used to specify the number of times the action is to be repeated. In the next example, the actual values of the loop variables will be printed.

printloopvars.m

% Displays the loop variables

for i = 1:3

for j = 1:2

fprintf('i   =%d, j   =%d\n',i,j)

end

fprintf('\n')

end

Executing this script would print the values of both i and j on one line every time the action of the inner loop is executed. The action of the outer loop consists of the inner loop and printing a newline character, so there is a separation between the actions of the outer loop:

>> printloopvars

i   =   1, j   =   1

i   =   1, j   =   2

i   =   2, j   =   1

i   =   2, j   =   2

i   =   3, j   =   1

i   =   3, j   =   2

Now, instead of just printing the loop variables, we can use them to produce a multiplication table, by multiplying the values of the loop variables.

The following function multtable calculates and returns a matrix which is a multiplication table. Two arguments are passed to the function, which are the number of rows and columns for this matrix.

multtable.m

function outmat = multtable(rows, columns)

% multtable returns a matrix which is a

% multiplication table

% Format: multtable(nRows, nColumns)

% Preallocate the matrix

outmat = zeros(rows,columns);

for i = 1:rows

for j = 1:columns

outmat(i,j) = i ⁎ j;

end

end

end

In the following example of calling this function, the resulting matrix has three rows and five columns:

>> multtable(3,5)

ans =

1   2   3   4   5

2   4   6   8   10

3   6   9   12   15

Note that this is a function that returns a matrix. It preallocates the matrix to zeros, and then replaces each element. As the number of rows and columns are known, for loops are used. The outer loop loops over the rows, and the inner loop loops over the columns. The action of the nested loop calculates i ⁎ j for all values of i and j. Just like with vectors, it is again important to notice that the loop variables are used as the indices into the matrix.

First, when i has the value 1, j iterates through the values 1 through 5, so first we are calculating 1⁎1, then 1⁎2, then 1⁎3, then 1⁎4, and, finally, 1⁎5. These are the values in the first row (first in element outmat(1,1), then outmat(1,2), then outmat(1,3), then outmat(1,4), and finally outmat(1,5)). Then, when i has the value 2, the elements in the second row of the output matrix are calculated, as j again iterates through the values from 1 through 5. Finally, when i has the value 3, the values in the third row are calculated (3⁎1, 3⁎2, 3⁎3, 3⁎4, and 3⁎5).

This function could be used in a script that prompts the user for the number of rows and columns, calls this function to return a multiplication table, and writes the resulting matrix to a file:

createmulttab.m

% Prompt the user for rows and columns and

% create a multiplication table to store in

% a file "mymulttable.dat"

num_rows = input('Enter the number of rows: ');

num_cols = input('Enter the number of columns: ');

multmatrix = multtable(num_rows, num_cols);

save mymulttable.dat multmatrix -ascii

The following is an example of running this script, and then loading from the file into a matrix in order to verify that the file was created:

>> createmulttab

Enter the number of rows: 6

Enter the number of columns: 4

>> load mymulttable.dat

>> mymulttable

mymulttable =

1   2   3   4

2   4   6   8

3   6   9   12

4   8   12   16

5   10   15   20

6   12   18   24

Practice 5.3

For each of the following (they are separate), determine what would be printed. Then, check your answers by trying them in MATLAB.

mat = [7   11   3; 3:5];

[r, c] = size(mat);

for i = 1:r

fprintf('The sum is %d\n', sum(mat(i,:)))

end

-   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -   -

for i = 1:2

fprintf('%d: ', i)

for j   = 1:4

fprintf('%d ', j)

end

fprintf('\n')

end

5.2.1 Combining Nested for Loops and if Statements

The statements inside of a nested loop can be any valid statements, including any selection statement. For example, there could be an if or if-else statement as the action, or part of the action, in a loop.

As an example, assume there is a file called "datavals.dat" containing results recorded from an experiment. However, some were recorded erroneously. The numbers are all supposed to be positive. The following script reads from this file into a matrix. It prints the sum from each row of only the positive numbers. We will assume that the file contains integers, but will not assume how many lines are in the file nor how many numbers per line (although we will assume that there are the same number of integers on every line).

sumonlypos.m

% Sums only positive numbers from file

% Reads from the file into a matrix and then

%   calculates and prints the sum of only the

%   positive numbers from each row

load datavals.dat

[r c] = size(datavals);

for row = 1:r

runsum = 0;

for col = 1:c

if datavals(row,col) >= 0

runsum = runsum + datavals(row,col);

end

end

fprintf('The sum for row %d is %d\n',row,runsum)

end

For example, if the file contains:

33   -11   2

4   5   9

22   5   -7

2   11   3

the output from the program would look like this:

>> sumonlypos

The sum for row 1 is 35

The sum for row 2 is 18

The sum for row 3 is 27

The sum for row 4 is 16

The file is loaded and the data are stored in a matrix variable. The script finds the dimensions of the matrix and then loops through all of the elements in the matrix by using a nested loop; the outer loop iterates through the rows and the inner loop iterates through the columns. This is important; as an action is desired for every row, the outer loop has to be over the rows. For each element, an if statement determines whether the element is positive or not. It only adds the positive values to the row sum. As the sum is found for each row, the runsum variable is initialized to 0 for every row, meaning inside of the outer loop.

Quick Question!

Would it matter if the order of the loops was reversed in this example, so that the outer loop iterates over the columns and the inner loop over the rows?

Answer:

Yes, as we want a sum for every row the outer loop must be over the rows.

Quick Question!

What would you have to change in order to calculate and print the sum of only the positive numbers from each column instead of each row?

Answer:

You would reverse the two loops, and change the sentence to say "The sum of column…". That is all that would change. The elements in the matrix would still be referenced as datavals(row,col). The row index is always given first, then the column index—regardless of the order of the loops.

Practice 5.4

Write a function mymatmin that finds the minimum value in each column of a matrix argument and returns a vector of the column minimums. Use the programming method. An example of calling the function follows:

>> mat = randi(20,3,4)

mat =

15   19   17   5

6   14   13   13

9   5   3   13

>> mymatmin(mat)

ans =

6   5   3   5

Quick Question!

Would the function mymatmin in Practice 5.4 also work for a vector argument?

Answer:

Yes, it should, as a vector is just a subset of a matrix. In this case, one of the loop actions would be executed only one time (for the rows if it is a row vector or for the columns if it is a column vector).

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9780128154793000052

Introduction to the Tcl Language

Clif Flynt , in Tcl/Tk (Third Edition), 2012

3.6 Bottom Line

This covers the basics of the Tcl language. The next chapter introduces the Tcl I/O calls, techniques for using these commands, and a few more commands.

Tcl is a position-based language rather than a keyword-based language.

A Tcl command consists of

A command name

Optional subcommand, flags, or arguments

A command terminator [either a newline or semicolon (;)]

Words and symbols must be separated by at least one whitespace (space, tab, or escaped newline) character.

Multiple words or variables can be grouped into a single argument with braces ({}) or quotes ("").

Substitution will be performed on strings grouped with quotes.

Substitutions will not be performed on strings grouped with curly braces ({}).

A Tcl command is evaluated in a single pass.

The Tcl evaluation routine is called recursively to evaluate commands enclosed within square brackets.

Some Tcl commands can accept flags to modify their behavior. A flag will always start with a hyphen. It may proceed or follow the arguments (depending on the command) and may require an argument itself.

Values are assigned to a variable with the set command.

Syntax: set varName value

Math operations are performed with the expr and incr commands.

Syntax: expr mathExpression

Syntax: incr varName ?incrValue?

The branch commands are if and switch.

Syntax: if {test} {bodyTrue} ?elseif {test2} {body2}? ?else {bodyFalse}?

Syntax: switch ?option? string pattern1 body1\

  ?pattern2 body2? ?default defaultBody?

The looping commands are for, while, and foreach.

Syntax: for start test next body

Syntax: while test body

Syntax: foreach listVar list body

The list operations include list, split, llength, lindex, and lappend.

Syntax: list element1 ?element2? … ?elementN?

Syntax: linsert list position element1 … ?elementN?

Syntax: lappend listName ?element1? … ?elementN?

Syntax: split data ?splitChar?

Syntax: join list ?joinString?

Syntax: llength list

Syntax: lindex list index

Syntax: lsearch list pattern

Syntax: lreplace list position1 position2 element1 ?… elementN?

The string processing subcommands include first, last, length, match, toupper, tolower, and range.

Syntax: string first substr string

Syntax: string last substr string

Syntax: string length string

Syntax: string match pattern string

Syntax: string toupper string

Syntax: string tolower string

Syntax: string range string first last

Formatted strings can be generated with the format command.

Syntax: format format ?data? ?data2? …

The scan command will perform simple string parsing.

Syntax: scan textstring format ?varName1? ?varName2? …

The array processing subcommands include array names, array set, and array get.

Syntax: array names arrayName ?pattern?

Syntax: array set arrayName {index1 value1 …}

Syntax: array get arrayName

Values can be converted between various ASCII and binary representations with binary scan and binary format.

The source command loads and evaluates a script.

Syntax: source fileName

The info command returns information about the current state of the interpreter.

Syntax: info proc

Syntax: info args

Syntax: info body

Syntax: info exists

Syntax: info nameofexecutable

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9780123847171000038

Leveraging Platform Weaknesses

Mike Shema , in Hacking Web Apps, 2012

Executing Shell Commands

Web application developers with enough years of experience cringe at the thought of passing the value of a URI parameter into a shell command. Modern web applications erect strong bulwarks between the application's process and the underlying operating system. Shell commands by their nature subvert that separation. At first it may seem strange to discuss these attacks in a chapter about server misconfigurations and predictable pages. In fact, a secure server configuration can mitigate the risk of shell command exploits regardless of whether the payload's entry point was part of the web application or merely one component of a greater hack.

In the nascent web application environment of 1996 it was not uncommon for web sites to run shell commands with user-supplied data as arguments. In fact, an early 1996 CERT advisory related to web applications described a command-execution vulnerability in an NCSA/Apache CGI module (http://www.cert.org/advisories/CA-1996-06.html). The exploit involved injecting a payload that would be passed into the UNIX popen() function. The following code shows a snippet from the vulnerable source.

strcpy(commandstr, "/usr/local/bin/ph -m ");

if (strlen(serverstr)) {

  strcat(commandstr, " -s ");

  /∗ RM 2/22/94 oops ∗/

  escape_shell_cmd(serverstr);

  strcat(commandstr, serverstr);

  strcat(commandstr, " ");

}

/∗ ... some more code here ... ∗/

phfp = popen(commandstr,"r");

send_fd(phfp, stdout);

The developers did not approach this CGI script without some caution. They created a custom escape_shell_cmd() function that stripped certain shell metacharacters and control operators. This was intended to prevent an attacker from appending arbitrary commands. For example, one such risk would be concatenating a command to dump the system's password file.

/usr/local/bin/ph -m -s ;cat /etc/passwd

The semicolon, being a high-risk metacharacter, was stripped from the input string. In the end attackers discovered that one control operator wasn't stripped from the input, the newline character (hexadecimal 0x0A). Thus, the exploit looked like this:

http://site/cgi-bin/phf?Qalias=%0A/bin/cat%20/etc/passwd

The phf exploit is infamous because it was used in a May 1999 hack against the White House's web site. An interview with the hacker posted on May 11th (two days after the compromise) to the alt.2600.moderated Usenet group alluded to an "easily exploitable" vulnerability 3 . In page 43 of The Art of Intrusion by Kevin Mitnick and William Simon the vulnerability comes to light as a phf bug that was used to execute an xterm command that sent an interactive command shell window back to the hacker's own server. The command cat /etc/passwd is a cute trick, but xterm -display opens a whole new avenue of attack for command injection exploits.

Lest you doubt the relevance of a vulnerability over 13 years old, consider how simple the vulnerability was to exploit and how success (depending on your point of view) rested on two crucial mistakes. First, the developers failed to understand the complete set of potentially malicious characters. Second, user data was mixed with a command. Malicious characters, the newline included, have appeared in Chapter 1: Cross-Site Scripting (XSS) and Chapter 3: SQL Injection. Both of those chapters also discussed this issue of leveraging the syntax of data to affect the grammar of a command, either by changing HTML to affect an XSS attack or modifying a SQL query to inject arbitrary statements. We'll revisit these two themes throughout this chapter.

Note

A software project's changelog provides insight into the history of its development, both good and bad. Changelogs, especially for Open Source projects can signal problematic areas of code or call out specific security fixes. The CGI example just mentioned had this phrase in its changelog, "add newline character to list of characters to strip from shell cmds to prevent security hole." Attackers will take the time to peruse changelogs (when available) for software from the web server to the database to the application. Don't bother hiding security messages or believe that proprietary binaries without source code available discourages attackers. Modern security analysis is able to track down vulnerabilities just by reverse-engineering the binary patch to a piece of software. Even if a potential vulnerability is discovered by the software's development team without any known attacks or public reports of its existence, the changes—whether a changelog entry or a binary patch—narrow the space in which sophisticated attackers will search for a way to exploit the hitherto unknown vulnerability.

The primary reason shell commands are dangerous is because they put the attacker outside the web application's process space and into the operating system. The attacker's access to files and ability to run commands will only be restricted by the server's configuration. One of the reasons that shell commands are difficult to secure is that many APIs that expose shell commands offer a mix of secure and insecure methods. There is a tight parallel here with SQL injection. Although programming languages offer prepared statements that prevent SQL injection, developers are still able to craft statements with string concatenation and misuse prepared statements.

In order to attack a shell command the payload typically must contain one of the following metacharacters.

| & ; () < >

Or it must contain a control operator like one of the following. (There's an overlap between these two groups.)

|| & && ; ;; () |

Or a payload might contain a space, tab, or newline character. In fact, many hexadecimal values are useful to command injection as well as other web-related injection attacks. Some of the usual suspects are shown in Table 7.1.

Table 7.1. Common delimiters for injection attacks

Hexadecimal Value Typical Meaning
0×00 NULL character. String terminator in C-based languages
0×09 Horizontal tab
0×0a New line
0×0b Vertical tab
0×0d Carriage return
0×20 Space
0×7f Maximum 7-bit value
0×ff Maximum 8-bit value

While many of the original vectors of attack for command shells, CGI scripts written in Bash to name one, the vulnerability has not disappeared. Like many vulnerabilities from the dawn of HTTP, the problem seems to periodically resurrect itself through the years. More recently in July 2009 a command injection vulnerability was reported in the web-based administration interface for wireless routers running DD-WRT. The example payload didn't try to access an /etc/passwd file (which wouldn't be useful anyway from the device), but it bears a very close resemblance to attacks 13 years earlier. The payload is part of the URI's path rather than a parameter in the query string, as shown below. It attempts to launch a netcat listener on port 31415.

http://site/cgi-bin/;nc$IFS-l$IFS-p$IFS\31415$IFS-e$IFS/bin/sh

The $IFS token in the URI indicates the Input Field Separator used by the shell environment to split words. The most common IFS is the space character, which is used by default. Referencing the value as $IFS simply instructs the shell to use substitute the current separator, which would create the following command.

nc -l -p 31415 -e /bin/sh

The IFS variable can also be redefined to other characters. Its advantage in command injection payloads is to evade inadequate countermeasures that only strip spaces.

IFS=2&&P=nc2-l2-p2314152-e2/bin/sh&&$P

Creative use of the IFS variable might bypass input validation filters or monitoring systems. As with any situation that commingles data and code, it is imperative to understand the complete command set associated with code if there is any hope of effectively filtering malicious characters.

Injecting PHP Commands

Since its inception in 1995 PHP has suffered many growing pains regarding syntax, performance, adoption, and our primary concern, security. We'll cover different aspects of PHP security in this chapter, but right now we'll focus on accessing the operating system via insecure scripts.

PHP provides a handful of functions that execute shell commands.

exec()

passthru()

popen()

shell_exec()

system()

Any string between backticks (ASCII hexadecimal value 0×60)

The developers did not neglect functions for sanitizing user-supplied data. These commands should always be used in combination with functions that execute shell commands.

escapeshellarg()

escapeshellcmd()

There is very little reason to pass user-supplied data into a shell command. Keep in mind that any data received from the client is considered user-supplied and tainted.

Loading Commands Remotely

Another quirk of PHP is the ability to include files in code from a URI. A web application's code is maintained in a directory hierarchy across many files group by function. A function in one file can access a function in another file by including a reference to the file that contains the desired function. In PHP the include, include_once, require, and require_once functions accomplish this task. A common design pattern among PHP application is to use variables within the argument to include. For example, an application might include different strings based on a user's language settings. The application might load 'messages_en.php' for a user who specifies English and 'messages_fr.php' for French-speaking users. If 'en' or 'fr' are taken from a URI parameter or cookie value without validation, then the immediate problem of loading local files should be clear.

PHP allows a URI to be specified as the argument to an include function. Thus, an attacker able to affect the value being passed into include could point the function to a site serving a malicious PHP file, perhaps something as small as this code that executes the value of URI parameter 'a' in a shell command.

<?php passthru($_GET[a])?>

Warning

PHP has several configuration settings like "safe_mode" that have been misused and misunderstood. Many of these settings are deprecated and will be completely removed when PHP 6 is released. Site developers should be proactive about removing deprecated functions or relying on deprecated features to protect the site. Check out the PHP 5.3 migration guide at http://us3.php.net/migration53 to see what will change and to learn more about the reasons for deprecating items that were supposed to increase security.

Read full chapter

URL:

https://www.sciencedirect.com/science/article/pii/B9781597499514000072