Unix & Linux Stack Exchange
Q&A for users of Linux, FreeBSD and other Unix-like operating systems
Latest Questions
1
votes
1
answers
42
views
Fedora 40 - Apache Perl CGI - Open for writing fails
Last week, I upgraded my Linux file server from Fedora 39 to Fedora 40, and several CGI applications written in Perl stopped working. I first noticed it when Foswiki could not show any pages, because it was unable to open its log file. After unsuccessfully pursuing a theory that the system upgrade h...
Last week, I upgraded my Linux file server from Fedora 39 to Fedora 40, and several CGI applications written in Perl stopped working. I first noticed it when Foswiki could not show any pages, because it was unable to open its log file. After unsuccessfully pursuing a theory that the system upgrade had resulted in some incompatibility between (updated) perl libraries and the (same old) Foswiki application, I discovered that an application that I had written myself had the same problem.
I have now reduced it to a very small program, the core of which is just these few lines:
my $file_to_write = "/tmp/writetest.txt";
unless (open(OUTFILE, ">>", $file_to_write)) {
print "Failed to open (for append) $file_to_write.
\n";
}
printf "%s %s Write test to $file_to_write\n", ljpDate(), ljpTime();
printf OUTFILE "%s %s Write test\n", ljpDate(), ljpTime();
close OUTFILE;
print "Write completed
\n";
It appears that the open succeeds (I do not get the "Failed .." message), but nothing is written to the file, even though it has mode 666 (-rw-rw-rw-) and it is owned by apache:apache. If the file exists, it is untouched, and if it does not exist, it is not created.
If I run the script from the command line (./writetest.cgi) everything works as expected.
This worked last week before the update. Is there some new sandboxing feature that kills my applications ?
I should add that SElinux is disabled on this system, as confirmed by sestatus
.
Lars Poulsen
(357 rep)
Nov 15, 2024, 12:53 AM
• Last activity: Nov 15, 2024, 09:36 PM
0
votes
1
answers
77
views
Can Apache 2.4 run setuid root CGI binaries?
Note that I'm not asking about suEXEC, because the binary must be setuid root, and suEXEC doesn't allow root to execute CGI programs. I need to carry out a one-time configuration during system installation, via Apache. To do this, the client POSTs a request to a setuid root binary (compiled C++, own...
Note that I'm not asking about suEXEC, because the binary must be setuid root, and suEXEC doesn't allow root to execute CGI programs.
I need to carry out a one-time configuration during system installation, via Apache. To do this, the client POSTs a request to a setuid root binary (compiled C++, owned by root:root, mode u+s). This almost works: the script does run as root, and modifies system files as required. However, it does *not* return
stdout
to Apache, so Apache thinks that it dies without producing any headers. Apache's error log contains nothing useful (just the usual 'no headers' message), and the CGI log/debug file also contains nothing useful (it just gives an empty %response
, with nothing shown for %stdout
or %stderr
).
I've tested the binary by running it on the server from a script which supplies the required POST data on stdin, and records stdout and stderr. It also runs it under valgrind
. However, valgrind can't (easily) run setuid binaries, so I revert the binary to a plain 755 mode, and run the test script as root. In these conditions, the binary performs exactly as expected: valgrind reports no errors, stdout
is a valid HTML response with status 200, and stderr
contains only the valgrind output.
Any insight appreciated.
QF0
(391 rep)
Jul 20, 2024, 05:38 PM
• Last activity: Jul 21, 2024, 11:39 AM
0
votes
1
answers
194
views
What are Lynx CGI scripts?
In `lynx.cfg`, it contains: ``` .h1 CGI scripts # These settings control Lynx's ability to execute various types of scripts. .h2 LOCAL_EXECUTION_LINKS_ALWAYS_ON .h2 LOCAL_EXECUTION_LINKS_ON_BUT_NOT_REMOTE # Local execution links and scripts are by default completely disabled, # unless a change is ma...
In
lynx.cfg
, it contains:
.h1 CGI scripts
# These settings control Lynx's ability to execute various types of scripts.
.h2 LOCAL_EXECUTION_LINKS_ALWAYS_ON
.h2 LOCAL_EXECUTION_LINKS_ON_BUT_NOT_REMOTE
# Local execution links and scripts are by default completely disabled,
# unless a change is made to the userdefs.h file to enable them or
# the configure script is used with the corresponding options
# (-enable-exec-links and -enable-exec-scripts).
# See the Lynx source code distribution and the userdefs.h
# file for more detail on enabling execution links and scripts.
#
# If you have enabled execution links or scripts the following
# two variables control Lynx's action when an execution link
# or script is encountered.
#
# If LOCAL_EXECUTION_LINKS_ALWAYS_ON is set to TRUE any execution
# link or script will be executed no matter where it came from.
# This is EXTREMELY dangerous. Since Lynx can access files from
# anywhere in the world, you may encounter links or scripts that
# will cause damage or compromise the security of your system.
#
# If LOCAL_EXECUTION_LINKS_ON_BUT_NOT_REMOTE is set to TRUE only
# links or scripts that reside on the local machine and are
# referenced with a URL beginning with "file://localhost/" or meet
# TRUSTED_EXEC or ALWAYS_TRUSTED_EXEC rules (see below) will be
# executed. This is much less dangerous than enabling all execution
# links, but can still be dangerous.
#
#LOCAL_EXECUTION_LINKS_ALWAYS_ON:FALSE
#LOCAL_EXECUTION_LINKS_ON_BUT_NOT_REMOTE:FALSE
.h2 TRUSTED_EXEC
# If LOCAL_EXECUTION_LINK_ON_BUT_NOT_REMOTE is TRUE, and no TRUSTED_EXEC
# rule is defined, it defaults to "file://localhost/" and any lynxexec
# or lynxprog command will be permitted if it was referenced from within
# a document whose URL begins with that string. If you wish to restrict the
# referencing URLs further, you can extend the string to include a trusted
# path. You also can specify a trusted directory for http URLs, which will
# then be treated as if they were local rather than remote. For example:
#
# TRUSTED_EXEC:file://localhost/trusted/
# TRUSTED_EXEC:http://www.wfbr.edu/trusted/
#
# If you also wish to restrict the commands which can be executed, create
# a series of rules with the path (Unix) or command name (VMS) following
# the string, separated by a tab. For example:
#
# Unix:
# ====
# TRUSTED_EXEC:file://localhost//bin/cp
# TRUSTED_EXEC:file://localhost//bin/rm
# VMS:
# ===
# TRUSTED_EXEC:file://localhost/copy
# TRUSTED_EXEC:file://localhost/delete
#
# Once you specify a TRUSTED_EXEC referencing string, the default is
# replaced, and all the referencing strings you desire must be specified
# as a series. Similarly, if you associate a command with the referencing
# string, you must specify all of the allowable commands as a series of
# TRUSTED_EXEC rules for that string. If you specify ALWAYS_TRUSTED_EXEC
# rules below, you need not repeat them as TRUSTED_EXEC rules.
#
# If EXEC_LINKS and JUMPFILE have been defined, any lynxexec or lynxprog
# URLs in that file will be permitted, regardless of other settings. If
# you also set LOCAL_EXECUTION_LINKS_ON_BUT_NOT_REMOTE:TRUE and a single
# TRUSTED_EXEC rule that will always fail (e.g., "none"), then *ONLY* the
# lynxexec or lynxprog URLs in JUMPFILE (and any ALWAYS_TRUSTED_EXEC rules,
# see below) will be allowed. Note, however, that if Lynx was compiled with
# CAN_ANONYMOUS_JUMP set to FALSE (default is TRUE), or -restrictions=jump
# is included with the -anonymous switch at run time, then users of an
# anonymous account will not be able to access the jumps file or enter
# 'j'ump shortcuts, and this selective execution feature will be overridden
# as well (i.e., they will only be able to access lynxexec or lynxprog
# URLs which meet any ALWAYS_TRUSTED_EXEC rules).
#
#TRUSTED_EXEC:none
.h2 ALWAYS_TRUSTED_EXEC
# If EXEC_LINKS was defined, any lynxexec or lynxprog URL can be made
# always enabled by an ALWAYS_TRUSTED_EXEC rule for it. This is useful for
# anonymous accounts in which you have disabled execution links generally,
# and may also have disabled jumps file links, but still want to allow
# execution of particular utility scripts or programs. The format is
# like that for TRUSTED_EXEC. For example:
#
# Unix:
# ====
# ALWAYS_TRUSTED_EXEC:file://localhost//usr/local/kinetic/bin/usertime
# ALWAYS_TRUSTED_EXEC:http://www.more.net//usr/local/kinetic/bin/who.sh
# VMS:
# ===
# ALWAYS_TRUSTED_EXEC:file://localhost/usertime
# ALWAYS_TRUSTED_EXEC:http://www.more.net/show users
#
# The default ALWAYS_TRUSTED_EXEC rule is "none".
#
#ALWAYS_TRUSTED_EXEC:none
.h2 TRUSTED_LYNXCGI
# Unix:
# =====
# TRUSTED_LYNXCGI rules define the permitted sources and/or paths for
# lynxcgi links (if LYNXCGI_LINKS is defined in userdefs.h). The format
# is the same as for TRUSTED_EXEC rules (see above). Example rules:
#
# TRUSTED_LYNXCGI:file://localhost/
# TRUSTED_LYNXCGI:/usr/local/etc/httpd/cgi-bin/
# TRUSTED_LYNXCGI:file://localhost//usr/local/www/cgi-bin/
#
# VMS:
# ====
# Do not define this.
#
# The default TRUSTED_LYNXCGI rule is "none".
#
TRUSTED_LYNXCGI:none
.h2 LYNXCGI_ENVIRONMENT
# Unix:
# =====
# LYNXCGI_ENVIRONMENT adds the current value of the specified
# environment variable to the list of environment variables passed on to the
# lynxcgi script. Useful variables are HOME, USER, etc... If proxies
# are in use, and the script invokes another copy of lynx (or a program like
# wget) in a subsidiary role, it can be useful to add http_proxy and other
# *_proxy variables.
#
# VMS:
# ====
# Do not define this.
#
#LYNXCGI_ENVIRONMENT:
.h2 LYNXCGI_DOCUMENT_ROOT
# Unix:
# =====
# LYNXCGI_DOCUMENT_ROOT is the value of DOCUMENT_ROOT that will be passed
# to lynxcgi scripts. If set and the URL has PATH_INFO data, then
# PATH_TRANSLATED will also be generated. Examples:
# LYNXCGI_DOCUMENT_ROOT:/usr/local/etc/httpd/htdocs
# LYNXCGI_DOCUMENT_ROOT:/data/htdocs/
#
# VMS:
# ====
# Do not define this.
#
#LYNXCGI_DOCUMENT_ROOT:
What type of script is Lynx referring to in this context? It doesn't appear to be JavaScript (and several sources indicate that Lynx does not support it).
Aren't CGI scripts primarily executed on the server side?
Why is a web browser like Lynx involved with them?
Ignis Incendio
(153 rep)
Jul 4, 2023, 08:31 AM
• Last activity: Jul 4, 2023, 10:17 AM
0
votes
1
answers
140
views
lighttpd: ajax request prints the content of cgi script instead of running it
I am using lighttpd version 1.4.55 within an ARM environment. I created an HTML pages in which there is a button used to download some json data. This button trigger a submit form that calls a cgi script. This script has to take the output of the form and write into a file. But when I click on the b...
I am using lighttpd version 1.4.55 within an ARM environment. I created an HTML pages in which there is a button used to download some json data. This button trigger a submit form that calls a cgi script. This script has to take the output of the form and write into a file. But when I click on the button, the response text of the xhr request is the content of the cgi script instead of the printf message. The cgi has the execution permissions.
I divided the folders in the following way:
•mnt/userfs/lighttpd/
•www
• /scripts_files
json.cgi
• /html_files
•css folder
•js folder
• upload_dir
• index.html
• /admin
• password_file
• main.html
• file_upload.html
• /user
• password_file
• main.html
• file_upload.html
•lighttpd.conf
•log
•error.log
The button that calls the form is the following:
The button calls a function and then download the file created with .cgi script.
The function of the ajax request:
function submit_form()
{
var div1 = document.getElementById("extern");
var data = {};
data = recursive_f(div1, 0, 0);
output = JSON.stringify(data);
var xhr_lv = new XMLHttpRequest();
xhr_lv.onreadystatechange=function()
xhr_lv.open("POST", "/scripts_files/json.cgi", true);
xhr_lv.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr_lv.send(output);
}
C program that generates the .cgi script:
#include
#include
#include
int main(int argc, char* argv[])
{
char* post_len_v = getenv("CONTENT_LENGTH");
long post_len = strtol(post_len_v, NULL, 10);
char* post_msg = (char*)malloc(post_len + 1);
FILE *fp;
if (!post_msg)
{
return 0;
}
fgets(post_msg, post_len + 1, stdin);
fp = fopen("/mnt/userfs/lighttpd/www/scripts_files/conf.json", "w");
fprintf(fp, "%s", post_msg);
fclose(fp);
printf("Content-type: application/json\n\n");
return 0;
}
Lighttpd configuration file:
server.modules = (
"mod_indexfile",
"mod_access",
"mod_redirect",
"mod_alias",
"mod_compress",
"mod_dirlisting",
"mod_staticfile",
"mod_auth",
"mod_authn_file",
"mod_accesslog",
"mod_cgi",
#"mod_rewrite",
#"mod_status"
#"mod_fastcgi"
)
server.document-root = "/mnt/userfs/lighttpd/www"
server.errorlog = "/mnt/userfs/lighttpd/log/error.log"
server.breakagelog = "/mnt/userfs/lighttpd/log/breakage.log"
index-file.names = ("index.html", "main.html", "file_upload.html")
mimetype.assign = (
".class" => "application/java-vm",
".js" => "application/javascript",
".mjs" => "application/javascript",
".json" => "application/json",
".jsonld" => "application/ld+json",
".wmx" => "video/x-ms-wmx",
".wvx" => "video/x-ms-wvx",
".avi" => "video/x-msvideo",
".movie" => "video/x-sgi-movie",
".ice" => "x-conference/x-cooltalk",
".sisx" => "x-epoc/x-sisx-app",
".vrm" => "x-world/x-vrml",
"README" => "text/plain; charset=utf-8",
"Makefile" => "text/x-makefile; charset=utf-8",
# enable caching for unknown mime types:
#"" => "application/octet-stream"
)
mimetype.use-xattr = "disable"
url.access-deny = ( "~", ".inc" )
static-file.exclude-extensions = ( ".php", ".pl", ".fcgi" )
server.port = 80
server.username = "midac"
server.groupname = "midac"
#compress.cache-dir = "/var/cache/lighttpd/compress/"
compress.filetype = ( "application/javascript", "text/css", "text/html", "text/plain" )
cgi.assign = ( ".cgi" => "" )
$HTTP["url"] =~ "/admin" {
auth.backend = "htpasswd"
auth.backend.htpasswd.userfile = "/mnt/userfs/lighttpd/www/admin/.htpasswd"
auth.require = ( "/admin" => (
"method" => "basic",
"realm" => "main",
"require" => "valid-user")
)
}
$HTTP["url"] =~ "/user" {
auth.backend = "htpasswd"
auth.backend.htpasswd.userfile = "/mnt/userfs/lighttpd/www/user/.htpasswd"
auth.require = ( "/user" => (
"method" => "basic",
"realm" => "main",
"require" => "valid-user")
)
}
$HTTP["url"] =~ "/user2" {
auth.backend = "htpasswd"
auth.backend.htpasswd.userfile = "/mnt/userfs/lighttpd/www/user2/.htpasswd"
auth.require = ( "/user2" => (
"method" => "basic",
"realm" => "main",
"require" => "valid-user")
)
}
I tried also with sample cgi script, but I got this result:
#!/bin/sh
echo hello
so the content of the cgi script.
The type of POST request is octet-stream, seems that cgi_mod not working properly, or I missed something on the configuration file of lighttpd.
Any suggestions?
marco
(1 rep)
Mar 9, 2023, 10:40 AM
• Last activity: Jun 13, 2023, 04:03 AM
0
votes
1
answers
635
views
Disable CGI script buffering for web browsers
I have a tiny CGI script written in Perl which prints numbers from 1 to 10 with 1 second interval: ``` root@debian-s-1vcpu-1gb-fra1-01:~# cat /usr/lib/cgi-bin/test #!/usr/bin/perl use strict; local $|=1; print "Content-encoding: none\nContent-type: text/plain\n\n"; #print "Content-type: text/plain\n...
I have a tiny CGI script written in Perl which prints numbers from 1 to 10 with 1 second interval:
root@debian-s-1vcpu-1gb-fra1-01:~# cat /usr/lib/cgi-bin/test
#!/usr/bin/perl
use strict;
local $|=1;
print "Content-encoding: none\nContent-type: text/plain\n\n";
#print "Content-type: text/plain\n\n";
for ( my $i = 1 ; $i GET /cgi-bin/test HTTP/1.1
> Host: 164.90.236.255
> Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
> Accept-Encoding: gzip, deflate
> Accept-Language: en-US,en;q=0.5
> Connection: keep-alive
> Upgrade-Insecure-Requests: 1
> User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0
>
< HTTP/1.1 200 OK
< Date: Mon, 24 Jan 2022 12:19:56 GMT
< Server: Apache/2.4.25 (Debian)
< Content-encoding: none
< Keep-Alive: timeout=5, max=100
< Connection: Keep-Alive
< Transfer-Encoding: chunked
< Content-Type: text/plain
<
1
2
3
4
5
6
7
8
9
10
* Connection #0 to host 164.90.236.255 left intact
$
Server is Apache 2.4.25
with mod_deflate
disabled.
What might cause such behavior? How to disable CGI script buffering in web browsers? Perhaps there is a Response Header which allows one to control this behavior.
Martin
(8156 rep)
Jan 24, 2022, 12:40 PM
• Last activity: Jan 24, 2022, 02:19 PM
1
votes
2
answers
594
views
CGI (Commong Gateway Interface) program wont run from HTML page, getting "Forbidden" permission
I'm trying to run this example CGI program that is from this Wikipedia page https://en.wikipedia.org/wiki/Common_Gateway_Interface The HTML code is as follows, the file is named "add.html" ``` Enter two numbers to add First Number: Second Number: Add ``` while the CGI code is as follows, the file is...
I'm trying to run this example CGI program that is from this Wikipedia page https://en.wikipedia.org/wiki/Common_Gateway_Interface
The HTML code is as follows, the file is named "add.html"
Does anybody have any advice on how to make the script work? Or perhaps could link me to cgi scrip that works, i'm at my wits end and I have no idea what else to try.
I would very much appreciate any input, Thank you.
**Update:** I've moved the files into the following directory, gave permission to run and reloaded apache using the following commands
However I still encounter the same problem when pressing the add button
The following are the last two error codes that apache gave out
Enter two numbers to add
First Number:
Second Number:
Add
while the CGI code is as follows, the file is called "add.cgi"
#!/usr/bin/env python3
import cgi, cgitb
cgitb.enable()
input_data = cgi.FieldStorage()
print('Content-Type: text/html') # HTML is following
print('') # Leave a blank line
print('Addition Results
')
try:
num1 = int(input_data["num1"].value)
num2 = int(input_data["num2"].value)
except:
print('Sorry, the script cannot turn your inputs into numbers (integers).')
raise SystemExit(1)
print('{0} + {1} = {2}'.format(num1, num2, num1 + num2))
My apache config files are located at
User@User-VirtualBox:/etc/apache2/sites-available$ sudo vim 000-default.conf
and the code there is as follows
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
#ServerName www.example.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
Options ExecCGI Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
AddHandler cgi-script .cgi
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
And the Apache config files are located here
User@User-VirtualBox:/etc/apache2$ sudo vim apache2.conf
The code in the apache2.conf is as follows
# This is the main Apache server configuration file. It contains the
# configuration directives that give the server its instructions.
# See http://httpd.apache.org/docs/2.4/ for detailed information about
# the directives and /usr/share/doc/apache2/README.Debian about Debian specific
# hints.
#
#
# Summary of how the Apache 2 configuration works in Debian:
# The Apache 2 web server configuration in Debian is quite different to
# upstream's suggested way to configure the web server. This is because Debian's
# default Apache2 installation attempts to make adding and removing modules,
# virtual hosts, and extra configuration directives as flexible as possible, in
# order to make automating the changes and administering the server as easy as
# possible.
# It is split into several files forming the configuration hierarchy outlined
# below, all located in the /etc/apache2/ directory:
#
# /etc/apache2/
# |-- apache2.conf
# | `-- ports.conf
# |-- mods-enabled
# | |-- *.load
# | `-- *.conf
# |-- conf-enabled
# | `-- *.conf
# `-- sites-enabled
# `-- *.conf
#
#
# * apache2.conf is the main configuration file (this file). It puts the pieces
# together by including all remaining configuration files when starting up the
# web server.
#
# * ports.conf is always included from the main configuration file. It is
# supposed to determine listening ports for incoming connections which can be
# customized anytime.
#
# * Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/
# directories contain particular configuration snippets which manage modules,
# global configuration fragments, or virtual host configurations,
# respectively.
#
# They are activated by symlinking available configuration files from their
# respective *-available/ counterparts. These should be managed by using our
# helpers a2enmod/a2dismod, a2ensite/a2dissite and a2enconf/a2disconf. See
# their respective man pages for detailed information.
#
# * The binary is called apache2. Due to the use of environment variables, in
# the default configuration, apache2 needs to be started/stopped with
# /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not
# work with the default configuration.
# Global configuration
#
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE! If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the Mutex documentation (available
# at );
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
#ServerRoot "/etc/apache2"
#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
#Mutex file:${APACHE_LOCK_DIR} default
#
# The directory where shm and other runtime files will be stored.
#
DefaultRuntimeDir ${APACHE_RUN_DIR}
#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}
#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300
#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On
#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100
#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5
# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a
# container, that host's errors will be logged there and not here.
#
ErrorLog ${APACHE_LOG_DIR}/error.log
#
# LogLevel: Control the severity of messages logged to the error_log.
# Available values: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the log level for particular modules, e.g.
# "LogLevel info ssl:warn"
#
LogLevel warn
# Include module configuration:
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf
# Include list of ports to listen on
Include ports.conf
# Sets the default security model of the Apache2 HTTPD server. It does
# not allow access to the root filesystem outside of /usr/share and /var/www.
# The former is used by web applications packaged in Debian,
# the latter may be used for local directories served by the web server. If
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.
Options FollowSymLinks
AllowOverride None
Require all denied
AllowOverride None
Require all granted
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
#
# Options Indexes FollowSymLinks
# AllowOverride None
# Require all granted
#
# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives. See also the AllowOverride
# directive.
#
AccessFileName .htaccess
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
Require all denied
#
# The following directives define some format nicknames for use with
# a CustomLog directive.
#
# These deviate from the Common Log Format definitions in that they use %O
# (the actual bytes sent including headers) instead of %b (the size of the
# requested file), because the latter makes it impossible to detect partial
# requests.
#
# Note that the use of %{X-Forwarded-For}i instead of %h is not recommended.
# Use mod_remoteip instead.
#
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
# Include of directories ignores editors' and dpkg's backup files,
# see README.Debian for details.
# Include generic snippets of statements
IncludeOptional conf-enabled/*.conf
# Include the virtual host configurations:
IncludeOptional sites-enabled/*.conf
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
######### Adding capaility to run CGI-scripts #################
ServerName localhost
ScriptAlias /cgi-bin/ /var/www/cgi-bin/
Options +ExecCGI
AddHandler cgi-script .cgi .pl .py
While I also have the add.html and add.cgi both in the following directory
User@User-VirtualBox:/usr/lib/cgi-bin$ sudo vim add.cgi
User@User-VirtualBox:/usr/lib/cgi-bin$ sudo vim add.html
I've attempted to make them executable by doing the following commands
User@User-VirtualBox:/usr/lib/cgi-bin$ sudo chmod a+x add.cgi
User@User-VirtualBox:/usr/lib/cgi-bin$ sudo chmod a+x add.html
Now, when I try to run the add.html from the following url
http://localhost/cgi-bin/add.html
I get a "Forbidden" permission, not allowed.

User@User-VirtualBox:/$ cd /var/www/html
User@User-VirtualBox: /var/www/html$ sudo vim add.cgi
User@User-VirtualBox: /var/www/html$ sudo vim add.html
User@User-VirtualBox:/var/www/html$ sudo chmod a+x add.cgi
User@User-VirtualBox:/var/www/html$ sudo chmod a+x add.html
User@User-VirtualBox:/var/www/html$ systemctl reload apache2
The add.html file loads


User@User-VirtualBox:/var/www/html$ sudo tail -n 2 /var/log/apache2/error.log
[Mon Jul 26 21:14:05.882030 2021] [core:notice] [pid 770:tid 139880185056320] AH00094: Command line: '/usr/sbin/apache2'
[Mon Jul 26 21:40:13.567334 2021] [authz_core:error] [pid 772:tid 139880105506560] [client 127.0.0.1:42216] AH01630: client denied by server configuration: /usr/www
**UPDATE 2**
The following code shows the MPM and CGI modules used
User@User-VirtualBox:~$ ls /etc/apache2/mods-enabled/mpm* /etc/apache2/mods-enabled/cgi*
/etc/apache2/mods-enabled/cgid.conf /etc/apache2/mods-enabled/mpm_event.conf
/etc/apache2/mods-enabled/cgid.load /etc/apache2/mods-enabled/mpm_event.load
doomspacemarine
(29 rep)
Jul 27, 2021, 05:23 AM
• Last activity: Jul 27, 2021, 11:16 AM
0
votes
1
answers
393
views
CGI (Commong Gateway Interface) program example wont run from HTML page
I'm trying to run this example CGI program that is from this Wikipedia page https://en.wikipedia.org/wiki/Common_Gateway_Interface The HTML code is as follows, the file is named "add.html" ``` Enter two numbers to add First Number: Second Number: Add ``` while the CGI code is as follows, the file is...
I'm trying to run this example CGI program that is from this Wikipedia page https://en.wikipedia.org/wiki/Common_Gateway_Interface
The HTML code is as follows, the file is named "add.html"
Then when I try to use the add.html program from the desktop I get the following HTML page
but when I click add I only get the source code to the CGI script located at the desktop
Does anybody have any advice on how to make the script work? I would very much appreciate any input, Thank you.
**Update:** I've moved the files into the following directory, gave permission to run and reloaded apache using the following commands
However I still encounter the same problem when pressing the add button
The following are the last two error codes that apache gave out
Enter two numbers to add
First Number:
Second Number:
Add
while the CGI code is as follows, the file is called "add.cgi"
#!/usr/bin/env python3
import cgi, cgitb
cgitb.enable()
input_data = cgi.FieldStorage()
print('Content-Type: text/html') # HTML is following
print('') # Leave a blank line
print('Addition Results
')
try:
num1 = int(input_data["num1"].value)
num2 = int(input_data["num2"].value)
except:
print('Sorry, the script cannot turn your inputs into numbers (integers).')
raise SystemExit(1)
print('{0} + {1} = {2}'.format(num1, num2, num1 + num2))
My apache config files are located at
User@User-VirtualBox:/etc/apache2/sites-available$ sudo vim 000-default.conf
and the code there is as follows
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
#ServerName www.example.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
Options ExecCGI Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
AddHandler cgi-script .cgi
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
And the Apache config files are located here
User@User-VirtualBox:/etc/apache2$ sudo vim apache2.conf
The code in the apache2.conf is as follows
# This is the main Apache server configuration file. It contains the
# configuration directives that give the server its instructions.
# See http://httpd.apache.org/docs/2.4/ for detailed information about
# the directives and /usr/share/doc/apache2/README.Debian about Debian specific
# hints.
#
#
# Summary of how the Apache 2 configuration works in Debian:
# The Apache 2 web server configuration in Debian is quite different to
# upstream's suggested way to configure the web server. This is because Debian's
# default Apache2 installation attempts to make adding and removing modules,
# virtual hosts, and extra configuration directives as flexible as possible, in
# order to make automating the changes and administering the server as easy as
# possible.
# It is split into several files forming the configuration hierarchy outlined
# below, all located in the /etc/apache2/ directory:
#
# /etc/apache2/
# |-- apache2.conf
# | `-- ports.conf
# |-- mods-enabled
# | |-- *.load
# | `-- *.conf
# |-- conf-enabled
# | `-- *.conf
# `-- sites-enabled
# `-- *.conf
#
#
# * apache2.conf is the main configuration file (this file). It puts the pieces
# together by including all remaining configuration files when starting up the
# web server.
#
# * ports.conf is always included from the main configuration file. It is
# supposed to determine listening ports for incoming connections which can be
# customized anytime.
#
# * Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/
# directories contain particular configuration snippets which manage modules,
# global configuration fragments, or virtual host configurations,
# respectively.
#
# They are activated by symlinking available configuration files from their
# respective *-available/ counterparts. These should be managed by using our
# helpers a2enmod/a2dismod, a2ensite/a2dissite and a2enconf/a2disconf. See
# their respective man pages for detailed information.
#
# * The binary is called apache2. Due to the use of environment variables, in
# the default configuration, apache2 needs to be started/stopped with
# /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not
# work with the default configuration.
# Global configuration
#
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE! If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the Mutex documentation (available
# at );
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
#ServerRoot "/etc/apache2"
#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
#Mutex file:${APACHE_LOCK_DIR} default
#
# The directory where shm and other runtime files will be stored.
#
DefaultRuntimeDir ${APACHE_RUN_DIR}
#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}
#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300
#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On
#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100
#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5
# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a
# container, error messages relating to that virtual host will be
# logged here. If you *do* define an error logfile for a
# container, that host's errors will be logged there and not here.
#
ErrorLog ${APACHE_LOG_DIR}/error.log
#
# LogLevel: Control the severity of messages logged to the error_log.
# Available values: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the log level for particular modules, e.g.
# "LogLevel info ssl:warn"
#
LogLevel warn
# Include module configuration:
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf
# Include list of ports to listen on
Include ports.conf
# Sets the default security model of the Apache2 HTTPD server. It does
# not allow access to the root filesystem outside of /usr/share and /var/www.
# The former is used by web applications packaged in Debian,
# the latter may be used for local directories served by the web server. If
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.
Options FollowSymLinks
AllowOverride None
Require all denied
AllowOverride None
Require all granted
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
#
# Options Indexes FollowSymLinks
# AllowOverride None
# Require all granted
#
# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives. See also the AllowOverride
# directive.
#
AccessFileName .htaccess
#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
Require all denied
#
# The following directives define some format nicknames for use with
# a CustomLog directive.
#
# These deviate from the Common Log Format definitions in that they use %O
# (the actual bytes sent including headers) instead of %b (the size of the
# requested file), because the latter makes it impossible to detect partial
# requests.
#
# Note that the use of %{X-Forwarded-For}i instead of %h is not recommended.
# Use mod_remoteip instead.
#
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
# Include of directories ignores editors' and dpkg's backup files,
# see README.Debian for details.
# Include generic snippets of statements
IncludeOptional conf-enabled/*.conf
# Include the virtual host configurations:
IncludeOptional sites-enabled/*.conf
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
######### Adding capaility to run CGI-scripts #################
ServerName localhost
ScriptAlias /cgi-bin/ /var/www/cgi-bin/
Options +ExecCGI
AddHandler cgi-script .cgi .pl .py
While I also have the add.html and add.cgi both in the following directory
User@User-VirtualBox:/usr/lib/cgi-bin$ sudo vim add.cgi
User@User-VirtualBox:/usr/lib/cgi-bin$ sudo vim add.html
I've attempted to make them executable by doing the following commands
User@User-VirtualBox:/usr/lib/cgi-bin$ sudo chmod a+x add.cgi
User@User-VirtualBox:/usr/lib/cgi-bin$ sudo chmod a+x add.html
I also have these files on the desktop
User@User-VirtualBox:/home/User/Desktop$ sudo vim add.cgi
User@User-VirtualBox:/home/User/Desktop$ sudo vim add.html
Now, when I try to run the add.html from the following url
http://localhost/cgi-bin/add.html
I get a "Forbidden" permission, not allowed.



User@User-VirtualBox:/$ cd /var/www/html
User@User-VirtualBox: /var/www/html$ sudo vim add.cgi
User@User-VirtualBox: /var/www/html$ sudo vim add.html
User@User-VirtualBox:/var/www/html$ sudo chmod a+x add.cgi
User@User-VirtualBox:/var/www/html$ sudo chmod a+x add.html
User@User-VirtualBox:/var/www/html$ systemctl reload apache2
The add.html file loads


User@User-VirtualBox:/var/www/html$ sudo tail -n 2 /var/log/apache2/error.log
[Sat Jul 24 23:09:12.993845 2021] [mpm_event:notice] [pid 782:tid 139660732775488] AH00489: Apache/2.4.41 (Ubuntu) configured -- resuming normal operations
[Sat Jul 24 23:09:12.993855 2021] [core:notice] [pid 782:tid 139660732775488] AH00094: Command line: '/usr/sbin/apache2'
doomspacemarine
(29 rep)
Jul 25, 2021, 05:20 AM
• Last activity: Jul 26, 2021, 07:30 PM
3
votes
1
answers
22430
views
500:Internal Server Error from CGI program
I am trying to write a CGI Program which is invoked from a HTML page . The CGI code snippet is as follows: #!/bin/bash echo "Content-type: text/html" echo " " echo " " echo "Hi" echo " " echo " " But after executing the script I can see the `500:Internal Server Error` in browser page. . Following ca...
I am trying to write a CGI Program which is invoked from a HTML page . The CGI code snippet is as follows:
#!/bin/bash
echo "Content-type: text/html"
echo ""
echo ""
echo "Hi"
echo ""
echo ""
But after executing the script I can see the
500:Internal Server Error
in browser page. .
Following can be seen in error log file
[Wed Apr 09 18:36:59 2014] [error] [client 127.0.0.1] malformed header
from script. Bad header=: image.sh
[Wed Apr 09 18:37:14 2014] [error] [client 127.0.0.1] malformed header
from script. Bad header=: image.sh
Zama Ques
(3376 rep)
Apr 9, 2014, 07:51 AM
• Last activity: Jun 29, 2021, 02:49 PM
2
votes
2
answers
5030
views
Configuring Apache 2.4 for CGI on FreeBSD
I am trying to run CGI on FreeBSD 9.2. 1. I installed Apache 2.4 (`pkg install apache24`) 2. Configured it to load CGI module. 3. Also, I did `chmod a+x` on files in `cgi-bin` directory. And when I connect to the server to a test CGI script, the server printed this error message. AH01215: (13)Permis...
I am trying to run CGI on FreeBSD 9.2.
1. I installed Apache 2.4 (
pkg install apache24
)
2. Configured it to load CGI module.
3. Also, I did chmod a+x
on files in cgi-bin
directory.
And when I connect to the server to a test CGI script, the server printed this error message.
AH01215: (13)Permission denied: exec of '/usr/local/www/apache24/cgi-bin/test-cgi' failed
End of script output before headers: test-cgi
What's wrong and how to fix this problem?
Eonil
(4777 rep)
Jan 18, 2014, 09:17 AM
• Last activity: Aug 30, 2020, 03:02 AM
2
votes
2
answers
1133
views
Apache2 won't run cgi files based on shebang
I'm trying to use Python as the server-scripting language instead of PHP. I've configured localhost and php files run fine under it. If I create a file .../localhost/temp/test.cgi (making it executable): #!/home/mike/python_venvs/test_venv369/bin/python print( """Content-type:text/html\n\n TEST My s...
I'm trying to use Python as the server-scripting language instead of PHP.
I've configured localhost and php files run fine under it.
If I create a file .../localhost/temp/test.cgi (making it executable):
#!/home/mike/python_venvs/test_venv369/bin/python
print( """Content-type:text/html\n\n
TEST
My server-side template
""" )
print( "")
... it doesn't run as a Python script: the text of the file just gets displayed in the browser.
I've done quite a bit of searching on this. I have no such file, for example, as httpd.conf. My Apache2 setup is like this: executable in /usr/sbin/apache2, with most configuration files apparently under /etc/apache2, and in particular, seemingly, /sites-available, where one finds two files, 000-default.conf and default-ssl.conf.
I may be mistaken, but I believe httpd.conf is the "old" Apache way of doing things.
I found a totally baffling but (just) possibly promising line at the bottom of 000-default.conf:
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
... so I uncommented that and restarted the apache2 service. No difference.
**Details of 000-default.conf**
(in /etc/apache2/sites-available). NB when I was struggling to change the localhost directory changes in this file seemed to do that. # The ServerName directive sets the request scheme, hostname and port that... ServerAdmin webmaster@localhost DocumentRoot "/media/mike/W10 D drive/My Documents/localhost" Options FollowSymLinks AllowOverride All Options Indexes FollowSymLinks MultiViews AllowOverride None Require all granted ... I don't know where CGI scripts are meant to go or where they are configured (although I am about to examine the first answer below), but given that I want them to be used with the .html files under .../localhost/ as above, I want that location to be "CGI-enabled". **Later**
It turns out that a short answer to this question (specifically) was, in my case, simply to add "ExecCGI" as one of the "Options" in the `` tag or block or whatever it's called.
(in /etc/apache2/sites-available). NB when I was struggling to change the localhost directory changes in this file seemed to do that. # The ServerName directive sets the request scheme, hostname and port that... ServerAdmin webmaster@localhost DocumentRoot "/media/mike/W10 D drive/My Documents/localhost" Options FollowSymLinks AllowOverride All Options Indexes FollowSymLinks MultiViews AllowOverride None Require all granted ... I don't know where CGI scripts are meant to go or where they are configured (although I am about to examine the first answer below), but given that I want them to be used with the .html files under .../localhost/ as above, I want that location to be "CGI-enabled". **Later**
It turns out that a short answer to this question (specifically) was, in my case, simply to add "ExecCGI" as one of the "Options" in the `` tag or block or whatever it's called.
mike rodent
(1172 rep)
May 11, 2020, 01:20 PM
• Last activity: May 16, 2020, 11:01 AM
2
votes
1
answers
1110
views
How to give variable to a KSH script with a CGI?
index.sh is in the cgi-bin directory: #!/usr/bin/ksh echo 'Content-type: text/html ' FOO.KSH #!/usr/bin/ksh printf "Content-type: text/html\n\n"; echo $1 echo $QUERY_STRING echo $(</dev/stdin) **Q**: Why does the FOO.KSH gives an empty file if I send an "a" string in the index.sh's form?
index.sh is in the cgi-bin directory:
#!/usr/bin/ksh
echo 'Content-type: text/html
' FOO.KSH #!/usr/bin/ksh printf "Content-type: text/html\n\n"; echo $1 echo $QUERY_STRING echo $(
' FOO.KSH #!/usr/bin/ksh printf "Content-type: text/html\n\n"; echo $1 echo $QUERY_STRING echo $(
gasko peter
(5634 rep)
Aug 13, 2013, 07:45 AM
• Last activity: Apr 5, 2020, 11:01 AM
0
votes
1
answers
372
views
Why might a perl CGI script fail to connect to MySQL, when it works from console?
I'm migrating to new server hardware, which also means learning the idiosyncrasies of a new Linux distribution (Debian buster). I've got a Perl CGI script which when run from the console runs, but fails to connect to MySQL with: > AH01215: DBI connect('my_db','my_db_user',...) failed: Can't connect...
I'm migrating to new server hardware, which also means learning the idiosyncrasies of a new Linux distribution (Debian buster).
I've got a Perl CGI script which when run from the console runs, but fails to connect to MySQL with:
> AH01215: DBI connect('my_db','my_db_user',...) failed: Can't connect to local MySQL server through socket '/tmp/mysql.sock'
Given it's running on the same hardware, so it'll be the same Perl install, etc. I'm at a loss as to why it's not working? I know back on Centos, SELinux could get in the way, but I don't believe Debian has this by default, but is there something similar that I'd need to do to allow child processes to make connections?
mysqladmin suggests that's the right place (i.e I'm not hitting [this issue](https://www.perlmonks.org/bare/?node_id=72626)) :
# mysqladmin version -p Enter password: mysqladmin Ver 8.0.17 for Linux on i686 (Source distribution) Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Server version 8.0.17 Protocol version 10 Connection Localhost via UNIX socket UNIX socket /tmp/mysql.sock Uptime: 3 days 26 min 34 sec Threads: 2 Questions: 74254 Slow queries: 0 Opens: 1042 Flush tables: 3 Open tables: 962 Queries per second avg: 0.284And the socket clearly exists (as executing from console works)
$ ls -lF /tmp/mysql.sock srwxrwxrwx 1 mysql mysql 0 Sep 6 22:33 /tmp/mysql.sock=
Rowland Shaw
(382 rep)
Sep 8, 2019, 02:49 PM
• Last activity: Apr 4, 2020, 04:52 PM
0
votes
1
answers
1479
views
Curl command in bash CGI script not displaying the XML output [data not shown]
if I run this command in linux shell. curl=`curl --connect-timeout 4 -k -X POST -H "Content-type: text/xml" --data " " http://192.168.1.100:8484/rest/service?action=heartbeat 2>&1 | tee` echo "$curl" I get following response But when the same command is executed in a bash CGI script and output is di...
if I run this command in linux shell.
curl=
curl --connect-timeout 4 -k -X POST -H "Content-type: text/xml" --data "" http://192.168.1.100:8484/rest/service?action=heartbeat 2>&1 | tee
echo "$curl"
I get following response
But when the same command is executed in a bash CGI script and output is displayed in html pre tags, I see some weird table and no XML data is displayed at all.
in CGI bash script i have this code
curl=curl --connect-timeout 4 -k -X POST -H "Content-type: text/xml" --data "" http://192.168.1.100:8484/rest/service?action=heartbeat 2>&1 | tee
echo "RAW Troubleshooting Data
" echo "$curl" echo "" exit 0 instead of XML data, following table is displayed in the web browser. % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 76 0 424 --:--:-- --:--:-- --:--:-- 424 202 126 0 126 0 76 302 182 --:--:-- --:--:-- --:--:-- 210 However, if I use the curl verbosity with -v command in cgi bash script I get following out in my web browser but still the XML response is missing. * About to connect() to xx.xx.xx.xx port xxxxx (#0) * Trying xx.xx.xx.xx... connected * Connected to xx.xx.xx.xx (xx.xx.xx.xx) port xxxxx (#0) > POST /rest/service?action=heartbeat HTTP/1.1 > User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.15.3 zlib/1.2.3 libidn/1.18 libssh2/1.4.2 > Host: xx.xx.xx.xx:xxxx > Accept: */* > Content-type: text/xml > Content-Length: 76 > } [data not shown] % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 76 0 422 --:--:-- --:--:-- --:--:-- 422< HTTP/1.1 200 OK < Server: nginx < Date: Thu, 14 Nov 2019 18:53:44 GMT < Content-Type: application/xml < Transfer-Encoding: chunked < Connection: keep-alive < Vary: Accept-Encoding < X-Powered-By: PHP/7.0.32 < { [data not shown] 202 126 0 126 0 76 284 171 --:--:-- --:--:-- --:--:-- 190 202 126 0 126 0 76 284 171 --:--:-- --:--:-- --:--:-- 190* Connection #0 to host xx.xxx.xxx.xx left intact * Closing connection #0 Your help is appreciated.
user2107349
(147 rep)
Nov 14, 2019, 06:59 PM
• Last activity: Nov 14, 2019, 07:26 PM
0
votes
1
answers
219
views
Perl.cgi soap request HTTP ERROR 411
I'm trying to learn SoapUI, but when running the code below I'm getting **HTTP ERROR 411** all files are in /var/www/html/ not sure what's the issue. #!/usr/bin/perl use SOAP::Transport::HTTP; SOAP::Transport::HTTP::CGI -> dispatch_to('Demo') -> handle; package Demo; sub hi { return "hello, world";...
I'm trying to learn SoapUI, but when running the code below I'm getting **HTTP ERROR 411**
all files are in /var/www/html/ not sure what's the issue.
#!/usr/bin/perl
use SOAP::Transport::HTTP;
SOAP::Transport::HTTP::CGI
-> dispatch_to('Demo')
-> handle;
package Demo;
sub hi
{
return "hello, world";
}
sub bye
{
return "goodbye, cruel world";
}
**Directives**
Order allow,deny
Allow from all
Options +ExecCGI
AddHandler cgi-script .cgi .pl
AllowOverride None
Options Indexes FollowSymLinks
- CentOS 6.8
- Appache: Apache/2.2.15
- Perl: v5.10.1
- Client: HTTP Browser
Driven
(11 rep)
Aug 1, 2019, 08:45 PM
• Last activity: Aug 2, 2019, 06:31 AM
1
votes
1
answers
1594
views
Shell script equivalent to PHP $_POST
For example and learning purposes, I have a webpage that uses `POST` method to submit a text field. I have a server running script (bash) that I want to display what the "Query_string" is. I'm not completely familiar with PHP either, but I think `$_POST` would be used to print the submitted text. Th...
For example and learning purposes, I have a webpage that uses
POST
method to submit a text field. I have a server running script (bash) that I want to display what the "Query_string" is. I'm not completely familiar with PHP either, but I think $_POST
would be used to print the submitted text. The script I am using is bash. What could I use to print out the submitted text?
swam
(113 rep)
Nov 6, 2014, 04:43 AM
• Last activity: Jul 15, 2019, 01:06 AM
0
votes
1
answers
1656
views
Print the output of an interactive command in a shell script
I am writing a CGI script to monitor the system state, so the information must be outputted to the terminal with `echo` or `cat`. The problem is, `systat` is an interactive command, so it doesn't print anything to the screen. I tried `systat | echo` and `systat | cat`, but the former gives nothing,...
I am writing a CGI script to monitor the system state, so the information must be outputted to the terminal with
echo
or cat
. The problem is, systat
is an interactive command, so it doesn't print anything to the screen.
I tried systat | echo
and systat | cat
, but the former gives nothing, whereas the latter behaves identically as systat
.
**Edit**
OK, let me clarify. Basically, I'm asking for a shell script, say monitor.sh
. When executed with ./monitor.sh
, it would start a new process, output the result of systat
, and then exit.
It should look something like this:
root@HPC:~/playground # ./monitor.sh
/0 /1 /2 /3 /4 /5 /6 /7 /8 /9 /10
Load Average >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 12.0
/0% /10 /20 /30 /40 /50 /60 /70 /80 /90 /100
root calc XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
root calc XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
root calc XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
root calc XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
root calc XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
root calc XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
root calc XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
root calc XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
root calc XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
root calc XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
root calc XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
root calc XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
root@HPC:~/playground #
nalzok
(431 rep)
Mar 14, 2019, 03:15 AM
• Last activity: Mar 21, 2019, 03:12 PM
1
votes
1
answers
539
views
CGI error while trying to retrieve from sqlite3
I am trying to build a very simple login page, which asks the user for his `register_no`, `username` and `password`. And when he presses the submit button. I am trying to check whether it is an existing user or a new user and display a message accordingly. My folder hierarchy is like this prodicus@A...
I am trying to build a very simple login page, which asks the user for his
Username :
Password :
For
register_no
, username
and password
. And when he presses the submit button. I am trying to check whether it is an existing user or a new user and display a message accordingly.
My folder hierarchy is like this
prodicus@Acer:~/Downloads/souvik_refactoring$ tree
.
├── cgi-bin
│ ├── creating_user_base_table.py
│ ├── user_base.db
│ └── usr_check.py
├── index.html
└── keyCheck.py
1 directory, 5 files
**What I have tried:**
For the index.html
Login page
Login page
Registration number :Username :
Password :
creating_user_base_table.py
#!/usr/bin/env python3.4
import sqlite3
import os
db_name = "user_base.db"
if db_name in os.listdir():
print("removing the user_base.db and creating a fresh copy of it")
os.system("rm user_base.db")
print("Creating the database")
conn = sqlite3.connect(db_name)
cur = conn.cursor()
user_table = "CREATE TABLE users(reg_no INTEGER PRIMARY KEY, user_name TEXT, pass TEXT)"
new_users = (
(1081310251, 'admin', 'admin'),
(1081310234, 'foo', 'admin123')
)
cur.execute(user_table)
print("table created")
cur.executemany('INSERT INTO users VALUES(?, ?, ?)', new_users)
conn.commit()
print("default users created \n\ndisplaying them")
cur.execute('SELECT * FROM users')
print(cur.fetchall())
and finally usr_check.py
#/usr/bin/env python3.4
import cgi, cgitb
import os
import sqlite3
cgitb.enable()
form = cgi.FieldStorage()
register_no = form.getvalue('register_no')
username = form.getvalue('username')
passwd = form.getvalue('password')
print("Content-type:text/html\r\n\r\n")
print("")
print("")
print("Shit gets real here
") print("") print("") print('")
print("")
conn = sqlite3.connect('user_base.db')
cur = conn.cursor()
## now to check whether the entered data is for
## -> new user
## -> an old user
cur.execute('SELECT user_name FROM users WHERE register_no = ?', (register_no,))
rows = cur.fetchall()
print("
") if len(rows) == 0: print("
") if len(rows) == 0: print("
User : ", username , " does not exist.
") cur.execute('INSERT INTO users VALUES(?, ?, ?)', (register_no, username, passwd)) print("User was created successfully
") print("Done") else: print("Welcome", username ,". Good to have you back")
print("
Your account details
") print("- ")
print("
- Register number : ", register_no, " ") print("
- Username " , username, " ") print("
cgitb
is not showing an error. Where am I going wrong?
Tasdik Rahman
(139 rep)
Nov 3, 2015, 06:44 AM
• Last activity: Mar 20, 2019, 01:12 PM
1
votes
1
answers
258
views
How to get php-cgi with phpbrew (PHP5.3.x)
I installed php-5.6.40 php-7.1.14 with phpbrew and I've got php-cgi binaries on these both version. I used this command for get php-cgi 5.6.40 phpbrew install 5.6.40 +default+fpm+mysql+sqlite+mb+iconv+json+iconv+exif+fileinfo +curl=/opt/CURL/curl-7.26.0 +openssl=/opt/OpenSSL/openssl-1.0.1u and I get...
I installed php-5.6.40 php-7.1.14 with phpbrew and I've got php-cgi binaries on these both version. I used this command for get php-cgi 5.6.40
phpbrew install 5.6.40 +default+fpm+mysql+sqlite+mb+iconv+json+iconv+exif+fileinfo +curl=/opt/CURL/curl-7.26.0 +openssl=/opt/OpenSSL/openssl-1.0.1u
and I get
~# /opt/phpbrew/php/php-5.6.40/bin/php-cgi -v
PHP 5.6.40 (cgi-fcgi) (built: Jan 14 2019 12:19:43)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies
On the same system, I'm trying to do the same with an old version with this command
phpbrew install --old 5.3.29 +default+fpm+cgi+cli+mysql+sqlite+mb+iconv+json+iconv+exif+fileinfo +curl=/opt/CURL/curl-7.26.0 +openssl=/opt/OpenSSL/openssl-1.0.1u -- --enable-cgi
The compilation has been finished without error but php-cgi is not present in the bin directory of php version 5.3.29
dubis
(1480 rep)
Jan 14, 2019, 04:58 PM
• Last activity: Jan 21, 2019, 04:06 PM
2
votes
1
answers
1186
views
How to Configure CGI in Ubuntu?
I recently installed Apache2 on Ubuntu and I am trying to configure CGI. I added the following lines in apache2.conf file: ScriptAlias /cgi-bin/ /home/router/cgi-bin/ Options ExecCGI AddHandler cgi-script cgi pl And I saved and restart apache2, but when I type the following in browser: http://192.16...
I recently installed Apache2 on Ubuntu and I am trying to configure CGI. I added the following lines in apache2.conf file:
ScriptAlias /cgi-bin/ /home/router/cgi-bin/
Options ExecCGI
AddHandler cgi-script cgi pl
And I saved and restart apache2, but when I type the following in browser:
http://192.168.1.1/cgi-bin/file1.cgi
I get the following error:
You don't have permission to access /cgi-bin/file1.cgi on this server.
user5499177
(23 rep)
Jul 11, 2016, 04:16 AM
• Last activity: Jan 6, 2019, 01:40 PM
1
votes
0
answers
986
views
How to execute a cgi pointed to by a symlink?
My website has several cgi's (executable binaries compiled from **C** source, in case that matters) that work fine when run from a browser as, e.g., http://mydomain.com/cgi-bin/myprog.cgi But if I put a symlink to myprog.cgi in cgi-bin/ like cd cgi-bin/ ln -s myprog.cgi proglink.cgi then trying...
My website has several cgi's (executable binaries compiled from **C** source, in case that matters) that work fine when run from a browser as, e.g.,
http://mydomain.com/cgi-bin/myprog.cgi
But if I put a symlink to myprog.cgi in cgi-bin/ like
cd cgi-bin/
ln -s myprog.cgi proglink.cgi
then trying to run
http://mydomain.com/cgi-bin/proglink.cgi
from a browser generates a 500 error. My .htaccess has
AddHandler cgi-script .cgi
Options +ExecCGI +FollowSymLinks -Indexes
(and I'd also tried +SymLinksIfOwnerMatch, both with and without +FollowSymLinks alongside it), but that doesn't seem to work. **Edit** I should mention (thanks to @slm's suggestion in comments below) that the site already has symlinks to .php scripts, which have been working fine for years. (Those php scripts do a $_SERVER['PHP_SELF'], returning the name of the symlink, and that all works without any problem.) But now the symlink to an executable image .cgi fails as described above.
I probably also should mention that this site is on a shared host (cheap dreamhost.com shared hosting). Googling the problem seems to suggest nothing will work, and that apache simply won't execute a cgi pointed to by a symlink. Is that googling right, or is there some way to run cgi's following a symlink? If it is right, and I can't do that no-way/no-how, let me describe below why I want to do it, and then hopefully you can suggest an alternative strategy that works and that accomplishes the same overall purpose... ...So this is where the _security_ Tag below comes in. Some of those cgi's had been the target of ddos attacks to my site (though God knows, or maybe He doesn't, why anybody would bother with my site, which has absolutely nothing of any value). So I added some code to each cgi (pretty much the same code to each) to validate its ?query_string, and assign it a "likelihood-of-attack" score. With a small score the cgi just ignores the request, and with a larger score the user's ipaddr=getenv("REMOTE_ADDR"), is automatically appended to .htaccess with a "deny from". And also various in-between actions, like emailing me about the situation. So this has become lots of lines of code. And rather than individually compiling it into each cgi, I wanted (and still want) to write a front-end query-validation that does it once-and-for-all. Then, if everything's okay, it issues a system() call to run the requested cgi. So I wrote a short little test program that just indirectly runs a cgi by issuing a system() call, and that indeed works okay. The symlink issue now comes in because, in the general case, that front end has to be able to run many different cgi's, and therefore needs to know which cgi to run. And by symlink'ing each cgi name to that front-end cgi, it could parse out getenv("SCRIPT_NAME"), which would give it the symlink name, thereby identifying the particular cgi issuing the request. Kind of like php $_SERVER['PHP_SELF']. So symlinks seem like the neatest and easiest solution. But if that's not feasible with apache/.htaccess, then can you suggest some other method to accomplish the same purpose?
http://mydomain.com/cgi-bin/myprog.cgi
But if I put a symlink to myprog.cgi in cgi-bin/ like
cd cgi-bin/
ln -s myprog.cgi proglink.cgi
then trying to run
http://mydomain.com/cgi-bin/proglink.cgi
from a browser generates a 500 error. My .htaccess has
AddHandler cgi-script .cgi
Options +ExecCGI +FollowSymLinks -Indexes
(and I'd also tried +SymLinksIfOwnerMatch, both with and without +FollowSymLinks alongside it), but that doesn't seem to work. **Edit** I should mention (thanks to @slm's suggestion in comments below) that the site already has symlinks to .php scripts, which have been working fine for years. (Those php scripts do a $_SERVER['PHP_SELF'], returning the name of the symlink, and that all works without any problem.) But now the symlink to an executable image .cgi fails as described above.
I probably also should mention that this site is on a shared host (cheap dreamhost.com shared hosting). Googling the problem seems to suggest nothing will work, and that apache simply won't execute a cgi pointed to by a symlink. Is that googling right, or is there some way to run cgi's following a symlink? If it is right, and I can't do that no-way/no-how, let me describe below why I want to do it, and then hopefully you can suggest an alternative strategy that works and that accomplishes the same overall purpose... ...So this is where the _security_ Tag below comes in. Some of those cgi's had been the target of ddos attacks to my site (though God knows, or maybe He doesn't, why anybody would bother with my site, which has absolutely nothing of any value). So I added some code to each cgi (pretty much the same code to each) to validate its ?query_string, and assign it a "likelihood-of-attack" score. With a small score the cgi just ignores the request, and with a larger score the user's ipaddr=getenv("REMOTE_ADDR"), is automatically appended to .htaccess with a "deny from". And also various in-between actions, like emailing me about the situation. So this has become lots of lines of code. And rather than individually compiling it into each cgi, I wanted (and still want) to write a front-end query-validation that does it once-and-for-all. Then, if everything's okay, it issues a system() call to run the requested cgi. So I wrote a short little test program that just indirectly runs a cgi by issuing a system() call, and that indeed works okay. The symlink issue now comes in because, in the general case, that front end has to be able to run many different cgi's, and therefore needs to know which cgi to run. And by symlink'ing each cgi name to that front-end cgi, it could parse out getenv("SCRIPT_NAME"), which would give it the symlink name, thereby identifying the particular cgi issuing the request. Kind of like php $_SERVER['PHP_SELF']. So symlinks seem like the neatest and easiest solution. But if that's not feasible with apache/.htaccess, then can you suggest some other method to accomplish the same purpose?
John Forkosh
(242 rep)
Jul 14, 2018, 04:23 PM
• Last activity: Jul 14, 2018, 05:53 PM
Showing page 1 of 20 total questions