Showing posts with label Operating Systems. Show all posts
Showing posts with label Operating Systems. Show all posts

November 27, 2011


NachOS 3 Practical Presentation

This is our practical presentation, it contents Networking in nachOS and a program of sockets and encryption (out of NachOS).




Highlights of Client code (encryption) program

//First, you need to install the library libpurelibc1 to create sockets, you can find it in Ubuntu Software Center.

Including libraries ...






Creating sockets and connecting with Server...






Encrypting string ...




Highlights of Server code (encryption) program


Declarations ...



Socket creation and connection





Decrypting String




Reading, decrypting, and printing String ...




Links to some tutorials and the encryption code :



Encryption - decryption code


That's all, leave your comments...

November 21, 2011

Malware

Malware, short for malicious software, consists of programming (code, scripts, active content, and other software) designed to disrupt or deny operation, gather information that leads to loss of privacy or exploitation, gain unauthorized access to system resources, and other
In law, malware is sometimes known as a computer contaminant, for instance in the legal codes of several U.S. states, including California and West Virginia. The prevalence of malware as a vehicle for organized Internet crime, along with the general inability of traditional anti-malware protection platforms (products) to protect against the continuous stream of unique and newly produced malware, has seen the adoption of a new mindset for businesses operating on the abusive behavior. The expression is a general term used by computer professionals to mean a variety of forms of hostile, intrusive, or annoying software or program code.
Software is considered to be malware based on the perceived intent of the creator rather than any particular features. Malware includes computer viruses, worms, trojan horses, spyware, dishonest adware, scareware, crimeware, most rootkits, and other malicious and unwanted software or program. Internet: the acknowledgment that some sizable percentage of Internet customers will always be infected for some reason or another, and that they need to continue doing business with infected customers. The result is a greater emphasis on back-office systems designed to spot fraudulent activities associated with advanced malware operating on customers' computers. Malware is not the same as defective software, that is, software that has a legitimate purpose but contains harmful bugs. Sometimes, malware is disguised as genuine software, and may come from an official site. Therefore, some security programs, such as McAfee may call malware "potentially unwanted programs" or "PUP". Though a computer virus is malware that can reproduce itself, the term is often used
erroneously to refer to the entire category.

Purposes
Many early infectious programs, including the first Internet Worm and a number of MS-DOS viruses, were written as experiments or
pranks. They were generally intended to be harmless or merely annoying, rather than to cause serious damage to computer systems. In some cases, the perpetrator did not realize how much harm his or her creations would do. Young programmers learning about viruses and their
techniques wrote them simply for practice, or to see how far they could spread. As late as 1999, widespread viruses such as the Melissa virus and theDavid virus appear to have been written chiefly as pranks. The first mobile phone virus, Cabir, appeared in 2004. Hostile intent related to vandalism can be found in programs designed to cause harm or data loss. Many DOS viruses, and the WindowsExploreZip worm, were designed to destroy files on a hard disk, or to corrupt the file system by writing invalid data to them. Network-borne worms such as the 2001 Code Red worm or the Ramen worm fall into the same category. Designed to vandalize web pages, worms may seem like the online equivalent to graffiti tagging, with the author's alias or affinity group appearing everywhere the worm goes. Another strictly for-profit category of malware has emerged in spyware -- programs designed to monitor users' web browsing, display unsolicited advertisements, or redirect affiliate marketing revenues to the spyware creator. Spyware programs do not spread like viruses; they are, in general, installed by exploiting security holes or are packaged with user-installed software, such as peer-to-peer applications.

Backdoors

A backdoor is a method of bypassing normal authentication procedures. Once a system has been compromised (by one of the above methods, or in some other way), one or more backdoors may be installed in order to allow easier access in the future. Backdoors may also be installed prior to malicious software, to allow attackers entry. The idea has often been suggested that computer manufacturers preinstall backdoors on their systems to provide technical support for customers, but this has never been reliably verified. Crackerstypically use backdoors to secure remote access to a computer, while attempting to remain hidden from casual inspection. To install backdoors crackers may use Trojan horses, worms, or other methods.

Vulnerability to malware
In this context, as throughout, it should be borne in mind that the “system” under attack may be of various types, e.g. a single computer and operating system, a network or an application.

Various factors make a system more vulnerable to malware:
 Homogeneity: e.g. when all computers in a network run the same OS, upon exploiting one, one can exploit them all.
 Weight of numbers: simply because the vast majority of existing malware is written to attack Windows systems, then Windows systems, ipso facto, are more vulnerable to succumbing to malware (regardless of the security strengths or weaknesses of Windows itself).
 Defects: malware leveraging defects in the OS design.
 Unconfirmed code: code from a floppy disk, CD-ROM or USB device may be executed without the user’s agreement.
 Over-privileged users: some systems allow all users to modify their internal structures.
 Over-privileged code: some systems allow code executed by a user to access all rights of that user.

How to protect yourself from Malware?
Prevention is a vital point when our equipment to protect against possible infection of somekind of malware and for this there are three vital points:
  • Antivirus program.
  • A firewall program.
  • A "little" common sense.

if you want know more, check this links:
http://en.wikipedia.org/wiki/Malware
http://www.infospyware.com/articulos/que-son-los-malwares/

November 19, 2011

NachOS 3 - Theoretical part

Hi, here is our Practical presentation of NachOS 3.
We posted for extra points some information about networking and algorithms of encryption to complement our presentation.

We also had a post about cron and crontab.

We would like you to see our posts



TCP and UDP ports

Hi, now we are going to talk about ports in networking,

there are different ports in protocols TCP and UDP.

A port is an application - specific software construct serving as a communications endpoint in a computer's host operating system. A port is associated with an IP address of the host, as well as the type of protocol used for communication. The protocols that primarily use the ports are the Transport Layer (layer 4 of OSI model) protocols, such as the Transmission Control Protocol (TCP) and the User Datagram Protocol (UDP) of the Internet Protocol Suite.

A port is identified for each address and protocol by a 16-bit number, commonly known as the port number.

The operating system's networking software has the task of transmitting outgoing data from all application ports onto the network, and forwarding arriving network packets to a process by matching the packet's IP address and port number. Only one process may bind to a specific IP address and port combination using the same transport protocol. Common application failures, sometimes called port conflicts, ocurr when multiple programs attempt to bind to the same port numbers on the same IP address using the same protocol.

Applications implementing common services often use specifically reserved, well-known port numbers for receiving service request from client hosts. This process is known as listening and involves the receipt of a request on the well-known ports are defined by convention overseen by the Internet Assigned Numbers Authority (IANA).

Common port numbers

The IANA is responsible for the global coordination of the DNS Root, IP addressing and the other Internet protocol resources. This includes the registration of commonly used port numbers for well-known Internet services.

TCP and UDP ports




An example for the use of ports is the Internet mail system. A server using for sending and receiving email generally needs 2 services. The first service is used to transport email to and from other servers. This is accomplished with a Simple Mail Transfer Protocol (SMPT). The SMTP service application usually listens on TCP port 25 for incoming request. The second service is the Post Office Protocol (POP) wich is used by e-mail client applications on user's personal computers to fetch email messages from the server. The POP server listens on TCP port number 110. Both services mabe running on the same host computer, in which case the port number distinguishes the service that was requested by a remote computer, be it a user's computer or another mail server.

While the listening port number of a server is well defined, the client's port number is often chosen from the dynamic port range. In some applications, the client and the server each use specific port numbers assigned by the IANA. A good example of this is DHCP in wich the client always uses UDP port 68 and the server always uses UDP port 67.

Other example for the use of ports is administrate network equipment, when you need to enter in a equipment to administrate it, you can enter connecting physically or by telnet.
When you use telnet the computer uses port 23 to enter in the network equipment.

You can see more of ports in this webpage: http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers

Thats all!

November 17, 2011

VIRUS


What are computer viruses?

A computer virus is a program that can infect other programs by modifying them to cause damage in the event (delete or damage files) or affect performance or safety.

This software is a very serious threat, is spreading faster than it takes to fix it. Therefore it is necessary for users to stay informed about the virus to escape the ignorance that allowed them to grow up to be a serious problem.

What are the main types of PC viruses?

The first class includes those infected files attached to regular programs, though some can infect any. A direct action virus selects one or more programs to infect each time the program is executed. One resident is hiding somewhere in memory the first time an infected program is executed, and then infects other programs when they are executed.

The second category consists of those infected system files or boot sector. These viruses infect the system area on a disk. There are some that run when Windows starts, and viruses that directly infect the boot sector of hard disks, and may even permanently damage them. There are other viruses that modify the entries to the file table for the virus to run. Keep in mind that these can cause loss of data (files).


How is the virus transmitted?

The most common way viruses are spread is by file transfer, discharge or enforcement of mail attachments. Also you may encounter a virus just by visiting certain types of Web pages that use a component called ActiveX or Java applet. In addition, you may be infected by a virus just by reading an e-mail within certain types of e-mail programs like Outlook or Outlook Express.

What does a virus do?
When a virus carries out the action that had been created, is said to run the load can be quite malicious and try to cause irreparable damage to
computer files destroying, replacing / overwriting the master boot sector, blurring the contents of the hard disk or even writing about the BIOS, leaving the computer unusable. Most viruses do not erase all files on the hard drive. The reason for this is that once you delete the hard disk will remove the virus, thus ending the problem.

Why do people create viruses?

Some viruses are created by the challenge of creating a threat that is unique, not detectable, or simply devastating to its victim. The creator expects the virus to spread in such a way that makes you famous. The notoriety increased when the virus is considered such a threat that antivirus manufacturers have to design a solution.

How do I know if I have a virus?

Many viruses are advertised themselves by producing a sound or displaying a message, but it is also common for a virus shows no signs of their presence at all. Viruses behave in different ways and there is no absolute indicator sign to remind you of their presence, an updated antivirus program is the only one who can tell us if you have an infection.


Now we will explain some of the viruses and what damage they do


Virus: Happy99
Sent by mail program opens a window with fireworks. Manipulate Internet connectivity.

Virus: WinWord.Concept
Macro virus that infects the Normal.dot template. Message pops up on screen and Word malfunction.

Virus: FormatC
Trojan that infects the Word, when you open an infected file formats the hard drive.

Virus: VBS / Bubbleboy
Trojan is executed without opening an attachment (attachment), and is activated immediately after the user opens the mail. It creates serious problems.

Virus: I-Worm.Nimda
The virus arrives via e-mail attachment via "README.EXE" in an attached file, the message apparently empty but contains malicious code that exploits an exploit in Outlook and Outlook Express without upgrading (routine that uses the weakness of the system) to run the virus only display the message. When run it copies itself to the system directory under the name load.exe. It also replaces the library riched20.dll modifying itself to be loaded as a DLL. This DLL is used by other applications that work with Richedit Text Format such as Wordpad. To get into the computer the virus uses a well-known Windows vulnerability (from 29/03/2001) that allows the attachment of a message is automatically executed when reading the message.

Virus: W32/Frethem.J
Worm that spreads quickly via email with a message easy to recognize because its subject: Re: Your password!. Furthermore, the message includes the decrypt-password.exe file. Thus, the author of the worm tries to fool the recipient thereof to execute the attached file, thinking it contains a password that supposedly can access relevant information.

Virus: W32.Opaserv.Worm
It is a worm that spies on the network and tries to replicate resources shared by multiple network users. It copies itself to the file "scrsvr.exe" on the remote machine. The worm also tries to download updates www.opasoft.com direction, although the website has already been closed. Indicators of infection can include:
The existence of scrsout.dat scrsin.dat and in the root directory C: indicating local infection (the worm has been executed on the local machine)
The existence of tmp.ini in the root directory C: indicates remote infection (infected by a remote server)
The registry key HKLM \ Software \ Microsoft \ Windows \ Current Version \ Run contains a string value called ScrSvrOld ScrSvr or set to C: \ tmp.iniro


Virus: Win32.Worm.Benjamin

When the infected file is executed by this worm, it generates a lot of files like *. exe and *. scr names of movies, music and software applications in the Windows \ Temp \ sys32. If you installed the Kazaa shared folder change the program to C: \ Windows \ Temp \ sys32 so that if a network user find a file with a name similar to the names generated by the worm downloads a file infected. executables (bat, exe, scr).

Virus: W32/Choke.worm (Shoot)
MSN Messenger Worm Microsoft, also known as President Bush. The worm arrives via MSN Messenger, as a Visual Basic. The file name may vary but will always have the extension. EXE. When this file is executed, the worm displays a window like this: This program Choke Needs Flash 6.5 to run! [OK]. When executed, the worm can send itself to users of MSN that you discuss with the infected user.

Virus: W32.Bugbear @ mm
Alias: WORM_BUGBEAR.A, W32/Bugbear @ MM, I-Worm.Tanatos, W32/Tanat, I-Worm.Bugbear, NATOSTA.A, Win32.BugBear.A @ mm @ mm W32/Bugbear.A
It is a mass-mailing worm e-mail can also spread through network shares. It has backdoor capabilities that allow remotely control the infected system. In addition, several processes interrupts antivirus and firewall applications. It is written in Microsoft Visual C / C + + and compressed with UPX.

Bibliography:

November 15, 2011

Encryption algorithms


What is encryption?

All encryption is based on an algorithm, the function of this algorithm is basically encode the information to be indecipherable at first sight. An encryption algorithm can transform the letter "A" to "5x5mBwE" or to "xQE9fq" and the work of an encryption algorithm is precisely determine how information will be transformed from its original state to one that is difficult to decode. The encryption and decryption algorithms uses what is called key to encrypt or decrypt information. These keys are used to encrypt information, however, there is another key that the person who receives the message knows, and it is through this unique key that the message can be decrypted.




What function does the key have?

There are two types of keys ("keys"), but the Internet's most widely used is called "public key" or asymmetric algorithm. The name "public" comes from its operation: there is a public key that is made known to anyone (all Internet) who so desires, this public key is used to encrypt information, however, there is another key that the person who receives the message knows, and it is through this unique key that the message can be decrypted.


Digital Signatures 

A digital signature uses the same function as "public key" or asymmetric algorithm mentioned above.
As mentioned, there is a "public key" and a "secret key" in the case of digital signatures public key is widely known is able to identify whether the information comes from a reliable source. In other words, the public key will be able to recognize whether the information actually comes from the "secret key" in question.


Now we will talk about the algorithms that we saw in class




The RSA cryptosystem
Of all asymmetric algorithms, RSA is the most used and perhaps the easiest to understand and implement. A peculiarity of this algorithm is that two keys are used interchangeably for both encrypt and authenticate. It was named after its three inventors: Ron Rivest, Adi Shamir and Leonard Adleman, who first published in 1977, the RSA method. Patent has been under RSA Laboratories until September 20, 2000, so their commercial use was restricted to that date.

The RSA algorithm

Key pair generation
To generate a key pair (KP, KP), we first randomly choose two large prime numbers p and q (approximately 200 numbers each, for example). Then the product n = calculated p.q
Now choose a number e relatively prime to (p-1) and (q-1). This pair of numbers (e, n) can be known by anyone, and constitute the so-called public key
and therefore must have an inverse module (p-1) (q-1), which we call d. Of course it is true that ed ≡ 1 mod ((p-1) (q-1)), which is the same as saying that ed = 1 + k (p-1) (q-1) for some integer k. The private key is the pair (d, n). This number d is kept secret and will only be known by the owner of the key pair.


Encrypt the message with the public key
It should be noted that this algorithm the messages are encrypted and decrypted integers smaller than n, not individual letters as in the case of Caesar and Vigenere ciphers.
To obtain the encrypted message C from clear message M, it performs the following operation:
C = I (mod n)


Decrypt the message with the private key
To recover the original message from the encryption is performed the following operation:
M = Cd (mod n)


Justification of the method
Cd (mod n) = (I) d (mod n) = M1 + k (p-1) (q-1) (mod n) = (M (p-1) (q-1)) kM (mod n ) [i]
vou recall, the Euler function φ (n) = (p-1) (q-1), and in general, but unlikely chance, you will have that gcd (M, p) = gcd (M, q) = gcd (M, n) = 1. And therefore according to the Euler-Fermat theorem, Mφ (n) ≡ 1 (mod n) ⇒ (M (p-1) (q-1)) k ≡ 1 (mod n) [ii]

In [i] and [ii] we obtain that Cd (mod n) = 1.M (mod n) = M, for 0


Commutativity of RSA encryption and decryption
For the properties of modular exponentiation, encryption and decryption are commutative:
M = (I mod n) d mod n = Md.e mod n = (Md mod n) e mod n = M
This means that if encrypting M with public key e and then decrypting the result with the Private M d get back, we can also encrypt M with private key d to decrypt the result with the public key and, returning to obtain M. This property is important because it allows us not only to use RSA to encrypt a message, but also to authenticate the message, as discussed in the next topic.


Cryptanalysis of RSA
To break RSA encryption, you can try several ways. In addition to factor n, we know that is a computationally intractable problem in a reasonable time, we could try to calculate φ (n) directly, or try a brute force attack trying to find the private key d, systematically testing each possible numbers of the key space. Both attacks are, for large n, even more computationally expensive than factoring n. own


DES cryptosystem
The encryption algorithm DES (Data Encryption Standard) is the most used in the world. Although its strength has been weakened by the creation of a $ 220,000 machine that breaks this code, continue to be used for several years thanks to a version that extends the life of this algorithm: the "Triple DES." This work complements an implementation in C language, learn how the DES. The operation of the Triple DES is a simple variant of DES, so it does not fully explain its operation. The purpose of explaining this algorithm is that a lot of other encryption algorithms use the same principles as the DES. By understanding the changes that occur in the DES, it is easier to understand the latest algorithms.


Preliminary Example
DES works by encrypting groups of 64 bits, ie, over 16 hexadecimal numbers. To make the encryption, DES keys are apparently uses 64-bit. However, every eighth bit is ignored, so the key is 56 bits effective. In any

case, 64 bits are the number around which to organize the DES. Take this first example, if we encrypt the text "8787878787878787" with the DES key "0E329232EA6D0D73" get the encrypted text "0000000000000000". The reverse process (decrypt) with the same key result gives us the original text: "8787878787878787".


This example is simple because our text measures exactly 128 bits. But most of the messages will be measured in 64-bit or a multiple of this number. For these cases, you must fill with zeroes up to a multiple of 64 bits.


DES works in detail
DES is a block cipher, which means working in a given text block size (in this case 64 bits) and returns blocks of the same size. Thus DES results in a permutation of the 264 possible distributions of those 64 bits. Each block of 64 bits is divided into two blocks of 32 bits each, called L and R (left and right by the acronym in English.) This division is used in certain operations.
Let M be the main message M = 0123456789ABCDEF where M is in hex format. By changing M to binary we get the block of 64 bits:
M = 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
L = 0000 0001 0010 0011 0100 0101 0110 0111
R = 1000 1001 1010 1011 1100 1101 1110 1111
DES operates on the 64-bit blocks using 56-bit keys. Both keys are stored as if using 64-bit but every eighth bit is ignored. That is, bits 8, 16, 24, 32, 40, 48, 56 and 64. However, we will continue calling to bits 1 to 64. 

The remaining bits will be eliminated when we sub keys.



Suppose that K is the key K = 133457799BBCDFF1 hexadecimal. Transforming a binary notation (1 = 0001 3 = 0011, etc..) And grouping every 8 bits, we see that the last bit will not be used:
K = 00010011 00110100 10011011 10111100 01010111 01111001 11011111 11110001


Diffie Hellman Cryptosystem
The Diffie-Hellman algorithm was the first public key algorithm invented. This significant that their authors are also the owners of the idea. The algorithm can be used for key distribution, but not to encrypt or decrypt

messages. Your safety lies in the difficulty of computing discrete logarithms in a finite field compared to the ease of performing exponentiation is in the same field. If you were left confused by all this, do not worry.


The problem of key distribution.

The problem of key distribution is whether it was first the chicken or the egg. If two people want to exchange secret messages, they need to encrypt messages. To encrypt and decrypt, you need a secret key. As this key also needs to be transmitted should be encrypted with another key, and so on indefinitely.

A fairly simple way to solve the problem of the keys is to use locks. Say you want to send a message Antonio Belen. She places the message in a metal box, closes the box with a lock (only she holds the key to this lock) and sent them to Bethlehem. Belen also puts a lock on the box (only he has the key of the second lock) and returns the box to Antonio. Upon receiving the box, Antonio opens and removes his padlock and again sent the case to Belen. Now, Belen can remove your lock, open the box and read the message. Perfect scheme? Almost ...


Mathematical functions


If mathematical functions necessary to encrypt a message had to perform at the locks, the solution found by Belen and Antonio would be perfect. Unfortunately, this is not the case math functions need to be "retired" in the reverse order that they were "placed", which is not necessary when it comes to locks. Despite this, this was the starting point used by Diffie and Hellman. Most mathematical functions are easily reversible, and for this reason, function calls can be bidirectional. A multiplicative function is reversible, easy to solve and an excellent example. Say f (x) = 2x. In this case, if x = 3, then f (x) = 2 x 3 = 6. Knowing the function x can be calculated quickly, regardless of the size of the result of the function. For example, if f (x) = 1000, we can make the account and get head at x = 500. So far, nothing special. Diffie and Hellman happen that they were concentrating efforts on the search for a one-way function. We can define a one-way function as a function has no return (this would be the true one-way function) or whose turn it is so difficult or so slow that, in practice, the return is not feasible. At the beginning of 1976, Hellman was considering an axiom that has existed for several hundred years. The idea was to use the function in the form of g


Diffie-Hellman algorithm

x (mod n)

To make the magic work, there were some restrictions:

g (base) needs to be less than n (the module)
and g needs to be greater than 1.
To get the keys, Belen and Antonio can exchange information freely, without the slightest concern with someone who is present or will eventually be intercepting this information. In just 4 steps, the two have a secret key.


Cryptosystem Hill
This system is based on linear algebra and has been important in the history of cryptography. It was invented by Lester S. Hill in 1929 and was the first system that was practical cryptographic polyalphabetic to work with more than three symbols simultaneously.
This system is polyalphabetic because it might be that same character in a message to send is encrypted in


two different characters in the encrypted message. Assuming that we work with an alphabet of 26 characters. The letters are numbered in alphabetical order so that A = 0, B = 1, ... , Z = 25


They choose an integer d d blocks determines which elements are treated as a vector of dimensions.
It chooses a random d × d matrix elements which will be the key to use.
The elements of the matrix of d × d be an integer between 0 and 25, plus the matrix M must be invertible in.
For encryption, the text is divided into blocks of d elements which are multiplied by the matrix d × d
All arithmetic operations are performed in the form module 26, ie 26 = 0 27 = 1, 28 = 2and so on.
Given a message to encrypt the message we take blocks of "d" characters and apply:
Pi = M × C, where C is the encryption code for the message Pi cryptanalysis
Hill system poses many problems cryptanalysts greater than those posed 'CAESAR'. To start the key space is much greater in this case is 4C25, ie permutations of 4 elements taken from among 25 possible. And using a matrix larger the number of possible keys can be made ​​as large as necessary to make it impossible to brute force attack.


Cron and Crontab

What is cron?

Cron is a time-based job scheduler in Unix-like computer operating systems. Cron enables users to schedule jobs (commands or shell scripts) to run periodically at certain times or dates. It is commonly used to automate system maintenance or administration, though its general-purpose nature means that it can be used for other purposes, such as connecting to the Internet and downloading email.

In the terminal we can search for its commands, just write this in your terminal: man cron.


Cron is a service or daemon that needs to be started only once, usually it starts with the operating system boot. The cron daemon is called crond. We can prove that the cron daemon is started at the boot, typing this in the terminal:

#> /etc/rc.d/init.d/crond status
#> /etc/init.d/crond status                //Use either of this two lines depending on the distro

      crond (pid 507) is running...


Or use this line if you have the command “service” installed:

#> service crond status
crond (pid 507) is running...


You can also check it through the ps command:


# ps -ef | grep crond


If for some reason, cron isn’t not working:


#> /etc/rc.d/init.d/crond start
Starting crond: [ OK ]

If the service wasn’t configured to boot from the start, would be sufficient to add it with the chkconfig command:

#> chkconfig --level 35 crond on

With this you would be adding it to the runlevel 3 and 5, to start at system boot time.


What Is Crontab?


A crontab file contains instructions to the cron daemon of the general form: "run this command at this time on this date"

Each user can create his own crontab.

On Wikipedia you can find how to make a crontab, below we provide the link

http://es.wikipedia.org/wiki/Cron_(Unix)

Also here is an example of a crontab:


http://unixhelp.ed.ac.uk/CGI/man-cgi?crontab+5

Sources:


http://es.wikipedia.org/wiki/Cron_(Unix)
http://unixhelp.ed.ac.uk/CGI/man-cgi?crontab+5

November 6, 2011

2nd Practical

Practical Part - NachOS 2

PRACTICAL PART - NACHOS 2

To test our programs of paging/swaping algorithms, page table and TLB, we need to make user programs.
To run user programs we need system calls (syscalls are the interface between the OS and user programs), so here is the work that we made to run user programs.

Step 1. Code Assignment

For the system to be able to identify each call is assigned an integer to each.
The statement of system calls is on file: userprog/syscall.h


We add these lines:
#define SC_Cuadrado   22;   /*Obviously the number of syscalls can't repeat*/ 
#define SC_Duplicar 23;

2. Declaration of prototype


To perform the compilation of the user program we must to have the prototype of function to call in the user space.This statement of name, parameters and return of functions is on the file :
userprog/syscall.h

We include the statement of "Cuadrado" and "Duplicar" at the end of file, before the logical end(#endif).

We add these lines:

/* Retorna el cuadrado del valor entregado */
Int Cuadrado(int x);
/* Retorna el cuadrado del valor entregado */
int Duplicar(char* origen, char* destino);


Step 3. Implementation of the trap

In nachOS the trap of the kernel (the passing of control from the user program to the system) must be done in machine language for the MIPS processor simulated.

The file to edit is : test/start.s

We add these lines:

.globl Cuadrado
.ent
Cuadrado
Cuadrado:
addiu $2,$0,SC_Cuadrado
syscall
j
$31
.end Cuadrado
.globl Duplicar
.ent
Duplicar
Duplicar:
addiu $2,$0,SC_Duplicar
syscall
j
$31
.end Duplicar

//Sorry syntax highlighter doesn't work with assembler


Here is an image of the code, cause the spaces in the code are important, so try to copy it exactly like in the image, the large spaces are TAB





In the past lines we declare the implementation in assembler of funtions "Cuadrado" and "Duplicar". This implementation copy to register #2 code of syscall that is calling , then performed over control from the user to the system program to return to the instruction that is next in user program.

(In the MIPS processors the code calls the system is always stored in the register #2 for kernel space recovery)

Step 4. Receiving the syscall in kernel space

NachOS provides a single point of entry to the kernel form user programs. This file is in : userprog/exception.cc in ExceptionHandler function.

This handles syscalls, pagefaults, failures invalid address and instructions.

For the syscall "Cuadrado" and "Duplicar" should add the following code within the switch / case of syscalls:

/* I think that you dont have the switch(which),
i have nachOS 3.4 and this switch doesnt exist so
i implemented it.
*/

void ExceptionHandler(ExceptionType which)
{
int type = machine->ReadRegister(2);
switch(which){
case SyscallException:
switch(type){

case SC_Halt:
DEBUG('a', "Shutdown, initiated by user program.\n");
interrupt->Halt();
break;
case SC_Exec:
vaddr = machine->ReadRegister(4);
DEBUG(dbgSysCall,"System Call: Exec vaddr=" << vaddr);
returnval = ExecHandler(vaddr);
break;

case SC_Cuadrado:
vaddr = machine->ReadRegister(4);
DEBUG(dbgSysCall,"System Call: Cuadrado valor=" << vaddr);
returnval = CuadradoHandler(vaddr);
break;
case SC_Duplicar:
vaddrOrigen = machine->ReadRegister(4);
vaddrDestino = machine->ReadRegister(5);
DEBUG(dbgSysCall,"System Call: Duplicar vaddrOrigen=" <<
vaddrOrigen << " vaddrDestino=" << vaddrDestino );
returnval1 = DuplicarHandler(vaddrOrigen, vaddrDestino);
break;
default:
printf("Unexpected user mode exception %d %d\n", which, type);
ASSERT(false);
}//Fin de 2do switch
}//Fin de 1er switch

}//Fin de ExceptionHandler

In the case SC_Duplicar virtual addresses are recovered where the 2 Strings from the registry #4 and #5 respectively and the handler is invoked.

Step 5. Call Handling implementation

On receipt of the syscall in the past step we make the function calls "CuadradoHandler" and "DuplicarHandler" . These are the functions that actually implement the actions you must perform each syscall.

To CuadradoHandler implementation is:

// Retorna el cuadrado del valor entregado
//--------------------------------------------------------------------
int CuadradoHandler(int numero)
{
return (numero*numero);
}


To DuplicarHandler implementation is:

//DuplicarHandler implementation

int DuplicarHandler(int vOrigen, int vDest)
{
char* origen = new char[MaxStringArgLength];
char* destino = new char[MaxStringArgLength];
int len = 0;
// se limpia el buffer origen y destino
bzero(destino, MaxStringArgLength);
bzero(origen, MaxStringArgLength);
// recuperacion del string desde espacio de usuario a espacio de kernel
if ((len = kernel->currentThread->space->UserStringToKernel(vOrigen,origen)) < 0) {
return -1;
}
// copiamos la primera vez el string
strcpy(destino, origen);
// segunda vez
strcpy(destino+len-1, origen);
// luego debemos pasar el string resultado al espacio de usuario
if (kernel->currentThread->space->KernelToUserBuf(vDest, MaxStringArgLength,
destino)) {
return -1;
}
return MaxStringArgLength;
}

In the tutorial that we followed don't tell us where put these functions("CuadradoHandler and DuplicarHandler"), but we assume that these functions must to be in userprog/exception.cc cause right there calls system are handled :)

Step 6. Inclusion in the user program

The inclusion of syscalls in a user program has 2 parts. The first is the programming, and the second is the modification of test directory makefile to include the headers syscalls.

A basic user program to call both syscalls and print in screen the results is:

#include "syscall.h"
#include "io_lib.h"
int main() {
char destino[256];
printInt(Cuadrado(10));
Duplicar("hola", destino);
print(destino);
Halt();
}


Finally we must to edit the file /test/Makefile to add our program.

Here is a image to guide how you can do it:



This file called Makefile indicates which files must be compiled at moment to do "make".

Now just "make" at .../nachos/code/ and if there aren't errors you can do "./nachos" in /nachos/code/test

We had problems with the function ExceptionHandler so we had 2 errors, here is an image:





Well if you don't have problems the output of execution must be like this:


"(This image is from the tutorial that we followed)"




That's all, all your questions write it in comments please :).

September 14, 2011

NachOS code.


This is our code that we implement in nachos, we made the bounded buffer producer-consumer code. We put our code in threadtest.cc file, this file is located in nachos/code/threads.

Our code is the next:

//PRODUCER FUNCTION

void Producer(void* id){
char* name = (char*)id;
while (i<=30){ empty -> P();
Sem -> P();
Producto++;
printf("%s - %d\n", name, Producto);
Sem -> V();
full -> V();
i++;
}
}



//CONSUMER FUNCTION

void Consumer(void* id){
char* name = (char*)id;
while(i<=20){ full -> P();
Sem -> P();
Producto --;
printf("%s - %d\n", name, Producto);
Sem -> V();
empty-> V();
i++;
}
}


//START FUNCTION

void start(){
//Initialize semaphores
Sem = new Semaphore("Sem",1);
empty = new Semaphore("empty",5);
full = new Semaphore("full",0);


Thread *t = new Thread("Producer");

t -> Fork(Producer,(void*) "Producer ");

t = new Thread("Consumer");
t -> Fork(Consumer, (void*) "Consumer");
}



//THREADTEST FUNCTION
/*
This function is implementing in nachos by default,
we just put the name of our method "start" to call it.
*/

void
ThreadTest()
{
DEBUG('t', "Entering SimpleTest");

for ( int k=1; k<=10; k++) { char* threadname = new char[100]; sprintf(threadname, "Hilo %d", k); Thread* newThread = new Thread (threadname); newThread->Fork (SimpleThread, (void*)threadname);
}
start(); //We agregate this line to call our method
SimpleThread( (void*)"Hilo 0");
}

Practical Presentation

Practical Presentation

August 18, 2011


Instaling Nachos on Ubuntu 11.04

Hi everybody, this is the first activity, im going to explain how my team and i installed Nachos on Ubuntu 11.04.

The version of nachos that we installed was Nachos ulpgc :S (i'm not sure about which version of Nachos we installed,cause the name of the folder is just nachos, but in the README file I found that is Nachos 3.1).

If you want see the version of Nachos that we installed, here is the link:
http://sopa.dis.ulpgc.es/so/practica/nachos/nachos-ulpgc.tgz



Programming Language.

The language that we will use is C++.
We don't have experience in C++ but we will learn a lot in this proyect.


Instalation.

We installed Nachos following the steps of this tutorial:
http://sopa.dis.ulpgc.es/wiki/index.php/Instalaci%C3%B3n_de_Nachos
(Thank you to Saul for post this link in piazza :p )

We installed Nachos on ubuntu 64 bits, so we had to edit some lines of the /nachos/code/Makefile.dep file.

All is included in the tutorial that mentioned previously.


This is the output of the command "make":






This is the output of command ./nachos (in the folder thread, inside folder code)




I hope this tutorial has helped you, if you have a question put in comments.
Thanks to everyone who see this post :) .