I wrote a cherrypy application and now I need SSL. I am working with apache/wsgi and have a working python file running and returning pages. Now I am trying to get POSTs to work.
This is my working script:
import sys
sys.stdout = sys.stderr
import atexit
import threading
import cherrypy
cherrypy.config.update({'environment': 'embedded'})
if cherrypy.engine.state == 0:
cherrypy.engine.start(blocking=False)
atexit.register(cherrypy.engine.stop)
class Root(object):
def index(self):
# restrict access by ip address
clientIP = cherrypy.request.headers["Remote-Addr"]
if clientIP not in self.allowedIPs:
return "Access Denied"
return cherrypy.url()
index.exposed = True
allowedIPs = ["127.0.0.1", "192.168.174.1"]
application = cherrypy.Application(Root(), None)
If i make modifications to catch the post:
class Root(object):
def index(self, files):
I receive the following error:
<h2>404 Not Found</h2>
<p>Nothing matches the given URI</p>
My apache config,
WSGISocketPrefix run/wsgi
NameVirtualHost *:443
<VirtualHost *:443>
DocumentRoot /var/www/ssl_html
ServerName 192.168.174.130:443
ServerAlias 192.168.174.130
SSLEngine On
SSLCertificateFile /etc/ssl/certs/devel.crt
SSLCertificateKeyFile /etc/ssl/certs/devel.key
<Location />
SSLRequireSSL
</Location>
WSGIDaemonProcess 192.168.174.130 processes=2 threads=15 display-name=%{GROUP}
WSGIProcessGroup 192.168.174.130
WSGIScriptAlias / /var/www/wsgi-scripts/helloWorld.py
</VirtualHost>
any help would be greatly appreciated! :)
def index(self, files):
should be
def index(self, file):
ughh!! alas, fixed!
Related
I have an api service that i wrote with FastApi and served with gunicorn. Apache is working on the server as reverse proxy and ssl manage.
Everything was fine until i decided to use SqlAdmin as admin panel.
The problem is that my api endpoints works fine with SSL but SqlAdmin endpoints are not.
e.g: Responses i get when i want reach https://example.com/admin: (FAIL)
--- I summarized responses ---
307 Temporary Redirect -> http://example.com/admin
302 Not Found
Somehow redirect -> https://example.comadmin/
e.g: Responses i get when i want reach https://example.com/users: (PASS) (API ENDPOINT)
Request URL: https://example.com/users/
Request Method: GET
Status Code: 200 OK
Apache Configuration:
<VirtualHost ip:80>
ServerName subdomain.example.com
ServerAlias www.subdomain.example.com
ServerAdmin ****#gmail.com
Redirect / https://subdomain.example.com
</VirtualHost>
<VirtualHost ip:443>
ServerName subdomain.example.com
ServerAlias www.subdomain.example.com
ServerAdmin ******#gmail.com
ProxyRequests On
ProxyPreserveHost On
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
SSLEngine on
SSLCertificateFile *****
ProxyPass / http://example.com:8000/
ProxyPassReverse / http://example.com:8000/
<Location />
Order allow,deny
Allow from all
</Location>
</VirtualHost>
Gunicorn Configuration:
import json
import multiprocessing
import os
workers_per_core_str = os.getenv("WORKERS_PER_CORE", "1")
max_workers_str = os.getenv("MAX_WORKERS")
use_max_workers = None
if max_workers_str:
use_max_workers = int(max_workers_str)
web_concurrency_str = os.getenv("WEB_CONCURRENCY", None)
host = os.getenv("HOST", "0.0.0.0")
port = os.getenv("PORT", "80")
bind_env = os.getenv("BIND", None)
use_loglevel = os.getenv("LOG_LEVEL", "warning")
if bind_env:
use_bind = bind_env
else:
use_bind = f"{host}:{port}"
cores = multiprocessing.cpu_count()
workers_per_core = float(workers_per_core_str)
default_web_concurrency = workers_per_core * cores
if web_concurrency_str:
web_concurrency = int(web_concurrency_str)
assert web_concurrency > 0
else:
web_concurrency = max(int(default_web_concurrency), 2)
if use_max_workers:
web_concurrency = min(web_concurrency, use_max_workers)
accesslog_var = os.getenv("ACCESS_LOG", "/var/log/gunicorn/access_log")
use_accesslog = accesslog_var or "/var/log/gunicorn/access_log"
errorlog_var = os.getenv("ERROR_LOG", "/var/log/gunicorn/error_log")
use_errorlog = errorlog_var or "/var/log/gunicorn/error_log"
graceful_timeout_str = os.getenv("GRACEFUL_TIMEOUT", "120")
timeout_str = os.getenv("TIMEOUT", "120")
keepalive_str = os.getenv("KEEP_ALIVE", "5")
# Gunicorn config variables
loglevel = use_loglevel
workers = web_concurrency
bind = use_bind
errorlog = use_errorlog
worker_tmp_dir = "/dev/shm"
accesslog = use_accesslog
graceful_timeout = int(graceful_timeout_str)
timeout = int(timeout_str)
keepalive = int(keepalive_str)
# For debugging and testing
log_data = {
"loglevel": loglevel,
"workers": workers,
"bind": bind,
"graceful_timeout": graceful_timeout,
"timeout": timeout,
"keepalive": keepalive,
"errorlog": errorlog,
"accesslog": accesslog,
# Additional, non-gunicorn variables
"workers_per_core": workers_per_core,
"use_max_workers": use_max_workers,
"host": host,
"port": port,
}
print(json.dumps(log_data))
I dont have any idea how this behavior happend at all so any clue would be helpful :)
Thanks in advance.
I did try to add middleware to the FastApi. HTTPSRedirectMiddleware.
every requests reached to this response on gunicorn:
WARNING: Invalid HTTP request received.
I did try to start gunicorn with --forwarded-allow-ips='*' and --proxy-headers.
Nothing changed.
I use ASP .NET CORE 2.
I use this code in Startup.cs
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = new PathString("/Account/Login");
options.AccessDeniedPath = new PathString(/Account/AccessDenied);
options.ExpireTimeSpan = TimeSpan.FromMinutes(3 * 60 + 1);
});
I am not login so my website redirects to
https://localhost/Account/Login?ReturnUrl=%252Fbbb.
It works in development. I get the URL
https://aaaaa.com/?ReturnUrl=%252Fbbb in production.
How to fix it? I searched Google but was unable to find anything.
My Apache proxy file 000-default.conf
<VirtualHost *:80>
ServerName aaaaa.com
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/ [R,L]
</VirtualHost>
<VirtualHost *:443>
ProxyPreserveHost On
ProxyPass "/" "http://localhost:5000/"
ProxyPassReverse "/" "http://localhost:5000/"
ErrorLog /var/log/httpd/aaaaa-error.log
CustomLog /var/log/httpd/aaaaa-access.log common
SSLEngine on
SSLProtocol all -SSLv2
SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:!RC4+RSA:+HIGH:+MEDIUM:!LOW:!RC4
SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt
SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key
</VirtualHost>
The code in Startup.cs
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = new PathString("/Account/Login");
options.AccessDeniedPath = new PathString(/Account/AccessDenied);
options.Events.OnRedirectToLogin = context =>
{
LogManager.GetLogger(this.GetType()).Info("OnRedirectToLogin->RedirectUri: " + context.RedirectUri);
#if DEBUG
context.Response.Redirect(context.RedirectUri);
#else
string strURL = context.RedirectUri.ToLower();
if (strURL.StartsWith("http://"))
{
strURL = strURL.Replace("http://", "https://", StringComparison.CurrentCultureIgnoreCase);
}
context.Response.Redirect(strURL);
#endif
return Task.CompletedTask;
};
});
Logging shows HTTP protocol http://aaaaa.com/Account/Logon?ReturnUrl=%252Fbbb and then Apache
redirect to HTTPS while cutting Account/Logon from URL.
Solution is simple replace HTTP with HTTPS so Apache won't redirects.
Edward and MarkG, I appreciate your hints!
I have configure apache2 into my ubuntu 14.04 with odoo.DB has over 100000 records i for partners. So we are loading them into background. Same way products are also loading. Products are loading fine, but partner are not loading. Can any one help me with this.
apache proxy configuration.
`
ServerName odoo-bhaviraj.com
ServerAlias odoo-bhaviraj.com
LogLevel warn
ErrorLog /var/log/apache2/odoo-bhaviraj.com.error.log
CustomLog /var/log/apache2/odoo-bhaviraj.com.access.log combined
ProxyRequests Off
ProxyPreserveHost On
ProxyVia full
ProxyTimeout 18000
KeepAlive On
ProxyPass / http://localhost:8069/
ProxyPassReverse / http://localhost:8069/
ProxyPass / http://127.0.0.1:8069/
ProxyPassReverse / http://127.0.0.1:8069/
</VirtualHost>
odoo.conf file
[options]
; This is the password that allows database operations:
admin_passwd = admin
db_host = localhost
db_port = 5432
db_user = acespritech
db_password = 123456
addons_path = /home/bhaviraj/project/erp/odoo/odoo_8/addons
## Logging Group - Logging Configuration
logfile = /var/log/odoo/odoo-server.log
logrotate = True
syslog = False
log_level = debug
log_handler = [':INFO']
log_level = info
db_filter = .*
workers = 4
proxy_mode = True
limit_memory_soft = 671088640
limit_memory_hard = 805306368
limit_time_cpu = 3000
limit_time_real = 3000
limit_request = 8192
max_cron_threads = 0
xmlrpc_interface = 127.0.0.1
longpolling_port = 8072`
It's very simple, execute this commande :
sudo gedit /etc/apache2/apache2.conf
And, verify the Timeout (The number of seconds before receives and sends time).
Timeout 300
I am trying to export an SVG graph as an attachment to download. I am using http://d3export.housegordon.org/ to achieve the same. The perl file returns a status message of 200OK. Neither the apache log nor the perl log is showing any errors. Also, I am able to print the output SVG string of the perl file in my console which I assume is indicative of the request to perl file being successful. However, instead of getting an SVG attachment file to download as response, an extra tab gets opened displaying an APACHE ERROR which reads..."Not Found
The requested URL /[object XMLDocument] was not found on this server.". I have made a few modifications in my perl script wrt the perl script provided on the link mentioned above. My modified perl script is as below:
use strict;
use warnings;
use CGI qw/:standard/;
use CGI::Carp qw/fatalsToBrowser/;
use autodie qw(:all);
use File::Temp qw/tempfile/;
use File::Slurp qw/read_file write_file/;
$CGI::POST_MAX = 1024 * 5000;
my $output_format = param("output_format")
or die "Missing 'output_format' parameter";
die "Invalid output_format value"
unless $output_format eq "svg" ||
$output_format eq "pdf" ||
$output_format eq "png";
my $data = param("data")
or die "Missing 'data' parameter";
die "Invalid data value"
unless $data =~ /^[\x20-\x7E\t\n\r ]+$/;
my $timestamp = time;
my $random = int(rand(99999));
my $dnldfile = "/dnld/d3Momentum" . $timestamp . "_" . $random . ".svg";
my $filename = "/var/www/html/Project/Project_frontend/public".$dnldfile;
my $q = CGI->new;
if ($output_format eq "svg") {
print $q->header(-type=>"image/svg+xml", -attachment=>$filename,);
print $data;
exit(0);
}
elsif ($output_format eq "pdf" || $output_format eq "png") {
my (undef, $input_file) = tempfile("d3export.svg.XXXXXXX", OPEN=>0, TMPDIR=>1, UNLINK=>1);
my (undef, $output_file) = tempfile("d3export.out.XXXXXXX", OPEN=>0, TMPDIR=>1, UNLINK=>1);
write_file( $input_file, $data );
my $zoom = ($output_format eq "png")?10:1;
system("rsvg-convert -o '$output_file' -z '$zoom' -f '$output_format' '$input_file'");
my $pdf_data = read_file( $output_file, {binmode=>':raw'});
my $mime_type = ($output_format eq "pdf")?"application/x-pdf":"image/png";
print header(-type=>$mime_type,
-attachment=>"d3js_export_demo.$output_format");
print $pdf_data;
exit(0);
}
Request Parameters being passed are..
'ouput_format' : 'svg';
'data' : (Entire SVG Element parsed using XMLSerializer.serializeToString() as mentioned on http://d3export.housegordon.org/).
Below is my Virtual Host Configuration:
<VirtualHost *:80>
ServerName project-v4.co
ServerAlias project-v4.co
Alias /awstatsclasses "/usr/share/awstats/lib/"
Alias /awstats-icon "/usr/share/awstats/icon/"
Alias /awstatscss "/usr/share/doc/awstats/examples/css"
ScriptAlias /awstats/ /usr/lib/cgi-bin/
DocumentRoot /var/www/html/Project-v4/Project-v4_frontend/public
SetEnv APPLICATION_ENV "production"
<Directory /var/www/html/Project-v4/Project-v4_frontend/public>
DirectoryIndex index.html
AllowOverride All
Order allow,deny
Allow from all
AddHandler cgi-script .bin
Header set Access-Control-Allow-Origin "*"
</Directory>
ScriptAlias /cgi-bin/ /var/www/html/Project-v4/Project-v4_frontend/public/cgi-bin/
<Directory "/var/www/html/Project-v4/Project-v4_frontend/public/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#ErrorLog ${APACHE_LOG_DIR}/live-error.log
ErrorLog /var/www/live-error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access.log combined
#<Location /perl/>
# SetHandler perl-script
# PerlHandler ModPerl::PerlRun
# Options ExecCGI
#</Location>
Below is the Ajax Call to the perl script.
var oData = {"output_format" : "svg", "data" : svg_xml};
$.ajax({
url: '/cgi-bin/d3export.pl',
method: "POST",
data: oData,
success: function(oResult) {
console.log(oResult);
window.open(oResult);
}
})
The Perl script is located in the cgi-bin directory, which is located in the public folder of my Project (Project-v4_frontend/public/cgi-bin/d3export.pl). I am using the MEAN stack for my project.
Any help to resolve the apache NOT FOUND error would be appreciated sincerely.
Thank You.
i am running wamp on windows 7
i am trying to upload some images via a form into my MVC applIcation. i am working from my laptop, so the Wamp is installed on my laptop
my problem is that i keep getting this message:
Warning: move_uploaded_file(C:\Users\test\zend\\module\guest\src\guest/pics/holdover/pic.jpg): failed to open stream: Permission denied in
my problem is that i have not restricted any previged so i dont knwo why it would be restricted.
not-with-standing this, where do i go on my WAMP to enable access to the folder ?
thank you in advanced for your advise
my Code:
the aim of the file_upload is to transfer the file (currently held in a temp folder) to another folder. its also given a new name.
everything else work. the problem is with the permission of the receiving folder; permission is being denied
if ($form->isValid())
{
$size = new Size(array('min'=>2000)); //minimum bytes filesize
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setValidators(array($size), $data['fileupload']['name']);
if (!$adapter->isValid())
{
$dataError = $adapter->getMessages();
$error = array();
foreach($dataError as $key=>$row)
{
$error[] = $row;
}
$form->setMessages(array('fileupload'=>$error ));
}
else
{
$fileName = $data['fileupload']['name'];
$fileTmpLoc = $data['fileupload']['tmp_name'];
$fileType = $data['fileupload']['type'];
$fileSize = $data['fileupload']['size'];
$fileErrorMsg = $data['fileupload']['error'];
$kaboom = explode(".", $fileName);
$this->fileExt = end($kaboom);
$this->fileName = "user_{$this->getAbbriviation($data)}{$this->getUserId()}.$this->fileExt";
$moveResult = move_uploaded_file($fileTmpLoc, dirname(__DIR__)."/pics/member/holdover/$this->fileName");
if ($moveResult != true)
{
echo "ERROR: File not uploaded. Try again.";
unlink($this->fileTmpLoc);
exit();
}
$this->processAndUploadPhotos($data);
// var_dump($moveResult); die();
$adapter->setDestination(dirname(__DIR__).'/testImage');
if ($adapter->receive($data['fileupload']['name'])) {
$profile->exchangeArray($form->getData());
echo 'Profile Name '.$profile->profilename.' upload ';
}
}
}
}
And the important bit
<VirtualHost *:80>
ServerName Zend
DocumentRoot "C:\Users\zend\testingZend2\public"
SetEnv APPLICATION_ENV "development"
<Directory "C:\Users\zend\testingZend2\public">
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
You can set the folder permissions using the chmod command try this command in you php script file.
if( chmod($path, 0777) ) {
move_uploaded_file($path)
}
else
echo "Couldn't do it.";
The problem is that your Virtual Host definition is giving access to "C:\Users\zend\testingZend2\public" but you are trying to store the images in a totally different folder C:\Users\test\zend\\module\guest\src\guest/pics/holdover/pic.jpg.
Not withstanding the double \\ between zend and module, you will also have to give Apache access to this other folder structure.
So you need to add another <Directory.. definition so Apache knows this site has access to the other folder structur as well as the folders it is running from.
<VirtualHost *:80>
ServerName Zend
DocumentRoot "C:\Users\zend\testingZend2\public"
SetEnv APPLICATION_ENV "development"
<Directory "C:\Users\zend\testingZend2\public">
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
</Directory>
<Directory "C:/Users/test/zend/module/guest/src/guest/pics/holdover">
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
Its normal to do this with an alias like so
<VirtualHost *:80>
ServerName Zend
DocumentRoot "C:\Users\zend\testingZend2\public"
SetEnv APPLICATION_ENV "development"
<Directory "C:\Users\zend\testingZend2\public">
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
</Directory>
Alias /pictures "C:/Users/test/zend/module/guest/src/guest/pics/holdover"
<Directory "C:/Users/test/zend/module/guest/src/guest/pics/holdover">
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
This allows you to use the alias i.e. pictures in your code rather than the full directory name.
Its also a good idea to stick to the Unix directory seperator in any files/directory information as PHP will do any necessary conversions to the DOS seperator automatically if it is running on DOS.