Leaderboard
Popular Content
Showing content with the highest reputation on 01/04/19 in all areas
-
Salutare Guys, Cum se mai intampla sa te plictisesti in concediu, am facut azi, un script in python cu care poti descarca melodii de pe Tidal (https://tidal.com). Tidal este un serviciu de streaming online asemanator Spotify, doar ca are o calitate net superioara: HI-FI - 44.1 kHz/16 bit flac si mp4 si Master - 96 kHz/24 bit (MQA) - flac . Daca ai niste scule decente (fie ca e vorba de casti sau un sistem) e must have! Povestea a inceput de la nevoia de a descarca niste melodii pentru a le asculta offline, si cum nu am gasit nimic functional, am decis sa scriu eu aceasta aplicatie. Si m-am gandit sa impartasesc cu voi! Dependinte (e posibil sa imi fi scapat cateva): pip install tidalapi Unidecode ffmpeg - trebuie sa fie in system path Testand jucaria am gasit un bug in tidalapi: in cazul in care o melodie nu are relese date, va crapa, este un caz extrem de rar, si se intampla inspecial la unele melodii vechi. Daca iti place doar muzica noua si foarte comerciala cu siguranta nu ai neaparat nevoie de acest fix. # fix in tidalapi: # edit __init__.py # from line 224 # change: # if 'releaseDate' in json_obj: # try: # kwargs['release_date'] = datetime.datetime(*map(int, json_obj['releaseDate'].split('-'))) # except ValueError: # pass # return Album(**kwargs) # with: # if 'releaseDate' in json_obj: # if json_obj['releaseDate'] is None: # json_obj['releaseDate'] = '2008-10-14' # try: # kwargs['release_date'] = datetime.datetime(*map(int, json_obj['releaseDate'].split('-'))) # except ValueError: # pass # return Album(**kwargs) Salvati codul intr-un fisier .py, si rulati-l. Apropo, caile catre fisierele salvate/creerea de directoare este hardcodata in format *nix, deci nu va asteptati sa va mearga pe windoza fara mici finisaje. Este scris si testat in Python 2,7 (defaultul la macOS Majave) dar am cautat sa il tin compatibil si cu Python 3.x (sper ca mi-a iesit). # -*- coding: utf-8 -*- # RST Tidal MP4 Downloader by Cheater v1.0 (https://rstforums.com) # All tracks will be download in PCM (MPEG AAC Audio coded, MP4A) at 44100 Hz/16 bits, 320 kbps and stored in MP4 container # requirements: # pip install tidalapi Unidecode # ffmpeg # tidalapi has a bug, so if some album/playlist contains one song with no date, it will exit, this is very rare, however, there is some workaround. # fix in tidalapi: # edit __init__.py # from line 224 # change: # if 'releaseDate' in json_obj: # try: # kwargs['release_date'] = datetime.datetime(*map(int, json_obj['releaseDate'].split('-'))) # except ValueError: # pass # return Album(**kwargs) # with: # if 'releaseDate' in json_obj: # if json_obj['releaseDate'] is None: # json_obj['releaseDate'] = '2008-10-14' # try: # kwargs['release_date'] = datetime.datetime(*map(int, json_obj['releaseDate'].split('-'))) # except ValueError: # pass # return Album(**kwargs) import tidalapi import os import subprocess import errno import shlex from aigpy.cmdHelper import myinput from subprocess import Popen, PIPE, STDOUT from random import randint from time import sleep import unidecode # compatibility workaround for py27/py3 try: from subprocess import DEVNULL # py3k except ImportError: import os DEVNULL = open(os.devnull, 'wb') # fill this with your tidal user and pass tidalUser = '' tidalPass = '' cwd = os.getcwd() config = tidalapi.Config() # using HIGH quality in order to get mp4's unencrypted url instead of enctyped flac config.quality = 'HIGH' session = tidalapi.Session(config) session.login(tidalUser, tidalPass) def getTidalTrackUrl(track_id): try: url = session.get_media_url(track_id) return url except: # in case we need to retry we add a random sleep, in order to worckaround bot detection sleep(randint(1,10)) print('Tidal responds with 401. Retrying track url discovery for track id: ' + str(track_id)) generatePlaylistTrackUrl(track_id) def downloadAlbum(): while True: print("----------------ALBUM------------------") sID = myinput("Enter AlbumID(Enter '0' go back) :") if sID == '0': return tracks = session.get_album_tracks(album_id=sID) queue = [] for track in tracks: trackNo = str(tracks.index(track) + 1) # don't try to download unavailable track, it will fail if track.available is False: continue # replace utf-8 diacritics with ascii equivalent, and cleanup " and ' from album/artist/track name trackName = unidecode.unidecode(track.name).replace('"', '').replace("'", "") artistName = unidecode.unidecode(track.artist.name).replace('"', '').replace("'", "") albumName = unidecode.unidecode(track.album.name).replace('"', '').replace("'", "") print('Adding to queue: ' + artistName + ' - ' + albumName + ' - ' + trackNo + '.' + trackName) # create dw directory and subdirs if it not exits if not os.path.exists(cwd + '/tidalDownloaded/' + albumName): os.makedirs(cwd + '/tidalDownloaded/' + albumName) cmd = 'ffmpeg -y -i "rtmp://' + getTidalTrackUrl(track.id) + '" -acodec copy "' + cwd + '/tidalDownloaded/' + albumName + '/' + trackNo + '.' + artistName + ' - ' + trackName + '.mp4"' queue.append(cmd) print('All track has been added to queue successfully. Download begins....') processes = [] for cmd in queue: p = subprocess.Popen(shlex.split(cmd), shell=False, universal_newlines=True, stdout=DEVNULL, stderr=subprocess.STDOUT) processes.append(p) print('All tracks download is in progress. Please wait....') # wait for all started ffmpeg processes to be finished for p in processes: if p.wait() != 0: print("There was an error") print("Finished. All tracks has been download successfully!") return True def downloadPlaylist(): while True: print("----------------PlayList------------------") sID = myinput("Enter PlayList(Enter '0' go back) :") if sID == '0': return playlist = session.get_playlist(playlist_id=sID) tracks = session.get_playlist_tracks(playlist_id=sID) queue = [] for track in tracks: trackNo = str(tracks.index(track) + 1) # don't try to download unavailable track, it will fail if track.available is False: continue # replace utf-8 diacritics with ascii equivalent, and cleanup " and ' from playlist/artist/track name playlistName = unidecode.unidecode(playlist.name).replace('"', '').replace("'", "") trackName = unidecode.unidecode(track.name).replace('"', '').replace("'", "") artistName = unidecode.unidecode(track.artist.name).replace('"', '').replace("'", "") print('Adding to queue: ' + playlistName + ' - ' + trackNo + '.' + artistName + ' - ' + trackName) # create dw directory and subdirs if it not exits if not os.path.exists(cwd + '/tidalDownloaded/' + playlistName): os.makedirs(cwd + '/tidalDownloaded/' + playlistName) cmd = 'ffmpeg -y -i "rtmp://' + getTidalTrackUrl(track.id) + '" -acodec copy "' + cwd + '/tidalDownloaded/' + playlistName + '/' + trackNo + '.' + artistName + ' - ' + trackName + '.mp4"' queue.append(cmd) print('All track has been added to queue successfully. Download begins....') processes = [] for cmd in queue: p = subprocess.Popen(shlex.split(cmd), shell=False, universal_newlines=True, stdout=DEVNULL, stderr=subprocess.STDOUT) processes.append(p) print('All tracks download is in progress. Please wait....') # wait for all started ffmpeg processes to be finished for p in processes: if p.wait() != 0: print("There was an error") print("Finished. All tracks has been download successfully!") return True while True: print(" RST Tidal MP4 Downloader by Cheater v1.0 (https://rstforums.com)") print("=====================Choice=========================") print(" Enter '0' : Exit") print(" Enter '1' : Download Album.") print(" Enter '2' : Download PlayList.") print("====================================================") print("All tracks will be download in PCM (MPEG AAC Audio coded, MP4A) at 44100 Hz/16 bits, 320 kbps and stored in MP4 container") choice = myinput("Choice:") if choice == '0': quit() elif choice == '1': downloadAlbum() elif choice == '2': downloadPlaylist() Ce stie sa faca? 1. Poti descarca un album 2. Poti descarca un playlist 3. Adauga melodiile intr-o coada, si le descarca simultan pentru a scurta timpul de asteptare semnificativ. Daca aveti intrebari sau nu va descurcati puteti scrie aici, si va voi ajuta in limita timpului disponibil (adica sper sa nu fie nevoie :))) ). PS: Fiti blanzi cu code review, sunt programator si python nu este specialitatea mea, este al 2-lea script scris in python si prima interactiune am avut-o in decembrie. PS2: Distractie si La multi ani! PS3: Feel free to improve it! Later: Am gasit un tool functional de download scris de altcineva (daca il gaseam mai repede probabil ca nu il mai scriam eu pe asta, deci nu e neaparat bine): https://github.com/redsudo/RedSea acest tool spre deosebire de ce am scris eu, stie de si decripteze flacurile, astfel poate descarca inclusiv MQA de 92k / 24bit (cea mai intalta calitate disponibila pe tidal), si flac 44.1k / 16bit cu un bitrate de 1.411 kbps. Decriptarea nu e rocket sience, dar cu siguranta a fost nevoie de un reverse engineering serios pentru aflarea algoritmului si key de criptare (AES cu key binara, tinuta in base64 in cod).4 points
-
GG pentru initiativa. Vad ca ai ceva timp pe forumu' asta si eu intru din ce in ce mai rar. Am incercat sa dau c/p intr-uun IDE sa bag cateva imbunatatiri da' sa-mi bag pula daca nu mai mult m-am enervat. Daca vrei sa faci ceva cum trebe' pentru forum (chiar daca spui ca ii facut asa intr-o doara in conced), fa si tu un commit pe git sau ce folosesti tu, pune un link aici, alege o versiune de Python recenta nu ceva care o sa fie deprecated maine poimaine. Ca mai vine azi unu' cu un edit, maine altu' cu un issue, si pac te trezesti cu meleonu' de la Dragnea care iti cumpara aplicatia si o baga pe RATB. Pwp & no homo2 points
-
Every day we see a bunch of new Android applications being published on the Google Play Store, from games, to utilities, to IoT devices clients and so forth, almost every single aspect of our life can be somehow controlled with “an app”. We have smart houses, smart fitness devices and smart coffee machines … but is this stuff just smart or is it secure as well? Reversing an Android application can be a (relatively) easy and fun way to answer this question, that’s why I decided to write this blog post where I’ll try to explain the basics and give you some of my “tricks” to reverse this stuff faster and more effectively. I’m not going to go very deep into technical details, you can learn yourself how Android works, how the Dalvik VM works and so forth, this is gonna be a very basic practical guide instead of a post full of theoretical stuff but no really useful contents. Let’s start! Prerequisites In order to follow this introduction to APK reversing there’re a few prerequisites: A working brain ( I don’t give this for granted anymore … ). An Android smartphone ( doh! ). You have a basic knowledge of the Java programming language (you understand it if you read it). You have the JRE installed on your computer. You have adb installed. You have the Developer Options and USB Debugging enabled on your smartphone. What is an APK? An Android application is packaged as an APK ( Android Package ) file, which is essentially a ZIP file containing the compiled code, the resources, signature, manifest and every other file the software needs in order to run. Being it a ZIP file, we can start looking at its contents using the unzip command line utility ( or any other unarchiver you use ): unzip application.apk -d application Here’s what you will find inside an APK. /AndroidManifest.xml (file) This is the binary representation of the XML manifest file describing what permissions the application will request (keep in mind that some of the permissions might be requested at runtime by the app and not declared here), what activities ( GUIs ) are in there, what services ( stuff running in the background with no UI ) and what receivers ( classes that can receive and handle system events such as the device boot or an incoming SMS ). Once decompiled (more on this later), it’ll look like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <?xml version="1.0" encoding="utf-8" standalone="no"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.company.appname" platformBuildVersionCode="24" platformBuildVersionName="7.0"> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name="com.company.appname.MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> </manifest> Keep in mind that this is the perfect starting point to isolate the application “entry points”, namely the classes you’ll reverse first in order to understand the logic of the whole software. In this case for instance, we would start inspecting the com.company.appname.MainActivity class being it declared as the main UI for the application. /assets/* ( folder ) This folder will contain application specific files, like wav files the app might need to play, custom fonts and so on. Reversing-wise it’s usually not very important, unless of course you find inside the software functional references to such files. /res/* ( folder ) All the resources, like the activities xml files, images and custom styles are stored here. /resources.arsc ( file ) This is the “index” of all the resources, long story short, at each resource file is assigned a numeric identifier that the app will use in order to identify that specific entry and the resources.arsc file maps these files to their identifiers … nothing very interesting about it. /classes.dex ( file ) This file contains the Dalvik ( the virtual machine running Android applications ) bytecode of the app, let me explain it better. An Android application is (most of the times) developed using the Java programming language. The java source files are then compiled into this bytecode which the Dalvik VM eventually will execute … pretty much what happens to normal Java programs when they’re compiled to .class files. Long story short, this file contains the logic, that’s what we’re interested into. Sometimes you’ll also find a classes2.dex file, this is due to the DEX format which has a limit to the number of classes you can declare inside a single dex file, at some point in history Android apps became bigger and bigger and so Google had to adapt this format, supporting a secondary .dex file where other classes can be declared. From our perspective it doesn’t matter, the tools we’re going to use are able to detect it and append it to the decompilation pipeline. /libs/ ( folder ) Sometimes an app needs to execute native code, it can be an image processing library, a game engine or whatever. In such case, those .so ELF libraries will be found inside the libs folder, divided into architecture specific subfolders ( so the app will run on ARM, ARM64, x86, etc ). /META-INF/ ( folder ) Every Android application needs to be signed with a developer certificate in order to run on a device, even debug builds are signed by a debug certificate, the META-INF folder contains information about the files inside the APK and about the developer. Inside this folder, you’ll usually find: A MANIFEST.MF file with the SHA-1 or SHA-256 hashes of all the files inside the APK. A CERT.SF file, pretty much like the MANIFEST.MF, but signed with the RSA key. A CERT.RSA file which contains the developer public key used to sign the CERT.SF file and digests. Those files are very important in order to guarantee the APK integrity and the ownership of the code. Sometimes inspecting such signature can be very handy to determine who really developed a given APK. If you want to get information about the developer, you can use the openssl command line utility: openssl pkcs7 -in /path/to/extracted/apk/META-INF/CERT.RSA -inform DER -print This will print an output like: PKCS7: type: pkcs7-signedData (1.2.840.113549.1.7.2) d.sign: version: 1 md_algs: algorithm: sha1 (1.3.14.3.2.26) parameter: NULL contents: type: pkcs7-data (1.2.840.113549.1.7.1) d.data: <ABSENT> cert: cert_info: version: 2 serialNumber: 10394279457707717180 signature: algorithm: sha1WithRSAEncryption (1.2.840.113549.1.1.5) parameter: NULL issuer: C=TW, ST=Taiwan, L=Taipei, O=ASUS, OU=PMD, CN=ASUS AMAX Key/emailAddress=admin@asus.com validity: notBefore: Jul 8 11:39:39 2013 GMT notAfter: Nov 23 11:39:39 2040 GMT subject: C=TW, ST=Taiwan, L=Taipei, O=ASUS, OU=PMD, CN=ASUS AMAX Key/emailAddress=admin@asus.com key: algor: algorithm: rsaEncryption (1.2.840.113549.1.1.1) parameter: NULL public_key: (0 unused bits) ... ... ... This can be gold for us, for instance we could use this information to determine if an app was really signed by (let’s say) Google or if it was resigned, therefore modified, by a third party. How do I get the APK of an app? Now that we have a basic idea of what we’re supposed to find inside an APK, we need a way to actually get the APK file of the application we’re interested into. There are two ways, either you install it on your device and use adb to get it, or you use an online service to download it. Pulling an app with ADB First of all let’s plug our smartphone to the USB port of our computer and get a list of the installed packages and their namespaces: adb shell pm list packages This will list all packages on your smartphone, once you’ve found the namespace of the package you want to reverse ( com.android.systemui in this example ), let’s see what its physical path is: adb shell pm path com.android.systemui Finally, we have the APK path: package:/system/priv-app/SystemUIGoogle/SystemUIGoogle.apk Let’s pull it from the device: adb pull /system/priv-app/SystemUIGoogle/SystemUIGoogle.apk And here you go, you have the APK you want to reverse! Using an Online Service Multiple online services are available if you don’t want to install the app on your device (for instance, if you’re reversing a malware, you want to start having the file first, then installing on a clean device only afterwards), here’s a list of the ones I use: Apk-DL Evozi Downloader Apk Leecher Keep in mind that once you download the APK from these services, it’s a good idea to check the developer certificate as previously shown in order to be 100% sure you downloaded the correct APK and not some repackaged and resigned stuff full of ads and possibly malware. Network Analysis Now we start with some tests in order to understand what the app is doing while executed. My first test usually consists in inspecting the network traffic being generated by the application itself and, in order to do that, my tool of choice is bettercap … well, that’s why I developed it in the first place Make sure you have bettercap installed and that both your computer and the Android device are on the same wifi network, then you can start MITM-ing the smartphone ( 192.168.1.5 in this example ) and see its traffic in realtime from the terminal: sudo bettercap -T 192.168.1.5 -X The -X option will enable the sniffer, as soon as you start the app you should see a bunch of HTTP and/or HTTPS servers being contacted, now you know who the app is sending the data to, let’s now see what data it is sending: sudo bettercap -T 192.168.1.5 --proxy --proxy-https --no-sslstrip This will switch from passive sniffing mode, to proxying mode. All the HTTP and HTTPS traffic will be intercepted (and, if neeeded, modified) by bettercap. If the app is correctly using public key pinning (as every application should) you will not be able to see its HTTPS traffic but, unfortunately, in my experience this only happens for a very small number of apps. From now on, keep triggering actions on the app while inspecting the traffic ( you can also use Wireshark in parallel to get a PCAP capture file to inspect it later ) and after a while you should have a more or less complete idea of what protocol it’s using and for what purpose. Static Analysis After the network analysis, we collected a bunch of URLs and packets, we can use this information as our starting point, that’s what we will be looking for while performing static analysis on the app. “Static analysis” means that you will not execute the app now, but you’ll rather just study its code. Most of the times this is all you’ll ever need to reverse something. There’re different tools you can use for this purpose, let’s take a look at the most popular ones. apktool APKTool is the very first tool you want to use, it is capable of decompiling the AndroidManifest file to its original XML format, the resources.arsc file and it will also convert the classes.dex ( and classes2.dex if present ) file to an intermediary language called SMALI, an ASM-like language used to represent the Dalvik VM opcodes as a human readable language. It looks like: 1 2 3 4 5 6 7 8 .super Ljava/lang/Object; .method public static main([Ljava/lang/String;)V .registers 2 sget-object v0, Ljava/lang/System;->out:Ljava/io/PrintStream; const-string v1, "Hello World!" invoke-virtual {v0, v1}, Ljava/io/PrintStream;->println(Ljava/lang/String;)V return-void .end method But don’t worry, in most of the cases this is not the final language you’re gonna read to reverse the app Given an APK, this command line will decompile it: apktool d application.apk Once finished, the application folder is created and you’ll find all the output of apktool in there. You can also use apktool to decompile an APK, modify it and then recompile it ( like i did with the Nike+ app in order to have more debug logs for instance ), but unless the other tools will fail the decompilation, it’s unlikely that you’ll need to read smali code in order to reverse the application, let’s get to the other tools now jADX The jADX suite allows you to simply load an APK and look at its Java source code. What’s happening under the hood is that jADX is decompiling the APK to smali and then converting the smali back to Java. Needless to say, reading Java code is much easier than reading smali as I already mentioned Once the APK is loaded, you’ll see a UI like this: One of the best features of jADX is the string/symbol search ( the button ) that will allow you to search for URLs, strings, methods and whatever you want to find inside the codebase of the app. Also, there’s the Find Usage menu option, just highlight some symbol and right click on it, this feature will give you a list of every references to that symbol. Dex2Jar and JD-Gui Similar to jADX are the dex2jar and JD-GUI tools, once installed, you’ll use dex2jar to convert an APK to a JAR file: /path/to/dex2jar/d2j-dex2jar.sh application.apk Once you have the JAR file, simply open it with JD-GUI and you’ll see its Java code, pretty much like jADX: Unfortunately JD-GUI is not as features rich as jADX, but sometimes when one tool fails you have to try another one and hope to be more lucky. JEB As your last resort, you can try the JEB decompiler. It’s a very good software, but unfortunately it’s not free, there’s a trial version if you want to give it a shot, here’s how it looks like: JEB also features an ARM disassembler ( useful when there’re native libraries in the APK ) and a debugger ( very useful for dynamic analysis ), but again, it’s not free and it’s not cheap. Static Analysis of Native Binaries As previously mentioned, sometimes you’ll find native libraries ( .so shared objects ) inside the lib folder of the APK and, while reading the Java code, you’ll find native methods declarations like the following: 1 public native String stringFromJNI(); The native keyword means that the method implementation is not inside the dex file but, instead, it’s declared and executed from native code trough what is called a Java Native Interface or JNI. Close to native methods you’ll also usually find something like this: 1 System.loadLibrary("hello-jni"); Which will tell you in which native library the method is implemented. In such cases, you will need an ARM ( or x86 if there’s a x86 subfolder inside the libs folder ) disassembler in order to reverse the native object. IDA The very first disassembler and decompiler that every decent reverser should know about is Hex-Rays IDA which is the state of the art reversing tool for native code. Along with an IDA license, you can also buy a decompiler license, in which case IDA will also be able to rebuild pseudo C-like code from the assembly, allowing you to read an higher level representation of the library logic. Unfortunately IDA is a very expensive software and, unless you’re reversing native stuff professionaly, it’s really not worth spending all those money for a single tool … warez … ehm … Hopper If you’re on a budget but you need to reverse native code, instead of IDA you can give Hopper a try. It’s definitely not as good and complete as IDA, but it’s much cheaper and will be good enough for most of the cases. Hopper supports GNU/Linux and macOS ( no Windows! ) and, just like IDA, has a builtin decompiler which is quite decent considering its price: Dynamic Analysis When static analysis is not enough, maybe because the application is obfuscated or the codebase is simply too big and complex to quickly isolate the routines you’re interested into, you need to go dynamic. Dynamic analysis simply means that you’ll execute the app ( like we did while performing network analysis ) and somehow trace into its execution using different tools, strategies and methods. Sandboxing Sandboxing is a black-box dynamic analysis strategy, which means you’re not going to actively trace into the application code ( like you do while debugging ), but you’ll execute the app into some container that will log the most relevant actions for you and will present a report at the end of the execution. Cuckoo-Droid Cuckoo-Droid is an Android port of the famous Cuckoo sandbox, once installed and configured, it’ll give you an activity report with all the URLs the app contacted, all the DNS queries, API calls and so forth: Joe Sandbox The mobile Joe Sandbox is a great online service that allows you to upload an APK and get its activity report without the hassle of installing or configuring anything. This is a sample report, as you can see the kind of information is pretty much the same as Cuckoo-Droid, plus there’re a bunch of heuristics being executed in order to behaviourally correlate the sample to other known applications. Debugging If sandboxing is not enough and you need to get deeper insights of the application behaviour, you’ll need to debug it. Debugging an app, in case you don’t know, means attaching to the running process with a debugger software, putting breakpoints that will allow you to stop the execution and inspect the memory state and step into code lines one by one in order to follow the execution graph very closely. Enabling Debug Mode When an application is compiled and eventually published to the Google Play Store, it’s usually its release build you’re looking at, meaning debugging has been disabled by the developer and you can’t attach to it directly. In order to enable debugging again, we’ll need to use apktool to decompile the app: apktool d application.apk Then you’ll need to edit the AndroidManifest.xml generated file, adding the android:debuggable="true" attribute to its application XML node: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 <?xml version="1.0" encoding="utf-8" standalone="no"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.company.appname" platformBuildVersionCode="24" platformBuildVersionName="7.0"> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" android:debuggable="true"> <-- !!! NOTICE ME !!! --> <activity android:name="com.company.appname.MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> </manifest> Once you updated the manifest, let’s rebuild the app: apktool b -d application_path output.apk Now let’s resign it: git clone https://github.com/appium/sign java -jar sign/dist/signapk.jar sign/testkey.x509.pem sign/testkey.pk8 output.apk signed.apk And reinstall it on the device (make sure you unistalled the original version first): adb install signed.apk Now you can proceed debugging the app Android Studio Android Studio is the official Android IDE, once you have debug mode enabled for your app, you can directly attach to it using this IDE and start debugging: IDA If you have an IDA license that supports Dalvik debugging, you can attach to a running process and step trough the smali code, this document describes how to do it, but basically the idea is that you upload the ARM debugging server ( a native ARM binary ) on your device, you start it using adb and eventually you start your debugging session from IDA. Dynamic Instrumentation Dynamic instrumentation means that you want to modify the application behaviour at runtime and in order to do so you inject some “agent” into the app that you’ll eventually use to instrument it. You might want to do this in order to make the app bypass some checks ( for instance, if public key pinning is enforced, you might want to disable it with dynamic instrumentation in order to easily inspect the HTTPS traffic ), make it show you information it’s not supposed to show ( unlock “Pro” features, or debug/admin activities ), etc. Frida Frida is a great and free tool you can use to inject a whole Javascript engine into a running process on Android, iOS and many other platforms … but why Javascript? Because once the engine is injected, you can instrument the app in very cool and easy ways like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 from __future__ import print_function import frida import sys # let's attach to the 'hello process session = frida.attach("hello") # now let's create the Javascript we want to inject script = session.create_script(""" Interceptor.attach(ptr("%s"), { onEnter: function(args) { send(args[0].toInt32()); } }); """ % int(sys.argv[1], 16)) # this function will receive events from the js def on_message(message, data): print(message) # let's start! script.on('message', on_message) script.load() sys.stdin.read() In this example, we’re just inspecting some function argument, but there’re hundreds of things you can do with Frida, just RTFM! and use your imagination Here‘s a list of cool Frida resources, enjoy! XPosed Another option we have for instrumenting our app is using the XPosed Framework. XPosed is basically an instrumentation layer for the whole Dalvik VM which requires you to to have a rooted phone in order to install it. From XPosed wiki: There is a process that is called "Zygote". This is the heart of the Android runtime. Every application is started as a copy ("fork") of it. This process is started by an /init.rc script when the phone is booted. The process start is done with /system/bin/app_process, which loads the needed classes and invokes the initialization methods. This is where Xposed comes into play. When you install the framework, an extended app_process executable is copied to /system/bin. This extended startup process adds an additional jar to the classpath and calls methods from there at certain places. For instance, just after the VM has been created, even before the main method of Zygote has been called. And inside that method, we are part of Zygote and can act in its context. The jar is located at /data/data/de.robv.android.xposed.installer/bin/XposedBridge.jar and its source code can be found here. Looking at the class XposedBridge, you can see the main method. This is what I wrote about above, this gets called in the very beginning of the process. Some initializations are done there and also the modules are loaded (I will come back to module loading later). Once you’ve installed XPosed on your smartphone, you can start developing your own module (again, follow the project wiki), for instance, here’s an example of how you would hook the updateClock method of the SystemUI application in order to instrument it: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 package de.robv.android.xposed.mods.tutorial; import static de.robv.android.xposed.XposedHelpers.findAndHookMethod; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; public class Tutorial implements IXposedHookLoadPackage { public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable { if (!lpparam.packageName.equals("com.android.systemui")) return; findAndHookMethod("com.android.systemui.statusbar.policy.Clock", lpparam.classLoader, "updateClock", new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { // this will be called before the clock was updated by the original method } @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { // this will be called after the clock was updated by the original method } }); } } There’re already a lot of user contributed modules you can use, study and modify for your own needs. Conclusion I hope you’ll find this reference guide useful for your Android reversing adventures, keep in mind that the most important thing while reversing is not the tool you’re using, but how you use it, so you’ll have to learn how to choose the appropriate tool for your scenario and this is something you can only learn with experience, so enough reading and start reversing! Sursa: https://www.evilsocket.net/2017/04/27/Android-Applications-Reversing-101/1 point
-
Nu, API nu e scris de mine, l-am gasit gata scris, si am inceput de acolo. Poate il scriam eu daca nu exista, cand m-am lovit de bugul mentionat m-am gandit sa imi scriu singur api, apoi am zis ca e in afara scopului...voiam sa ajung repede la rezultat fara prea mare bataie de cap. Este un proiect de fun, nu vreau sa investesc in el sau sa il dezvolt mai mult.1 point
-
Vad ca te-ai documentat putin. Diferenta e ca pot sa iti descarc si flac-uri (prin link de app desktop/mobile) doar ca, sunt cum spui si tu criptate. Foloesc WidevineCDM. Iti dau multe fisiere prin web doar. Si calitate master ai doar pe Mac/Win cu aplicatia de desktop. Eu folosesc de cativa ani Tidal, si sunt fan, chiar face diferenta pe un sistem bun/casti bune, adica e asta si restul din punctul meu de vedere. (legat de valorile exacte le-am mentionat in primul post) Da asa este Spotify are un sistem de recomandari incredibil de bine pus la punct! Asta e motivul pentru care am si Spotify :)))).1 point
-
There were 28 transactions from his account, the businessman said, but he was not notified as his SIM card had been blocked by those behind the fraud. Story Highlights A suspected case of SIM card swapping led to the fraud The businessman says he received six missed calls before the fraud A case has been registered with the cybercrime wing Mumbai: A suspected case of SIM card swapping has led to a Mumbai-based textile businessman losing Rs 1.86 crore from his bank account. A case has been registered with the cybercrime wing of the Mumbai Police. The businessman, whose identity is not being revealed, says he received six missed calls on his mobile phone between 11.44 pm and 1.58 am on December 27-28, after which the fraud took place. Cyber experts call it the "SIM swap", in which criminals gain access to the data and use the OTP that is required to transfer funds. SIM swap is a relatively new and technologically advanced form of fraud that allows hackers to gain access to bank account details, credit card numbers, and other personal data. The businessman says he became suspicious when he noticed six missed calls on his phone. Two were from the UK. When he realized his phone had stopped working, he approached the service provider who informed him that the SIM card had been blocked on his request the previous night. "I was informed that I had put in a request to block my SIM around 11.15 pm on December 27. I disputed that as I had not put in any request to block the SIM card. After this, the service provider issued a new SIM card which was activated on the evening of December 29," the businessman said. There were 28 transactions from his account, he said, but he was not notified as his SIM card had been blocked by those behind the fraud. The businessman says he realised that he had been robbed when one of his employees approached the bank for a fund transfer and was told that the account was overdrawn. The businessman said, "On checking the accounts we found that there were 28 transactions transferring money to almost 15 different accounts. None of these transactions were initiated by us and the money wasn't transferred to accounts we transfer funds regularly to." Deputy Commissioner of Police Akbar Pathan told reporters, "We have received a complaint that around ₹ 1.86 crore has been transferred from his current account. The criminals had his bank credentials and phone number. We want to tell people that if your phone is blocked without consent, please get it reactivated immediately and inform the police if you notice fraudulent transactions." Via https://www.ndtv.com/mumbai-news/how-6-missed-calls-left-mumbai-businessman-robbed-off-rs-1-86-crore-1972131?amp=1&akamai-rum=off1 point
-
Daca face asta cred ca o sa fie dat jos continutul (DMCA), iar cei de la tidal vor patch-ui. Sunteti mult prea dusmanosi/invidioasi. Invatati sa fiti mai buni!1 point
-
Salut si bine ai venit! Ce te intereseaza mai exact? Ethical Hacking e white hat. Grey hat este cumva la granita dintre white si black, o combinatie intre cele doua. Detalii despre white, black, grey, aici. Pe astea le-am gasit cautand pe Google. Pe partea de web security poti sa incerci hacker101 si pwnthecode, cel din urma fiind un proiect RST. Iar mai jos ai carti, resurse/materiale pentru o viata: https://mega.nz/#F!8G4wxSrJ!m7LX9z4a3Zxbpw62q9ZFSQ - infosec PDF https://mega.nz/#F!8EdEmZSI!OHRaksNSZYpSKLMUnrOelQ - Infosec PDF https://mega.nz/#F!VpZSjbbR!T8HXLl20No0LDP8OTIYZAg - old hacking/pentesting courses & books 2003-2012 http://www.ytxmrc3pcbv5464e.onion/files/ https://repo.zenk-security.com http://index-of.es https://github.com/vhf/free-programming-books/blob/master/free-programming-books.md#professional-development - programming books https://github.com/Hack-with-Github/Free-Security-eBooks 500 GB programming resources: https://drive.google.com/drive/folders/0ByWO0aO1eI_MN1BEd3VNRUZENkU https://drive.google.com/drive/folders/0B6e-S9ckSvFSdE5MaXRiaWIwbGc https://drive.google.com/drive/folders/1O2cqrDEdX_1Vag9wWQC6ovBgeoXDk0BB https://mega.nz/#F!NAZwVILa!U15d9WY-uy4bg0tjUYGQEA - programming books http://www.oreilly.com/programming/free/ http://books.goalkicker.com1 point
-
Salutare, Daca sunteti interesati de Retelistica (Cisco CCNA) va invit sa urmariti aceste tutoriale si sa aplicati conceptele prin laboratoarele incluse [1] https://www.youtube.com/channel/UCVJZsdei_i2G3ZimBzqcmeg [2] https://ramonnastase.ro Spor la treaba !1 point
-
String-uri in Python Slicing and substrings ( Felierea si sub – stringuri ) Si mai interesanta este posibilitatea de taiere ( slicing ) , aceasta tehnia permite sa taiati o parte din lista care indica indicele de pornire si indicele de incheiere , este util sa stiti ca sub – stringul prelevat e acela care pleaca de la caracterul indicat al primului indice inclus , pana la indicele final exclus , omitand unu dintre indici indicam Python-ului sa mearga pana la sfarsit cu taierea , daca punem un numar negativ ca si indice final , Python va calcula caracterele in sens invers . Niste exemple practice : >>> y='Hello World' >>> y[0] # Ia prima litere de la Y avand in vedere ca se porneste de la 0 'c' >>> y[5] 'm' >>> x='Programare Pythom' >>> x[-2] # Printeaza al doilea caracter incepand de la dreapta 'o' >>> x[2:7] # Printeaza caracterele X inclusiv de la 2 la 7 'ogram' >>> x[4:] # Printeaza de la al patrulea caracter pana la sfarsit X 'ramuri python' >>> x[:4] # Printeaza caracterele X cuprinse de la inceput pana la al patrlea 'prog' >>> x[3:-2] # Printeaza de la al treilea caracter incepand de la 0 pana la penultimul X 'gramare python Metode pentru string-uri Observam acum anumite metode pentru stringuri care pot fii utile : Metoda " find() " este utila a reincarca de caractere un string , iar daca nu este prezent de rezulta " -1 " >>> s='rstforums.com' >>> s.find('rst') 0 Metoda " replace() " >>> s.replace('com','test') 'com.test' Metodele " upper() si lower()" , servesc la convertirea MAJUSCULELEOR si minusculelor intr-un string. >>> up=s.upper() >>> print(up) rstforumc.com >>> low=up.lower() >>> print(low) Construirea stringurilor : Multumita operatorului " % " putem sa construim un string introducand parametr " semnalpost " care se pot substituii cu valori asumate de variabile , ca si in instructia " printf " din " C " , exemplu : >>> nume = 'stefan' >>> ani = 29 >>> rezultat = "%s are %d ani" % (nume, ani) >>> print(rezultat) stefan are 29 ani In primele linii am definit variabilele + valorile string si numerice . In linia " %s are %d ani " am introdus parametrii . %s – Parametru de tip string %d – Parametru de tip numeric Parametrii pentru constrirea sting-urilor : Python ne ofera alte functii pentru a gestii string-urile , toate sunt grupate imprena cu modulul numic " string " . Liste Listele in Python sunt coletii ordonate de obiecte simalre " array " al altor tipuri de limbaje , cum ar fii Java . Diferit de string-urile despre care am vorbit , listele pot sa contina obiecte eterogene cum ar fii numere , string-uri si alte liste , acest ne permite de a manipula rapid si de a structura complexitati de alta natura , petru a declara o lista este suficient sa dati unui variabile o lista de valori , separate prin virgula si inchide cu paranteze patrate , exemplu : >>> l1=[1, 'html.it'] # Lista cu un intreg si un string >>> l2=[1, 1.2, 'ciao', [1,2] ] # Lista cu : intreg , real , string si o alta lista O mare parte din ceea ce am scris pentru string-uri este valabil si pentr liste , ca si indice care incepe de la 0 , normal o serie de exemple vor demonstra cum lucreaza operatorii de indici si slicing ( taiere ) . >>> s=['rst', 'com', 'rst.com'] * >>> s[0]****** # indicare 'rst' * >>> s[-2]***** # Indicare incepand de la dreapta 'com' * >>> s[:2]***** # slicing ['rst', 'com'] * >>> s[2:] ['rst.com'] * >>> s[1:-1] ['com'] Sa vedem acum operatorii pentru concatare " + " si repetare " + " , pentru liste . >>> [1, 2, 3] + [4, 5] # concatare [1, 2, 3, 4, 5] * >>> ['rst.com']*3***** # repetare ['rst.com', 'rst.com', 'rst.com'] >>> y=[1,2,3] * >>> y[0]="unu"* # Modifica lista >>> y ['unu', 2, 3] * >>> y[1:2]=[]** # Sterge un element din lista >>> y ['unu', 3] Pentru a cunoaste lngimea unei liste , utilizam functia " len()" >>> lista=['c', 'a', 'b']***** >>> len(lista) 3 Metode pentru liste Exemple : >>> lista=['rst', 'rst', 'rst l']**** * >>> lista.append('rst .com')************ #metoda append() >>> lista ['rst', 'rst', 'rst', 'rst.com'] * >>> lista.extend(['HYml','rst.COM'])*********#metoda extend() >>> lista ['rst', 'rst', 'rst', 'rst.com', 'HYml', 'rst.COM'] * >>> lista.insert(0, 'primuRST')************ #metoda insert() >>> lista ['primuRST', 'rst', 'rst', 'rst', 'rst.com', 'HYml', 'rst.COM'] Acum sa vedem metode de stergere : >>> lista=['rst', 'RST', 'Rst']**** >>> lista.pop() #Fara indice elimina ultimu element din lista 'Rst' >>> lista ['rst', 'RST'] >>> lista=['rst', 'RST', 'Rst']**** >>> lista.remove('rst')****** ['RST', 'Rst'] * >>> lista=['rst', 'RST', 'Rst'] >>> lista.remove(lista[1]) >>> lista ['rst', 'Rst'] >>> lista=['c', 'a', 'b']***** >>> lista.sort() >>> lista ['a', 'b', 'c'] Dictionare Un dictionar este o coloectie neordonata de obiecte . Obiectele sunt identificate unice de o cheie ( in general un string ) in loc de mediante un indice numeric , cum se face la liste . Fiecare element al dictionarului este reprezentat de o copie ( cheie / valoare ) , cheia este utila pentru a deschide elemente sau recuperare valori . Este exact ca si cand ai cauta un cuvand in DEX , in practica ceea ce se cauta este o explicatie a cheii , pentru a face o comparatie cu alte limbaje , putem spune la dictionar ca este o specie de array asociativ . Un dictionar este format din elemente separate , virgule si inchide in paranteze grafe , un dictionar gol este format din paranteze deschide si inchise . >>> dictionar1={}*********** # dictioar gol >>> dictionar1 {} Putem creea noi insine un dictionat prin metoda " dict() " >>> dictionar2=dict()******* # dictionar gol >>> dictionar2 {} Putem sa definim elemente din dictionar direct , listand copii ale cheilor-valorifice . >>> dictionar={'rst':1, 'RST':2, 'ESt':3} >>> dictionar {'rst': 1, 'RST': 2, 'RSt': 3} Pentru a recupera o valoare putem sa trecem la dictionarul nume de la cheia relativa. >>> dictionar['RST']******* # Recupereaza valoarile incepand de la dictionarul 2 Putem verifica existenta unei chei prin keyward-ul " in " >>>* 'rs' in dictionar******** # cauta cheia >>> True Introduceri , modificari si stergeri Sa vedem acum cum se introduce , modifica si sterge elemente dintr-un dictionar : >>> dic={'rst':1, 'RST':2, 'RSt':3} >>> dic['rst.com']=4****************** # introducere >>> dic {'rst': 1, 'RST': 2, 'rst.comt': 4, 'RSt': 3} * * >>> dic['rst']=7********************* # modifica >>> v {'rst': 7, 'RST': 2, 'html.it': 4, 'RSt': 3} * * >>> del dic['RST']******************* # stergere >>> dic {'rst': 7, 'rst.com': 4, 'RSt': 3} Pentru a cunoaste numarul elementelor dintr-un dictionar , utilizam "len " >>> len(dic) 3 Metode pentru dictionare >>> dic={'rst.com':1, 'RST':2, 'rst':3} * >>> dic.get('rst')*********************************** # metoda get() 3 * >>> dic.values()************************************** # metoda values() dict_values([1, 3, 2]) * >>> dic.keys()****************************************metoda keys() dict_keys(['rst.com', 'rst', 'RST'])* * >>> dic.items()*************************************** # metoda items() dict_items([('rst.com', 1), ('rst', 3), ('RST', 2)]) Oridinea cheilor ( cuvintelor ) Cum era la inceput cu Python 3.x , nu putem sa ordonam un dictionar utilizand direct lista obtinuta prin metoda " keys " . >>> dic1 = {'andrea':28, 'florin':25, 'marius':21, 'elena':28} >>> k = dic1.keys() >>> k.sort() Traceback (most recent call last): **File "<stdin>", line 1, in <module> AttributeError: 'dict_keys' object has no attribute 'sort' Ca o solutie ca saputem sa obtinem ceva ordonat convertind intr-o lista elancata de chei si aplcare metoda "sort" >>> k=list(k) #conversie in lista >>> k ['marius', 'florin', 'andrea', 'elena'] >>> k.sort() >>> k ['andrea', 'elena', 'florin', 'marius'] >>> for elemento in k: print(element, dic1[element]) ... andrea 28 elena 28 florin 25 marius 21 Tupla ( Tuple ) O tupla in Python este mult similara unei liste , functia lor este in mare parte aceeasi . Prima diferenta intre tupla si lista este sintaxa , tuplele sunt inchide intre paranteze rotunde ( nu patrate ) , exemple : >>> t=() >>> t () Iar pentru a reprezenta o tupla cu un element , se foloseste o sintaxa . >>> t=(1,) >>> t (1,) Urmatoare diferenta nu este prea vizibila , dar nu trebuie sa o trecem cu vederea . Lista poate fii mutat , tupla NU . Tipi mutabili Sa incercam sa descifram , variabilele de tip mutabil pot sa sa isi schimbe " viata ", practic pentru o lista este posibil sa intrducel sau sa stergem elemente in orice moment , pentru tipurile non mutabile , adica nu este posibil sa schimbam blocul valorii in in intern . Folosirea tuplelor Tuplele sunt folosite cand noi nu vrem sa se modifice continutul unei elencari , deci nu se pot adauga / sterge elemente . Operatorii sunt aceeasi ca cei ai listelor ( mai putin cei ce schimba valoarea care nu au motiv sa exista ) exemple : >>> tupla=(1,2,3,4) >>> tupla (1, 2, 3, 4) * >>> tupla[3]****** #indicare 4 * >>> tupla[1:-1]******* #slicing (2, 3) Ca si pentru string-uri si liste , avem operatori de concare si repetare : >>> ('unu','doi')+('trei','patru') # concatare ('primo', 'secondo', 'terzo', 'quarto') * >>>* ('unu',)*2************************** # ripetare ('unu', 'unu') Cum s-a mentionat mai sus , spre deosebire de liste, tuplele nu accepta modificari . >>> tupla=(1,2,3) >>> tupla.append(4) Traceback (most recent call last): **File "<stdin>", line 1, in <module> AttributeError: 'tuple' object has no attribute 'append' </pre> * <pre class="brush:plain"> >>> tupla.remove(1) Traceback (most recent call last): **File "<stdin>", line 1, in <module> AttributeError: 'tuple' object has no attribute 'remove' * >>> tupla[0]=2 Traceback (most recent call last): **File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment Conversatii liste -> tuple , tuple->liste Este posibila conversatia dintre cele doua , cu functiile list si tuple , exeplu : >>> tupla=(1,2,3,4) >>> lista=list(tupla)***** # conversatie tupla-lista >>> lista [1, 2, 3, 4] * >>> tuplaconv=tuple(lista) # conversatie lista-tupla >>> tuplaconv (1, 2, 3, 4) Fisiere in Python Conceptul de fisier ( file ) este destul de bine cunoscut , faptul ca gestirea fisierelor in Pytho trebuie facuta in internul limbajuli ( built-in ) garanteaza o voteza si simplitate in gestirea lor , in particular este important sa putem gestiona fisiere cu instructii de limbaj programare , pentru salvarea informatiilor pe HDD si facute persistente . Continuare ^ | Variabilele " input si output " din tabel sunt obiecte de tip file , exemplu : >>> myfile = open('R0cc0.txt','w')****** # apare fisierul in scriere * >>> myfile.write(' linia 1\n')************ #** scrie linia 1 7 >>> myfile.write(' linia 2\n')************ #** scrie linia 2 7 >>> myfile.write(' linia 3\n')************ #** scrie linia 3 7 >>> myfile.close()********************* # inchide fisier * >>> myfile = open('R0cc0.txt','r')****** # Apare fisierul in timpul citirii >>> myfile.readlines()***************** #** citeste din fisier si reda o lista in linii ['linia1\n', 'linia2\n', 'linia3\n'] Functia " open " ne da voie sa citim un fisier care il scriem si returneaza un obiect de tip file care se asociaza lui " myfile ", Utilizam creeatia pentru a scrie in file cu metoda " write " si il inchidem cu " close" . Apoi ne intoarcem la acelasi fisier in citire si printam continutul cu " readlines() . Metode de deschidere ( open ) In afara de " w " si " r " ( write si read ) , care le-am studiat deja , funcia " open " ne arata alte modalitati de deschidere a fisierelor , care le putem utiliza ca si al doilea parametru : Din fisierele deshide in mod binar , putem extrage date ca si byte , fara nici un cod . >>> print(open.__doc__) Miscandune in internul fisierului Pentru a verifica statutul fisierului este suficient a printa datele instantei curente , exemplu : >>> myfile <_eo.TextEuWrapper name='RST.txt' mode='r' encoding='cp1252'> NOTA : sa nu uitam , mereu trebuie sa inchidem fisierele dupa ce le folosim / modificam " (close()) " . Functii Functiile sunt grupuri de instructii care la inceput prind un intreg de valori parametrici si au ca rezultat aceeasi parametrii . Functiile sunt un instrument important . Parmit reutilizarea codului , functiile folosite de mai multe ori intr-un program pot sa fie adunate intr-o singura functie . Permit de structurare codul programului in bloccri omogene din punct de vedere logic pentru a imbunatatii munca programatorului . Sintaxa definirii unei functii este : def nume_functie(<listeaza parametri divizati de virgula >): <bloc de instructiuni> return <rezultat> # optional Odata definita functia in acest mod este posibila retilizarea ei simplu , invocand numele ei , urmat de list de valori , se sub intelege , valorile le vom trece ca si parametri . Exemplu : def patrat(valoare): ris = valoare * valoare return ris a = 5 print patrat(a) Urmarind acest program , rezultat este 25 . Primele 3 linii definesc functia de patrat . De acum innainte numele " patrat " devine parte din " namespace " al modulului curent ( un intreg de nume semnificative in internul modulului ) . Invoam funcia , valoarea trecuta ca si parametru vine transferat la functia numelui parametrului (" valoare ") , vine urmata functia si de restituie rezultatul modululuin invocat . Toate asta ne permit sa sa le introducem in " patrat " , o operatie mai complexa . Introducand functiile trebuie sa distrugem variabilele locale ale functiiloor , deci vor fii utilizate de la sine . Variabilele globale , sau aparente in " namespace "modulului, deci se utilizeaza in afara functiei . Cand se invoca o functie vin transferate valorile variabilelor parametrilor functiilor . Acesta permite functiilor de venire in urma fnctiior care provin din " bloc " . Trecerea pe valori : Vine transferta functiei doar o copie a variabilei, deci funcia nu poate altera valoare variabilei . Trecere pe referinte : In acest caz vine trandferata variabila adevarata , deci poate altera valoare variabilei . In python parametrii trecuti la functii sunt mereu transferati pe valori . Asta e diferenta intre alte limbaje , ca si " C , Pascal" , unde se pot trece parametrii si pe referinte . Practic cand se utilizeaza o variabila , Python incearca prima oara numele acelei variabile in " namespace "local . Daca , cautarea nu este pozitiva , se continua cu " namespace " global si doar succesiv se va cauta numele intre functii ( built – in ) . adica cele default in Python . Acest mecanisc permite de utilizare valoarea variabile si provoaca creearea aceluiasi nume intr-un " namespace " nou . Exemplu : def functie1(): x = 20 # variabila locala cu acelasi nume print x # adevarat' vazut 20 si nu 10 print y # devarat' vazut 19 x = 10 # variabile gloobale y = 19 functie1() Treaba se schimba radicat pentru strcurarea datelor mutabile , care pot fii modificate in internul functiilor . Practic nu sunt niste ariabile adevarate ,deci e posibil sa le modificam . Exemplu : def functie2(a,b = 30): print a, b x = 10 y = 19 functie2(x) functie2(x,y) Functia numita 2 "functie2" are 2 parametrii : a si b , ea vine invocata de 2 ori . Rezultatul primului invoc este 10, 30 , practic parametrul b, nu este indicat , ia valoarea 30 . Rezultatul la al doilea invoc este 10, 19 . Module ( Moduli ) Cand se intra mai adanc in Python , programele / codurile cresc repede , si devin obositoare si greu de gestionat , intregul program intr-un singur file script . Pentru asta e oportun subdidere programu in diverse fisiere de script . Aceasta medoda permite de creeare recolte de functii care pot sa fie utilizate in proiecte diverse . Moduli sunt fisiere de script , "file.py " care pot sa fie reinvocate de alte programe Python pentru reutilizarea functiilor continute . Moduli pot sa fie creati usor de noi cei ce programam , dar daca exista deja multi , dece sa nu ii modificam continutul . Moduli pentru gestionarea string-urilor Moduli pentru invocare functii , din sitemul operativ Moduli pentru gestionarea internetului Moduli pentru e-mail Pentru a scrie un modul , este de ajuns sa creean un " file.py " si sa scriem toate functiile necesare , pentru al putea folosii il vom importa cu , comanda " import " . Exemplu : NOTA : Nu va incerede tin moduli luati de pe internet . import library upa ce ati importat libraria ( modulul ) , ptem simplu invocare functiile continute , folosind " dot notation " . Scriem numele modululi un punct si numele functiei , reusim sa intram in modul si invocare functia . Exemplu : R0cc0.py , contine functiile " open() , close() " , si move(obiect ) , puteti sa invocati functii asa : import library library.open() ogg=5 library.move(ogg) library.close() Daca nu doriti sa utilizati numele librariei , mereu cand invocati o functie , este posibil sa puneti si numele functiei direct . import library from library import move libraty.open() ogg=5 move(ogg) library.close() In acest caz , fuctia mutat face parte din intregul de nume definite in program " namaspace " si nu necesita prefix de nume modul ( librarie ) . library.py in internul programului , este de ajuns sa utilizati caracterul "*" . from library import * open() ogg=5 move(ogg) close() String : Modul care aduna functii pentru gestionarea string-urilor . Functii pentru convertire din strind in numar Functii petru convertire din minuscula in MAJUSCULA Functii pentru inlocuirea de patilor dintr-un string Sys : modul care adna functii pentru reperarea de informatii din sistem , ex : reperearea argumentelor trecute in linia de comanda ( CmD ) . Os : Modul pentru a face operatii din sistemul operativ , ex : copierea , renumirea sau stergerea unui file . Pentru a se inetelege mai bine conceputl de import al numelor functiilor , trebuie sa punem in paralele conceputul " namespace " Fiecare modul are un intreg de nume ( cele de variabile si cele de functii ) care reprezinta nume utilizabile in internul sau . Acest intreg se mai numeste si " namespace " ( spatiul numelor ). Pentr a transporta numele dintr-un " namespace " in altul se poate folosii comanda " import " Mediant , functia " dir() " , cu , care este posibil sa vedem lista de nume . >>> dir() ['__builtins__', '__doc__', '__name__'] Aceste nume de mai sus , sunt nume definite de interpret inainte de a incepe a comunia . Daca noi importam modulul " R0cc0.py " , se obtine asta : >>> from libraty import * >>> dir() ['__builtins__', '__doc__', '__name__', 'open', 'close', 'move'] Acum dupa cum vedeti toate functiile continute de " R0cc0.py " fac parte din " namespace " , de asta nu mai sunt deloc vizibile variabilele precedente , doar cele locale pentru functia in sine . Uitasem , aici gasiti module ( toate ) . Scuzati eventualele greseli gramaticale .1 point
This leaderboard is set to Bucharest/GMT+03:00