Execute an external application as root - problem - external

Good morning:
I'm trying to run an external application that needs to be executed
as root. I have to read the lines from exit after the execution
of this application but it says "permission denied", as if the
its not been done correctly. I've been thinking over a time
and I can not move forward. The code is as follows:
process = Runtime.getRuntime().exec("su");
String[] command = {external application command};
process = Runtime.getRuntime().exec(comando);
InputStream inputStream = process.getInputStream();
BufferedReader bufferedReader = null;
try
{
bufferedReader = new BufferedReader(new
InputStreamReader(inputStream),8192);
String line = null;
while ((line = bufferedReader.readLine()) != null)
{
System.out.println("read line:"+line );
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
process.waitFor();
Does anyone know why not let me run the command?
Thanks.

Do you have any errors when trying to run su? (I imagine you would, since su will probably open the terminal directly to prompt for a password; su won't just read standard input for a password.)
Do you have any errors or success when trying to run a simple program, like /usr/bin/cat /etc/passwd? Might as well start simple and see if you can get it to work before trying for more complicated programs.

what about trying
sudo -iu root
instead of su

Related

Getting "Access denied for user..." every 2nd hit

I'm trying to use dapper with mysql in .net core 1.0. I'm using this mysql connector: https://github.com/bgrainger/MySqlConnector
I know the connector is in alpha but I was wondering if anyone had a similar issue when using it together with dapper.
This is my simple model:
public List<GeneralModel> GetAllLists()
{
try
{
using (DbConnection connection = new MySqlConnection("Server=localhost;Database=lists;Uid=Unnamed;Pwd=lol;"))
{
return connection.Query<GeneralModel>("SELECT * FROM lists.general").ToList();
}
}
catch (Exception)
{
throw;
}
}
And this is the controller:
public IActionResult Index()
{
GeneralModel GenRepo = new GeneralModel();
return View(GenRepo.GetAllLists());
}
When I go to the index page for the first time, it works. If I refresh, I get an "Access denied for user...". I have no idea what could be causing the error. I don't think the problem is in my code.
Edit:
I guess the problem is in the connector, since this also returns the error after a refresh:
List<GeneralModel> lists = new List<GeneralModel>();
using (DbConnection connection = new MySqlConnection("Server=localhost;Database=lists;Uid=Unnamed;Pwd=lol;"))
{
using (DbCommand myCommand = connection.CreateCommand())
{
myCommand.CommandText = "SELECT * FROM lists.general";
connection.Open();
using (DbDataReader myReader = myCommand.ExecuteReader())
{
while (myReader.Read())
{
GeneralModel tmpGen = new GeneralModel();
tmpGen.name = myReader["name"].ToString();
tmpGen.description = myReader["description"].ToString();
tmpGen.language = myReader["language "].ToString();
lists.Add(tmpGen);
}
}
connection.Close();
}
}
return lists;
This bug was caused by MySqlConnector not correctly handling the fast path for a COM_CHANGE_USER packet.
MySQL Server (versions 5.6 and 5.7) doesn't appear to immediately accept the user's credentials, but always returns an Authentication Method Switch Request Packet. MariaDB (which you are using) does implement the fast path and immediately returns an OK packet.
The connector has now been updated to handle this response and should stop throwing the spurious "Access Denied" exceptions. The fix is in 0.1.0-alpha09.

Can't connect to MySQL/MariaDB database from vibed app

All work fine if I use custom main ( void main() instead of shared static this() ).
With default main I am getting "Access Violation" error. It's look like MySQL not allow connecting to it from localhost, but in my.ini I added string:
bind-address = 127.0.0.1
code, if it's help:
import std.stdio;
import std.path;
import std.file;
import std.string;
import dini;
import vibe.d;
import colorize;
import ddbc.all;
shared static this()
{
auto settings = new HTTPServerSettings;
settings.port = 8080;
settings.bindAddresses = ["::1", "127.0.0.1"];
listenHTTP(settings, &hello);
auto parseconfig = new ParseConfig();
auto db = new DBConnect(parseconfig);
}
void hello(HTTPServerRequest req, HTTPServerResponse res)
{
res.writeBody("Hello, World!");
}
class ParseConfig
{
string dbname;
string dbuser;
string dbpass;
string dbhost;
string dbport;
this()
{
try
{
//getcwd do not return correct path if run from task shoulder
string confpath = buildPath((thisExePath[0..((thisExePath.lastIndexOf("\\"))+1)]), "config.ini");
//writefln(thisExePath[0..((thisExePath.lastIndexOf("\\"))+1)]); // get path without extention +1 is for getting last slash
//string confpath = buildPath(thisExePath, "config.ini");
if (!exists(confpath))
{
writeln("ERROR: config.ini do not exists");
}
auto config = Ini.Parse(confpath);
try
{
this.dbname = config.getKey("dbname");
this.dbuser = config.getKey("dbuser");
this.dbpass = config.getKey("dbpass");
this.dbhost = config.getKey("dbhost");
this.dbport = config.getKey("dbport");
}
catch (Exception msg)
{
cwritefln("ERROR: Can't parse config: %s".color(fg.red), msg.msg);
}
}
catch(Exception msg)
{
cwriteln(msg.msg.color(fg.red));
core.thread.Thread.sleep( dur!("msecs")(1000));
}
}
}
class DBConnect
{
Statement stmt;
ParseConfig parseconfig;
this(ParseConfig parseconfig)
{
try
{
this.parseconfig = parseconfig;
MySQLDriver driver = new MySQLDriver();
string url = MySQLDriver.generateUrl(parseconfig.dbhost, to!short(parseconfig.dbport), parseconfig.dbname);
string[string] params = MySQLDriver.setUserAndPassword(parseconfig.dbuser, parseconfig.dbpass);
DataSource ds = new ConnectionPoolDataSourceImpl(driver, url, params);
auto conn = ds.getConnection();
scope(exit) conn.close();
stmt = conn.createStatement();
writefln("\n[Database connection OK]");
}
catch (Exception ex)
{
writefln(ex.msg);
writeln("Could not connect to DB. Please check settings");
}
}
}
Also I run next command:
GRANT ALL PRIVILEGES ON *.* TO 'root'#'%' IDENTIFIED BY 'password' WITH GRANT OPTION;
FLUSH PRIVILEGES;
also I tried different bind-address like: 0.0.0.0 and localhost but without result. After every new binding I did restart of MySQL service.
I am using this driver http://code.dlang.org/packages/ddbc
What's wrong?
To continue on my comment ( Can't connect to MySQL/MariaDB database from vibed app ).
I just tested, and it's definitely the event loop ;)
Instead of:
auto parseconfig = new ParseConfig();
auto db = new DBConnect(parseconfig);
Just do:
runTask({
auto parseconfig = new ParseConfig();
auto db = new DBConnect(parseconfig);
});
Worked for me (DMD 2.067.0 / Vibe 0.7.23 / ddbc 0.2.24 / colorize & dini master).
To answer your comment ( Can't connect to MySQL/MariaDB database from vibed app) : the event loop starts inside the main function.
What happens when you launch a D application ? The entry point is a C main inside the runtime, which initialize it (the runtime), including module constructor, run the unittest (if you've compiled with -unittest), then call your main (which name is "_Dmain" - useful to know if you want to set a breakpoint with GDB).
When Vibe.d's main is called, it parses command line argument, an optional config file, and finally, starts the event loop. Any code that wish to run once the event loop has started should use runTask and similar, or createTimer. They should not call the code directly from the static constructor (it's actually one of the most common mistake when starting with Vibe.d).
I ran into an issue that could be related while developing mysql-lited, an alternative MySQL/MariaDB driver.
The issue I think is related to a module initialization order bug in phobos/SHA1, which I believe is still open in 2.067.1. The suggested work-around is to use VibeCustomMain instead, and define your own main(). You can just copy the defaul main() from appmain.d and use that.
Alternatively you could try mysql-lited and see if that works better for you.

Getting the cannot callsendredirect() after the response has been committed

Again my question related with the same project which i am doing for the report tracking system getting the below error in the tomcat logs after accessing the login page which is redirect towards "userloginmid.jsp".The code as shown below in the same window.
Please provide the solution for the same if possible.
<%# page import="java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %>
<%
String userName = request.getParameter("userName");
String password = request.getParameter("password");
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "report_tracking";
String driver = "com.mysql.jdbc.Driver";
String username = "root";
String userPassword = "root";
java.util.Date now = new java.util.Date();
String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
String strDateNew = sdf.format(now) ;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,username,userPassword);
Statement st = conn.createStatement();
String strQuery = "select * from userregister where username='"+userName+"' and password='"+password+"'";
out.println(strQuery);
ResultSet rs = st.executeQuery(strQuery);
if(rs.next())
{
int userid=rs.getInt(1);
String user=rs.getString(2);
session.setAttribute("userid",userid);
session.setAttribute("username",user);
session.setAttribute("intime",strDateNew);
String queryString = "INSERT INTO admin set userid="+userid+",intime='"+strDateNew+"'";
int i = st.executeUpdate(queryString);
if(i>0)
{
response.sendRedirect("welcome.jsp");
}
}
response.sendRedirect("login.jsp");
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
As all said there are lot of loopholes in your code.
But the answer to your quesion is
sendRedirect requires a return statement
So change your lines of code to
response.sendRedirect( "welcome.jsp"); return; and
response.sendRedirect("login.jsp"); return;
Also read this .
There are a lot of problems with your code.
First, the explanation of your stated problem, redirecting after committing a response:
When the HTTP headers are already sent to the client (read about the HTTP protocol if you don't know it yet), they are out and cannot be pulled back. You're coding your sample in a jsp, which is the VIEW part of your architecture - and at least between the "page import" and the code part there's a newline which might trigger the server to flush its buffers to the client. Once that's done, the HTTP headers are gone and you cannot redirect any more.
Workaround: Don't implement this routine in a jsp, but in a servlet (or use a decent framework that handles this problem for you. Any of the current will suffice).
Now about some of the problems that your code has:
Please read about SQL injection. Think of someone posting
usernames like someone'; someone' OR '0' = '0 or similar (just
making them up as I go)
Once you get your connection and run in to any error, you won't clean
up the connection (e.g. you will leak connections on any exception)
You seem to be storing clear text passwords. Definitely a no-go as
soon as someone else than you will have an account

Exception when sending big soap request

There is a web-service deployed on tomcat 6 and exposed via apache-cxf 2.3.3. A generated sources stubs using wsdl2java to be able to call this service.
Things seemed fine until I sent big request(~1Mb). This request wasn't processed and failing with exception:
Interceptor for {http://localhost/}ResourceAllocationServiceSoapService has thrown
exception, unwinding now org.apache.cxf.binding.soap.SoapFault:
Error reading XMLStreamReader.
...
com.ctc.wstx.exc.WstxEOFException: Unexpected EOF in prolog
at [row,col {unknown-source}]: [1,0]
Is some kind of max request length here, I'm totally stuck with it.
Vladimir's suggestion worked. This code below will help others with understanding where to put the 1000000.
public void handleMessage(SoapMessage message) throws Fault {
// Get message content for dirty editing...
InputStream inputStream = message.getContent(InputStream.class);
if (inputStream != null)
{
String processedSoapEnv = "";
// Cache InputStream so it can be read independently
CachedOutputStream cachedInputStream = new CachedOutputStream(1000000);
try {
IOUtils.copy(inputStream,cachedInputStream);
inputStream.close();
cachedInputStream.close();
InputStream tmpInputStream = cachedInputStream.getInputStream();
try{
String inputBuffer = "";
int data;
while((data = tmpInputStream.read()) != -1){
byte x = (byte)data;
inputBuffer += (char)x;
}
/**
* At this point you can choose to reformat the SOAP
* envelope or simply view it just make sure you put
* an InputStream back when you done (see below)
* otherwise CXF will complain.
*/
processedSoapEnv = fixSoapEnvelope(inputBuffer);
}
catch(IOException e){
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Re-set the SOAP InputStream with the new envelope
message.setContent(InputStream.class,new ByteArrayInputStream( processedSoapEnv.getBytes()));
/**
* If you just want to read the InputStream and not
* modify it then you just need to put it back where
* it was using the CXF cached inputstream
*
* message.setContent(InputStream.class,cachedInputStream.getInputStream());
*/
}
}
I figured out what was wrong. Actually it was bug inside interceptor's code:
CachedOutputStream requestStream = new CachedOutputStream()
When I replaced this with
CachedOutputStream requestStream = new CachedOutputStream(1000000);
things start working fine.
So the request was just trunkated during copying of streams.
I run into same issue of geting "com.ctc.wstx.exc.WstxEOFException: Unexpected EOF in prolog" when using CachedOutputStream class.
Looking at sources of CachedOutputStream class the threshold is used to switch between storing stream's data from "in memory" to "a file".
Assuming stream operates on data that exceeds threshold it gets stored in a file thus following code is going to break
IOUtils.copy(inputStream,cachedInputStream);
inputStream.close();
cachedInputStream.close(); //closes the stream, the file on disk gets deleted
InputStream tmpInputStream = cachedInputStream.getInputStream(); //returned tmpInputStream is brand *empty* one
// ... reading tmpInputStream here will produce WstxEOFException
Increasing 'threshold' does help as all stream data is stored into memory and in such scenario calling cachedInputStream.close() does not really close the underlying stream implementation so one can still read from it later on.
Here is 'fixed' version of above code (at least it worked without exception for me)
IOUtils.copy(inputStream,cachedInputStream);
inputStream.close();
InputStream tmpInputStream = cachedInputStream.getInputStream();
cachedInputStream.close();
// reading from tmpInputStream here works fine
Temporary file gets deleted when close() is called on tmpInputStream and there are no more other references to it, see source code of CachedOutputStream.maybeDeleteTempFile()

JDBC Driver in OSGI (Eclipse IDE)

I am having some problems with getting my OSGI programs to recognzie/utilize the mysql jdbc driver.
I have a bundle that is speficcally for entering data into a mysql database. I have copied over all the same methods as in a test program (non-OSGI). I am not able to create a connection suing DriverManager.getConnection().
I have added the driver to the class path andhave tried all the solutions on this site such as using Class.forName(). Possibly I am inputting the wrong string arg into forName().
public void createConn(String URL, String DBName, String username, String password){
try {
Class.forName("mysql-connector-java-5.1.14-bin.jar");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
try {
conn = DriverManager.getConnection(URL + DBName,username,password);
System.out.println("Connection Created");
stmt = conn.createStatement();
System.out.println("Statement Created");
//data = new ApplianceData();
//flag = true;
//this.writeThread = new Thread();
//writeThread.start();
} catch (SQLException e) {
System.err.println(e.getMessage());
}
}
Can someone tell me the argument they used in Class.forName();
Does anybody have a solution to this problem or encountered this?
Thanks, that took care of the classNotFound Exception. Now I have an error stating that the driver is not suitable. I know OSGI has some issues with drivers etc. Can someone recommend a way to circumvent this?
I have placed the jdbc jar in the java installation bin folders, and in the bin folder of the bundle.
ClassLoader DBHCL = ClassLoader.getSystemClassLoader();
DBHCL.loadClass("com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver", true, DBHCL).newInstance();
System.out.println("Class Loaded");
//DriverManager.getDriver("jdbc:mysql://localhost/timedb");
//System.out.println("Driver Gotten");
conn = DriverManager.getConnection(URL + DBName,username,password);
System.out.println("Connection Created");
stmt = conn.createStatement();
System.out.println("Statement Created");
connFlag = true;
Console Output, Error:
osgi> start 7
Data Base Service (MYSQL) Starting
Class Loaded
No suitable driver found for jdbc:mysql://localhost/timedb
Exception in thread "Thread-1" INSERT INTO appliance1...
Does anybody have any insight into this problem?
Thanks
Class.forName(String) takes a fully qualified class name, not a jar file. You should use something like
Class.forName("com.mysql.jdbc.Driver");
i know this has 3 years but i'm answering just in case someone googles it.
so the problem is that the bundle does not see the jar from the classloade, so you need to import its packages in the manifest.
the way i did, is i created a separate bundle containing mysql connector jar.
newProject> plugin from existing jar; then i added all of its packages to "exported packages" in its manifest file. Then in my first bundle i added all the packages of the connector to "imported packages" and it worked.