Do Python or Pycharm have a log of past console output? - python

I'm using Python to generate passwords for myself - I'd feel a little silly if I found out that those are available in some sort of log somewhere, presumably plaintext
Do console windows, in Pycharm or otherwise, maintain history like that?

No.
If you close your terminal, the outputs are gone. You can just go through your recent inputs by pushing the "up" arrow.
Given, that your python script will generate random passwords, this should not be an issue though.
But if you are legitimately concerned for your password safety, a real password manager should be your choice.

Could be. Most terminal emulators have a virtual "scroll buffer" that allows you to return to past outputs, thousands and thousands of lines -- everything that appeared on the screen. Obviously this text is collected, managed and stored for this use.
On Macbooks, Terminal.app will save and restore Terminal screen contents across a reboot, so they are stored somewhere. (Terminal has a system of unique session identifiers for each window, so information from multiple windows is managed.) I don't know of a way to recover the text after you close the OS X Terminal window, but that does not mean it is not sitting in some internal working file waiting for garbage collection.
The Python interactive commandline does not seem to save output; only your input is saved (in ~/.python_history), and can be reused in later sessions. As for pycharm, I don't know but since there is no way to view older session output, there's probably no reason to save it after a console window is closed.
As #Thunder wrote, you can avoid this particular problem by writing the passwords into a file, or even putting it directly in your system's clipboard. Clipboard management has its own exposures, but as long as the password is on your computer, it will be exposed somewhere.
But are you right to be worried? An exploit that gains access to your computer can easily assume full control, and looking for generated passwords in random places is certainly low on an attacker's list of priorities-- if anything, a worse-case attack with full access to your environment would be more likely to monitor keyclicks and snap to attention when you are about to authenticate to a known target like a bank, facebook, etc.
So my advice is: Don't worry too much about it. Close the console window after you generated the password, manage passwords securely from there on down (i.e. use a password manager), and use good practices and common sense to keep your computer from being pwned.

Related

Python IDLE/Terminal return back after error

When reading a book or just coding on terminal/IDLE it's common to make typo, forgot brace or comma etc. After I got error and all what I wrote before is lost.
Then I have to write down code again..
Is there any way/option to return back all what write before and just edit mistake and continue to code?
In Idle (at least my version, Python 2.7.10 on windows), you can simply copy paste your code. In the python interpreter, you can't afaik, however you can use the up/down arrow keys to recall lines you previously "submitted" (i.e. typed and pressed enter).
If I understood correctly, IDLE is a GUI (graphical user interface - a visual representation of a program rather just through text) made to have a bit more features for programming in Python. You can use IDLE interactively, like in Terminal (a.k.a command line), or use it to write your script rather than in a separate text editor. Then once you save your script/program you can do neat things like run it directly from IDLE. There's nothing more special about the Terminal, you just have to do some more work.
Furthermore, all the code you have written on your GUI is on the cache memory which is used in system to store information recently accessed by a processor. So, I suggest you write again your code you can't recover them without saving.
To avoid these kind of problems use Git!
Git is a version control system that is used for software development and other version control tasks.
IDLE's Shell window is statement rather that line oriented. One can edit any line of a statement before submitting it for execution. After executing, one may recall any statement by either a) placing the cursor anywhere on the statement and hitting Enter, or b) using the history-next and history-prev actions. On Windows, these are bound, by default, to Alt-p and Alt-p. To check on your installation, Select Options => IDLE preferences on the menu. In the dialog, select the Keys tab. Under Custom Key Bindings, find the 'histor-xyz' actions in the alphabetical list.
For short, one-off scripts, I have a scratch file called tem.py. Since I use it often, it is usually accessible via File => Recent files.

Is it possible to restrict access to globals for a block of code in python?

I would like users of my program to be able to define custom scripts in python without breaking the program. I am looking at something like this:
def call(script):
code = "access modification code" + script
exec(code)
Where "access modification code" defines a scope such that script can only access variables it instantiates itself. Is it possible to do this or something with similar functionality, such as creating a new python environment with its own scope and then receiving output from it?
Thank you for your time :)
Clarification Edit
"I want to prevent both active attacks and accidental interaction with the program variables outside the users script (hence hiding all globals). The user scripts are intended to be small and inputted as text. The return of the user script needs to be immediate, as though it were native to the program."
There's two separate problems you want to prevent in this scenario:
Prevent an outside attacker from running arbitrary code in the context of the OS user executing your program. This means preventing arbitrary code execution and privilege escalation.
Preventing a legitimate user of your program from changing the program behavior in unintended ways.
For the first problem, you need to make sure that the source of the python code you execute is the user. You shouldn't accept input from a socket, or from a file that other users can write to. You need to make sure, somehow, that it was the user who is running the program that provided the input.
Actual solutions will depend on your OS, but you may want to consider setting up restrictive file permissions, if you're storing the code in a file.
Don't ignore or downplay this problem, or your users will fall victim to virus/malware/hackers thanks to your program.
The way you solve the second problem depends on what exactly constitutes intended behaviour in your program. If you're happy with outputting simple data structures, you can run your user-inputted code in a separate process, and pass the result over a pipe in a serialization format such as JSON or YAML.
Here's a very simple example:
#remember to set restrictive file permissions on this file. This is OS-dependent
USER_CODE_FILE="/home/user/user_code_file.py"
#absolute path to python binary (executable)
PYTHON_PATH="/usr/bin/python"
import subprocess
import json
user_code= '''
import json
my_data= {"a":[1,2,3]}
print json.dumps(my_data)
'''
with open(USER_CODE_FILE,"wb") as f:
f.write(user_code)
user_result_str= subprocess.check_output([PYTHON_PATH, USER_CODE_FILE])
user_result= json.loads( user_result_str )
print user_result
This is a fairly simple solution, and it has significant overhead. Don't use this if you need to run the user code many times in a short period of time.
Ultimately, this solution is only effective against unsophisticated attackers (users). Generally speaking, there's no way to protect any user process from the user itself - nor would it make much sense.
If you really want more assurance, and want to mitigate the first problem too, you should run the process as a separate ("guest") user. This, again, is OS-dependent.
Finally a warning: avoid exec and eval to the best of your abilities. They don't protect either your program or the user against the inputted code. There's a lot of information about this on the web, just search for "python secure eval"

How to detect a host-computer change?

I'm working on a software that stores information on a local database on the computer (yeah, I know, that's incredible). Among that information, we recently added a secret token, provided by a third-party company.
Usually, when doing support the customers send us their database so we can test and reproduce errors reliably. Sadly, some of them send us their database with the secret token in it. Which means importing this database on our test platforms will actually hit the real third-party user production account, and mess with its production data (not cool).
To avoid that, we thought of detecting a host-computer change and disable the token (or erasing it from DB on startup) if the host change was detected.
The thing being, how to detect such a change (using Python, preferably) ? This is close to what one would require for a licensing system, except we probably don't need the same precision.
To make things even funnier, this would need to work for Mac OS X, Windows and Linux.
Any clue ?

Securely passing credentials to a program via plaintext file or command line

I have a program (not written by me) that I would like to use. It authenticates to an online service using a username and password that I would like to keep private. The authentication information may be passed to the program in two ways: either directly as command-line arguments or via a plaintext configuration file, neither of which seem particularly secure.
I would like to write a Python script to manage the launching of this program and keep my credentials away from the prying eyes of other users of the machine. I am running in a Linux environment. My concerns with the command-line approach are that the command line used to run the program is visible to other users via the /proc filesystem. Likewise, a plaintext configuration file could be vulnerable to reading by someone with the appropriate permissions, like a sysadmin.
Does anyone have any suggestions as to a good way to do this? If I had some way of obscuring the arguments used at the command line from the rest of the system, or a way to generate a configuration file that could be read just once (conceptually, if I could pipe the configuration data from the script to the program), I would avoid the situation where my credentials are sitting around potentially readable by someone else on the system.
Tough problem. If you have access to source code of the program in question, you can change argv[0] after startup. On most flavors of *nix, this will work.
The config file approach may be better from a security perspective.
If the config file can be specified at run time, you could generate a temp file (see mkstemp), write password there, and invoke subprocess. You could even add a small delay (to give subprocess time to do its thing) and possibly even remove the config file.
Of course the best solution is to change the program in question to read password from stdin (but it sounds like you already knew that)
About the only thing you can do in this situation is store the credentials in a text file and then deny all other users of the machine permissions to read or write it. Create a user just for this script, in fact. Encrypting doesn't do much because you still have to have the key in the script, or somewhere the script can read it, so it's the same basic attack.

Insert keypresses into the Linux console from Python

I have recently been faced with a rather odd task, one result being the necessity for the ability to use DTMF (aka "Touch Tone") tones to control a non-X Linux computer's terminal. The computer has a modem which can be accessed through ALSA, and therefore the sox "rec" program, which is what I am reading the input through. The computer in question is otherwise completely isolated, having no Ethernet or other network interfaces whatsoever. The Goertzel algorithm implementation I am using works very well, as does the eSpeak speech synthesis engine which is the only source of output; this is supposed to work with any Touch Tone phone. It reads back both input (input being octal digits, one ASCII byte at a time)and whatever the dash shell feeds back -- the prompt, the output from commands, etc., using ASCII mnemonics for control characters.
The current method that I am using for interacting with dash and the programs launched through it is the pexpect module. However, I need it to be able to, on demand, read back the entire contents of the line on which the cursor is positioned, and I do not recall pexpect being able to do this (If it is, I cannot tell.). The only other solution that I can think of is to somehow use Python to either control, or act as, the keyboard and console drivers.
Is this, indeed, the only way to go about it (and if so, is it even possible with Python?), or is there another way of having direct access to the contents of the console?
Edit: Through dumb luck, I just recently found that the SVN version of PExpect has pexpect.screen. However, it does not have any way of actually running a program under it. I'll have to keep an eye on its development.
The simple solution is to use the Linux kernel uinput interface. It allows you to insert keypresses and mouse events into the kernel, exactly as if they came from a physical human interface device. This would basically turn your application into a keyboard/mouse.
Since you are working with Python, I recommend you take a look at the python-uinput module.
If you are comfortable with binary I/O in Python, then you can certainly do the same without any libraries; just check out the /usr/include/linux/uinput.h header file for the structures involved (the interface is completely stable), and perhaps some uinput tutorials in C, too.
Note that accessing the /dev/uinput or /dev/input/uinput device (depending on your distribution) normally requires root privileges. I would personally run the Python service as a user and group dedicated to the service, and modify/add a udev rule (check all files under rules.d) to allow read-write access to the uinput device to that group, something like
SUBSYSTEM=="input", ENV{ID_INPUT}=="", IMPORT{builtin}="input_id"
KERNEL=="uinput", MODE="0660", GROUP="the-dedicated-group"
However, if your Python application simply executes programs, you should make it a terminal emulator -- for example, using this. You can do it too without any extra libraries, using the Python pty; the main work is to however simulate a terminal with ANSI escape sequences, so that applications don't get confused, and the existing terminal emulators have such code.
If you want to manipulate the contents of the console, you probably want to use curses. It's well documented here. Look at window.getch() and window.getyx().

Categories

Resources