Laravel capturing foreign url on $request->fullURL() function - php

So I have a middleware that captures requests in/out. Here's the middleware code
public function handle($request, Closure $next)
{
$logger = "[" . $request->ip() . "]" . $request->method() . " => " . $request->fullUrl() . " [" . Carbon::now()->format("H:i:s") . "]; \nUser-Agent:" . $request->userAgent();
log_routes($logger);
return $next($request);
}
public function terminate($request, $response)
{
$logger = "[" . $request->ip() . "]" . $request->method() . " <= " . $request->fullUrl() . " [" . Carbon::now()->format("H:i:s") . "]; \nUser-Agent:" . $request->userAgent();
log_routes($logger);
}
normally this middleware output
[IP address]GET <= https://i-assume-this-should-be-my-url.com/endpoint [07:58:13];
User-Agent:User-Agent App-Version:app version
[IP address]GET => https://i-assume-this-should-be-my-url.com/endpoint [07:58:13];
User-Agent:User-Agent App-Version:app version
But somehow I don't know why it outputs foreign URL like this
[92.118.160.1]GET <= https://foreign-url.xyz [08:12:39];
User-Agent:NetSystemsResearch studies the availability of various services across the internet. Our website is netsystemsresearch.com App-Version:Not Filled
[92.118.160.1]GET => https://foreign-url.xyz [08:12:39];
User-Agent:NetSystemsResearch studies the availability of various services across the internet. Our website is netsystemsresearch.com App-Version:Not Filled
And another thing I'm really confused about is I use Cloudflare's firewall to block the incoming request if the User-Agent provided doesn't match with what I already defined. But this strange log shows there's the incoming request with unmatch user agent and can pass that firewall
Any help and explanation would be appreciated. Thank you so much

Related

What is the scope of error_get_last() in PHP?

I've been using error_get_last() in combination with register_shutdown_function() to create an error report for some of my scripts. It's been working fine for the most part.
Every now and then, though, the error report will show an error from a different script.
I'm not quite sure how that can happen. Can anyone explain?
I'm wondering if error_get_last() in one script should be able to show errors from different scripts and if that's the case, under what circumstances would that happen?
My only guess is that the error is saved for a short time so that a script that finishes execution at almost the same time might catch another script's errors. Could that be it?
This is the code I use and have included in many different PHP files:
function send_error_report($extra) {
global $conn;
$base_url = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 'https' : 'http' ) . '://' . $_SERVER['HTTP_HOST'];
$url = $base_url . $_SERVER["REQUEST_URI"];
$error = error_get_last();
if (isset($error)) {
$error_str = "Type: " . $error['type'] . " | Message: " . $error['message'] . " | File: " . $error['file'] . " | Line: " . $error['line'];
$sql = "INSERT INTO `error_report` (`script`, `error`) VALUES ('$url', '" . $error_str . " - " . $extra . "');";
$conn->query($sql);
}
}
register_shutdown_function('send_error_report', '');

Braintree Webhook Methods

I'm fetching a Webhook that is coming from Braintree. The Webhook is return a success and also creates the log file. This is the code I'm using:
if( isset($_POST["bt_signature"]) && isset($_POST["bt_payload"])){
$webhookNotification = \Braintree_WebhookNotification::parse(
$_POST["bt_signature"], $_POST["bt_payload"]
);
$message = "[Webhook Received "
. $webhookNotification->timestamp->format('Y-m-d H:i:s') . "] "
. "Kind: " . $webhookNotification->kind . " | "
. "Payment ID: " . $webhookNotification->localPaymentCompleted->paymentId . "\n";
file_put_contents("/tmp/webhook.log", $message, FILE_APPEND);
// if everything went fine, send confirmation to the buyer
$this->artikelRepository->sendConfirmationAction(null, $webhookNotification->localPaymentCompleted->paymentId);
}
To confirm the payment I need the paymentId of the local payment. I tried with various methods, but this should work: $webhookNotification->localPaymentCompleted->paymentId according to the test file.
The log file returns this, though:
How am I able to retrieve the Payment ID of a local payment inside the webhook function?
Update: I just noticed that we used a totally outdated SDK. The functions we tried to use were not even added in the old version.

PHP - URL gets malformed during redirect

So, I have an image link that has this href:
http://www.app.com/link?target=www.target.com&param1=abc&param2=xyz
This is processed like so (I use laravel):
function out (Request $request) {
$url = $request->target;
$qs = $request->except('target');
if ( !empty($qs) ) {
$url .= strpos($url, '?') !== false ? '&' : '?';
$url .= http_build_query($qs);
}
return redirect($url);
}
Most of the time, this works. However, lately, we've been experiencing an issue where param1 and param2 are attached to the URL in a seemingly infinite loop causing us to hit a 414 Request URI too long Error.
The problem is that it happens so randomly that I really don't know where to check because I added a checker before the return statement.
if ( substr_count($url, 'param1') > 1 ) {
$file = storage_path() . '/logs/logger.log';
$log = "[ " . date("d-m-Y H:i:sa") . " ] [ {$request->ip()} ] - {$url} \n";
file_put_contents($file, $log, FILE_APPEND);
}
And it hasn't logged a single hit. Even after our testers experienced the bug.
Is it possible that the receiving application is breaking the URL somehow?
What information should I be looking out for? Have you seen an issue like this before?
Is it the http_build_query that could be causing this and that my checker just doesn't work as expected (though, I did test it and it logged my test URL).
Any help on the matter would be great.
Assuming and issue with http_build_query:
Well, one attempt you may try is to rewrite the code without $request->except and http_build_query.
If you don't have any special reason to use http_build_query i would suggest to use $request->input.
Example with $request->input:
function out (Request $request) {
$url = $request->target;
$param1 = $request->input('param1', '');
$param2 = $request->input('param2', '');
if (!empty($param1) || !empty($param2)) {
$url .= '?';
}
if (!empty($param1) && !empty($param2)) {
$url .= 'param1=' . $param1 . '&param2=' . $param2;
} else {
$url .= !empty($param1) 'param1=' . $param1 : '';
$url .= !empty($param2) 'param2=' . $param2 : '';
}
return redirect($url);
}
The solution is a little bit more verbose but with that, you should be sure 100% that is not the code to generate the redundancy.
Absurd, remote possibility:
The second thing I would try is to check you log system. For instance if you are running under apache you should have a file called access.log under /var/log/apache2/ (or under /var/log/nginx/ with nginx).
In there you should have the history of all your http requests.
Maybe there is a chance that some of the wired requests with multiple params are from a strange IP address.
If this is the case, it means that some company is monitoring and testing the website (potentially with the strange parameters) for security reasons.
If this is the case, I guess you are under http and you should switch to https.
Anyway, with the new code, you should be sure about the code and be able to investigate any other part of the system.

Undefined Variable in Laravel Command

I have added into a Laravel command mail::send to send an email to all users who meet the criteria. Whenever I run the first part of my foreach statement but gives me an [ErrorException] Undefined Variable: member whenever it gets to the emailing. My fire function code is below.
public function fire()
{
$members = Member::where('expire', '=', Carbon::now()->today());
$this->info('We found ' . $members->count() . ' expiring today (' . Carbon::now()->today() . ')!');
foreach ($members->get() as $member) {
$member->active = "0";
$member->save();
$this->comment($member->first_name . ' has been updated.'); //This is the last line which runs
Mail::send('emails.member.membership_expired', array('name'=>$member->first_name. ' ' . $member->last_name), function($message){
$message->to($member->email, $member->first_name . ' ' . $member->last_name)->subject('Your Membership has Expired');
});
}
}
With Mail::send you use a closure (also called anonymous function). To use local variables inside the closure you have to pass them in with use. Like that:
Mail::send('emails.member.membership_expired',
array('name'=>$member->first_name. ' ' . $member->last_name),
function($message) use ($member){
$message->to($member->email, $member->first_name . ' ' . $member->last_name)->subject('Your Membership has Expired');
}
);

Inserting Events to google calendar from a script

Anyone know the proper way to authenticate and publish directly to a calendar without relying on a currently logged in user? Several weeks ago I built a calendar that used the standard Oauth 2.0 protocol but this relied sessions stored by a user's we browser. I have one calendar that I want to pass events to from an application I am writing with a basic PHP framework. I'm more concerned with what are the best practices that others are using. Your answer could be simply, don't do it. Thanks alot.
Use OAuth 2 and the Authorization Code flow (web server flow), with offline enabled. Store the refresh tokens (which last indefinitely until the user has revoked), and you'll be able to upload events to Google Calendar even when the user isn't currently logged in.
More info:
https://developers.google.com/accounts/docs/OAuth2WebServer#offline
try Zend_Gdata_Calendar with this library you are able to insert or get events from any user(with the right username and password obviously) from google calendar and integrate with your own calendar or display it..here a short example:
$service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient('gmail#user.com', 'gmailpassword', $service);
$service = new Zend_Gdata_Calendar($client);
$query = $service->newEventQuery();
$query->setUser('default');
$query->setVisibility('private');
try {
$eventFeed = $service->getCalendarEventFeed($query);
} catch (Zend_Gdata_App_Exception $e) {
echo "Error: " . $e->getMessage();
}
echo "<ul>";
foreach ($eventFeed as $event) {
echo "<li>" . $event->title . " (Event ID: " . $event->id . ")</li>";
}
echo "</ul>";
$eventURL = "http://www.google.com/calendar/feeds/default/private/full/Dir0FthEpUbl1cGma1lCalendAr";
try {
$event = $service->getCalendarEventEntry($eventURL);
echo 'Evento: ' . $event->getTitle() .'<br>';
echo 'detalles: ' . $event->getContent().'<br>';
foreach ($event->getWhen() as $dato)
{
echo 'inicia: ' . substr($dato->startTime, 0,-19) . ' a las: ' . substr($dato->startTime, 11,-10) .'<br>';
echo 'termina: ' .substr($dato->endTime,0,-19) . ' a las: ' . substr($dato->endTime,11,-10) .'<br>';
}
} catch (Zend_Gdata_App_Exception $e) {
echo "Error: " . $e->getMessage();
}
with this you can add, update, edit or delete events from calendar form any user with mail and password...

Categories