Jenkins API Access Denied - php

I'm trying to connect my WordPress website to my jobs Jenkins via the Jenkins API. Even if I saw a lot of posts and tried them I still don't manage to make my Jenkins API working.
So I have a Jenkins running in http://localhost:9090 with the job Test.
I configured the HTTP proxy of Jenkins at proxy:8080 with my username and password. When I validate the proxy in Jenkins, it's a success.
Jenkins tells me as well that my token was never used.
Now about my API, I have:
function getLastBuildStatus($url, $jobName, $username, $api_token){
$password = 'xxxxx';
$ch = initCurl($username, $api_token); //see function downside
curl_setopt($ch, CURLOPT_URL, $url . '/job/' . $jobName . '/lastBuild/api/json');
curl_setopt($ch, CURLOPT_PROXY, 'http://proxy:8080');
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
$result = executeCurl($ch);
$json = json_decode($result);
var_dump ($result);
if($json){
return $json->result;
}
else {
return -1;
}
function initCurl($username, $api_token){
$ch = curl_init();
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false );
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $api_token);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
return $ch;
}
With or without proxy I have an Access Denied error. Am I missing something?
Edit 1
I've add in the httpd.conf rules for the Jenkins proxy reverse. Still the same error but probably something to look deeper..
ProxyPass / http://localhost:9090/ nocanon
ProxyPassReverse / http://localhost:9090/
ProxyRequests Off
AllowEncodedSlashes NoDecode
<Proxy http://localhost:9090/*>
Order deny,allow
Allow from all
</Proxy>
Edit 2
OK! So I could make it work via command line. When I enter that command, I can access the data:
curl -v --noproxy localhost, http://localhost:9090/job/Test/api/json --user username:token
I don't get why because when I put curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false); in my PHP file, I still get the 403 error.
However, when I put curl_setopt($ch, CURLOPT_PROXY, '');, I get a Error:Failed to connect to localhost port 9090: Connection refused

Related

WAMP : PHP Curl "working" but returning empty string, file_get_contents is working

I am running PHP Wampserver 3.2.6 under Windows 11 with Avast Antirus Free edition.
And PHP Version 8.1.0.
Now I have setup a simple curl script to fetch data from a remote host. But this returns nothing.
When I put the entire thing online on a server it works just fine. But from a local machine it doesn't work.
I have tried running the entire thing under postman. And there it works just fine.
private function __curl($url, $decode = true){
// * create curl resource
$ch = curl_init();
// * set url
curl_setopt($ch, CURLOPT_URL, $this->api_url.$url);
// * return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// * set headers
$headers = array('X-IM-API-KEY: '.$this->api_key);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, true);
// * if any postdata set
if(!empty($this->postdata)){
// * initialize post
$this->__post();
// * set postdata
curl_setopt($ch, CURLOPT_POST, count($this->postdata));
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->postfieldstr);
}
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
// * if no decode
if(!$decode) return $output;
// * return result
return json_decode($output, true);
}
When I just use file_get_contents it works fine.
file_get_contents($this->api_url.$url);
The result :
{"success":false,"error":true,"message":"fields
missing","data":{"email":"not set","password":"not
set","app_version":"1.1"}}
Of course it will give an error because it expects POST parameters with the username and password.
I have the following configuration visible under PHPinfo :
I hope someone can tell me what my mistake would be.
EDIT
When I add :
curl_error($ch);
I get the following error :
SSL certificate problem: unable to get local issuer certificate
But when viewing the address in FireFox I get no error at all.
(letscrypt)
EDIT : Answer added by : #codenathan
Adding the following code to disable host and peer verification does the trick actually.
I think in combination with the local firewall the letscrypt certificate simply didn't get through in the way it was supposed to.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
Since I need this for developement purposes this actually does the trick for me.
curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0);
However it is not ideal to switch this off : https://www.saotn.org/dont-turn-off-curlopt_ssl_verifypeer-fix-php-configuration/

Curl working on localhost but not working on server

so here is my problem ... I have a php-curl function that sends a POST Request to an API with a file as a parameter.
My Code is working perfectly fine on the localhost and its not working on my server.
Server Details
- Dedicated VPS windows server 2012
- Installed PHP 5.5 and MySQL 5.5 and phpmyadmin
- Curl is enabled ... && tried a simple curl function and its working fine
My app
- My Code is working perfectly fine on localhost but its not working on the server (i tried multiple servers with multiple specs)
$localFile=$_FILES['file_c']['tmp_name'];
$curl = curl_init($url);
if ((version_compare(PHP_VERSION, '5.5') >= 0)) {
$data = array(
'version' => '2017-01-20',
'file' => new CURLFile($localFile),
'config'=> '{"conversion_target":"normalized_html"}'
);
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
}else{
$data = array(
'version' => '2017-01-20',
'file' => "#".$localFile,
'config'=> '{"conversion_target":"normalized_html"}'
);
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
}
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Insert the data
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
// Send the request
if(!curl_exec($curl)){
die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}else{ //do something else}
so this piece of code works fine on localhost but on the server it shoots a 500 internal server error
no errors in server logs
I've traced every single line in that code it breaks at the curl execution line
Please help
Thanks!

Unable to access Flask web app from php curl

I have a Flask app, with a basic function, where I have exposed app.run() to a public ip, so that it is accessible from an external server;[ using Flask - Externally Visible Dev Server ]
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run(host = '0.0.0.0', port = 8080)
The curl request I have written in my php code is:
$signed_url = "http://my-ip-address:8080/";
$ch = curl_init($signed_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data= curl_exec($ch);
echo $data;
I can do a curl request :
curl http://my-ip-address:8080/
from command line. However, when the curl request is embedded within my PHP code, it gives me an error "Connection refused".
Kindly help!
If the PHP code is on another server, but your command line cURL request is on the same server, then you aren't comparing apples to apples.
Two things that might be wrong:
Your Flask server has a firewall that doesn't allow external connections.
You are connecting using an private network IP address rather than a public IP address.
For now your PHP code looks correct, so I would narrow down the problem a little bit. Ignore that PHP code and try to connect using cURL on the command line from the same server you are running your PHP code on.
try to set your port with curl options like this:
curl_setopt($ch, CURLOPT_PORT, 8080);
so your signed url will be:
$signed_url = "http://my-ip-address";
I use this code for my work and worked :)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost:5000/spmi/api/1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"teks_analysis\":\"tidak ada skor nol\"}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
the key is CURLOPT_POSTFIELDS

cURL on wamp not working

I'm using a php client written by a company for accessing their web service.
The client is very comprehensive and includes classes that get populated from XML responses that the web service endpoint generates.
when I run it on a proper web server, it works. But, when I use it locally with wamp it's throwing an error that no data was received.
I've already checked all around StackOverflow, I usually find answers to my questions but this one has drived me crazy!
here is the httpPost function (written as part of the php client they provide):
private function _httpPost(array $parameters)
{
$query = $this->_getParametersAsString($parameters);
$url = parse_url ($this->_config['ServiceURL']);
$scheme = '';
switch ($url['scheme']) {
case 'https':
$scheme = 'https://';
$port = $port === null ? 443 : $port;
break;
default:
$scheme = '';
$port = $port === null ? 80 : $port;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $scheme . $url['host'] . $url['path']);
curl_setopt($ch, CURLOPT_PORT, $port);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_USERAGENT, $this->_config['UserAgent']);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($_config['ProxyHost'] != null && $_config['ProxyPort'] != -1)
{
curl_setopt($ch, CURLOPT_PROXY, $_config['ProxyHost'] . ':' . $_config['ProxyPort']);
}
$response = "";
$response = curl_exec($ch);
$response = str_replace("HTTP/1.1 100 Continue\r\n\r\n", "", $response);
curl_close($ch);
list($other, $responseBody) = explode("\r\n\r\n", $response, 2);
$other = preg_split("/\r\n|\n|\r/", $other);
list($protocol, $code, $text) = explode(' ', trim(array_shift($other)), 3);
return array ('Status' => (int)$code, 'ResponseBody' => $responseBody);
}
By the way, my curl extension is active and I even made a simple test to fetch google.com with success.
My guess is that it's related to the VERIFYPEER option you have on, usually curl on wamp isn't configured by default to support it (CA certificate bundle), So by default it'll reject all SSL certificates as unverifiable.
try to replace it with (only when testing on your localhost, you want this to be ON when using a server):
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
good luck.
EDIT:
This is taken from curl's "Details on Server SSL Certificates":
If the remote server uses a self-signed certificate, if you don't
install a CA cert bundle, if the server uses a certificate signed by a
CA that isn't included in the bundle you use or if the remote host is
an impostor impersonating your favorite site, and you want to transfer
files from this server, do one of the following:
1) Tell libcurl to not verify the peer. With libcurl you disable this
with curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, FALSE); With
the curl command line tool, you disable this with -k/--insecure.
2) Get a CA certificate that can verify the remote server and use the proper option to point out this CA cert for verification when
connecting. For libcurl hackers: curl_easy_setopt(curl,
CURLOPT_CAPATH, capath); With the curl command line tool: --cacert
[file]
Shay, you are right, the issues is because CA cert bundle is not available in Windows distribution of WAMP.
To fix the issue without disabling ssl verification (which is not secure and not recommended for production)
download CA bundle. For example from official crul site: http://curl.haxx.se/ca/cacert.pem save to c:/wamp
open php.ini inside your apache. in my case: c:\wamp\bin\apache\apache2.4.9\bin\php.ini
set curl.cainfo="c:/wamp/cacert.pem"
restart Apache
Done)

cUrl error: "Couldn't resolve host 'search.twitter.com' "

When trying to connect to the Twitter api using cUrl and PHP, I get the following error:
Couldn't resolve host 'search.twitter.com'
Before it worked fine, and the request works in my browser. When trying to connect to example.com, I do get the page. I've also tried the following code, with which I get the same error:
$_h = curl_init();curl_setopt($_h, CURLOPT_HEADER, 1);
curl_setopt($_h, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($_h, CURLOPT_HTTPGET, 1);
curl_setopt($_h, CURLOPT_URL, 'http://www.example.com' );
curl_setopt($_h, CURLOPT_DNS_USE_GLOBAL_CACHE, false );
curl_setopt($_h, CURLOPT_DNS_CACHE_TIMEOUT, 2 );
var_dump(curl_exec($_h));
var_dump(curl_getinfo($_h));
var_dump(curl_error($_h));
Could this be a DNS issue? Are there any other options for fetching JSON data with PHP?
EDIT: This is the code that got an error initially:
$json_url = "https://search.twitter.com/search.json?q=" . 'bitterrific' . "&rpp=10&result_type=all";
$ch = curl_init();
$timeout = 100;
curl_setopt($ch,CURLOPT_URL,$json_url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
//curl_close($ch);
$content = json_decode($data);
$output = array();
echo "DATA: ".curl_error($ch);
Thanks!
I didn't found a problem with your code.
Also search.twitter.com works:
$ host search.twitter.com
search.twitter.com is an alias for s.twitter.com.
s.twitter.com has address 199.59.148.11
s.twitter.com has address 199.59.149.243
s.twitter.com has address 199.59.148.84
You should check your server's DNS settings.
You also ask for other ways to fetch json data with PHP. PHP accepts urls to be used as remote files. So you could try something like:
$content = file_get_contents("https://search.twitter.com/search.json?q=" . 'bitterrific' . "&rpp=10&result_type=all");
$content = json_decode($content);
var_dump($content);
Try adding a second nameserver to /etc/resolv.conf
eg: nameserver 8.8.8.8
which is the google nameserver
I found the same issue in using codebird.php. I was getting a timeout.
Our nameserver worked, but it seemed to timeout once in a while. When I added the second name server, the issue went away.

Categories