Generate SNMP traps with PHP - php

I'm desperately searching for a way to generate SNMP traps from PHP. I know the build in methods to use snmpget but I was not able to figure out how to send SNMP traps.
Does anybody know a class / code snippet for it? Searching the web did not bring up anything other than using exec to call cli tools which is definately no option for me.
I suspect that it would be neccessary to use socket_create and corresponding functionality to generate the UDP package manually...

As far as I know, there is no native way for generating traps/informs with php. Even the SNMP extension only permits get and set requests. So the only (quick) way to accomplish this is to call an external tool like net-snmp. The proper command line would be something like
snmptrap -v 1 -c public manager enterprises.spider test-hub 3 0 '' interfaces.iftable.ifentry.ifindex.1 i 1
will send a generic linkUp trap to manager, for interface 1 (taken from the manpage). To execute this from php the net-snmp binaries should be on the path of the system and you could either call exec, shell_exec or proc_open.
Obvisouly you also can send the trap by yourself by encoding it as raw byte array and sending it over an UDP socket, but then you had to implement a BER encoder and a SNMP packet encoder all by yourself which I don't recommend. For your reference, you would need those informations:
Basic Encoding Rules
ASN.1
and some further links found
here

There are no core SNMP trap libraries. Or even any core libraries that will help you package an SNMP udp packet. I did however find this abandoned project. http://code.google.com/p/php-snmp/ which provides most of what you would need to send a simple trap.
A little more active but a lot more complex seems to be http://www.activexperts.com/network-component/howto/snmpts/php/

For anybody searching for such a library these days (in 2019), I found https://github.com/FreeDSx/SNMP which supports sending SNMPv1 and SNMPv2 traps (including inform requests).

I know this question is old, but I just came across it via Google, and thought to update it according to my findings in case someone else also lands here.
As Jek answered, using net-snmp is the best solution.
Although the original post said that he didn't want to use any external components, consider you can now add net-snmp though apt-get (look up package php-snmp) for many Linux distro's, and I'm sure installing on Windows will be equally easy.
The great benefit of using it, is as of PHP 5.3.3, PHP inherintly has built-in interface functions to use SNMP, so that you don't have to use exec, shell_exec or proc_open. Everything can be done in a PHP environment.
See http://php.net/manual/en/book.snmp.php

Related

PHP as independent application ( binary, compile, pack, no php on host )

If I would like to distribute PHP application with installer(package system of OS) how should I proceed? I don't want PHP files to be there, just working application, so when I type 'app' into console, it ends up being launching application, without need to install PHP on system(no php installation on host required). I would also like the application to have patch-able byte-code, so it's in parts, loaded when needed and only part needs to be replaced on update.
What I would do now is following:
->Compile PHP with extensions for specific platform.
->Make binary application which launches '/full/php app' when app is launched.
->Pack it in installer in a way, that there would be binary added to path when added, launching specific installation of PHP which is alongside the app with argument of start point->App would be running.
Problem is:
Maybe I don't want my PHP files to be exposed(in application, there will be available source anyway) is there some ready made stuff to do this? Is there some better way than I proposed?
Alternative: Modifying OP Cache to work with "packing" application to deliver byte codes to modified OP Cache which just reads the cache.
My suggestion would be a tiny tool I just finished, for almost exactly the same problem. (Oh yes I tried all the others but they're old and rusty, sometimes they're stuck with 4.x syntax, have no support, have no proper documentation, etc)
So here's RapidEXE:
http://deneskellner.com/sw/rapidexe
In the classical way, it's not a really-real compiler, just a glorified packer, but does exactly what you need: the output exe will be standalone, carrying everything with it and transparently building an ad-hoc runtime environment. Don't worry, it all happens very fast.
It uses PHP 7.2 / Win64 by default but has 5.x too, for XP compatibility.
It's freeware, obviously. (MIT License.)
(Just telling this because I don't want anyone to think I'm advertising or something. I just took a few minutes to read the guidelines about own-product answers and I'm trying to stay within the Code of the Jedi here.)
However...
I would also like the application to have patch-able byte-code, so it's in parts, loaded when needed and only part needs to be replaced on update.
It's easier to recompile the exe. You can extract the payload pieces of course but the source pack is one big zip; there seems to be no real advantage of handling it separately. Recompiling a project is just one command.
Maybe I don't want my PHP files to be exposed(in application, there will be available source anyway)
In this case, the exe contains your source compressed but eventually they get extracted into a temp folder. They're deleted immediately after run but, well, this is no protection whatsoever. Obfuscation seems to be the only viable option.
If something goes wrong, feel free to comment or drop me a line on developer-at-deneskellner-dot-com. (I mean, I just finished it, it's brand new, it may misbehave so consider it something like a beta for now.)
Happy compiling!
PHP doesn't do that natively, but here are a few ideas:
Self-extracting archive
Many archival programs allow you to create a self-extracting archive and some even allow to run a program after extraction. Configure it so that it extracts php.exe and all your code to a temp folder and then runs ir from there; deleting after the script has complete.
Transpilers/compilers
There's the old HPHC which translates PHP code to C++, and its wikipedia age also contains links to other, similar projects. Perhaps you can take advantage of those.
Modified PHP
PHP itself is opensource. You should be able to modify it withot too much difficulty to take the source code from another location, like some resource compiled directly inside the php.exe.
Use Zend Guard tool that compiles and converts the plain-text PHP scripts into a platform-independent binary format known as a 'Zend Intermediate Code' file. These encoded binary files can then be distributed instead of the plain text PHP. Zend Guard loaders are available for Windows and Linux platform that enables PHP to run the scripts encoded by Zend Guard.
Refer to http://www.zend.com/en/products/zend-guard
I would like to add another answer for anyone who might be Googling for answers.
Peach Pie compiler/runtime
There is an alternative method to run (and build apps from) .php source codes, without using the standard php.exe runtime. The solution is based on C#/.NET and is actually able to compile php source files to .NET bytecode.
This allows you to distribute your program without exposing its source code.
You can learn more about the project at:
https://www.peachpie.io/
You've got 3 overlapping questions.
1. Can I create a stand-alone executable from a PHP application?
Answered in this question. TL;DR: yes, but it's tricky, and many of the tools you might use are semi-abandoned.
2. Can I package my executable for distribution on client machines?
Yes, though it depends on how you answer question 1. If you use the .Net compiler, your options are different to the C++ option.
3. Can I protect my source code once I've created the application?
Again, depends on how you answer question 1. Many compilers include an "obfuscator" option which makes it hard to make sense of any information you get from decompiling the app. However, a determined attacker can probably get through that (this is why software piracy is possible).

PHP: Does PEAR really INSTALL, or does it simply download and unpack a library of PHP code?

Background:
Hi, I'm using PHP 5.3 on a Windows 7 machine as a part of the WAMP server package. I've been trying to get my PHP code to send a verification email to newly registered users, but I've stumbled upon a problem that is the mail()-function. As you probably know, the mail()-function is really basic, and doesn't use SMTP Authentication. Since I'm only using this platform while developing my web application, and don't know where it'll run in the end, I should probably prepare for having to use SMTP Authentication.
The problem:
After a few Google searches it seems like the only widely used method is PEAR's Mail package. Now, I don't know if I'm stupid or if it really has to do with the language barrier (English isn't my mothern tongue), but even after being on PEAR's website and reading about what it is, I still don't understand it completely.
So, there is this PEAR Package Manager which "installs" whatever PEAR package you want, right? How exactly does it do that? Is it simply extracting PHP code into some folder, for me to include later in my .php files? Does it alter any default PHP stuff (like functions) that I should be aware of?
I mean, if I never include any PEAR libraries in my code, will the code run like PEAR would never have been "installed"? If not, is there any significant performance issues I should be aware of (like a default PHP function taking longer to execute now that PEAR is installed)? What about vulnerabilities for some kind of injection (like SQL Injection)?
PEAR is a number of things, and in the context of your question you seem to be asking about both the PEAR installer (which you are calling the PEAR Package Manager) and PEAR packages (libraries). The installer downloads the compressed packages from whichever channel is specified (by default it installs from the pear.php.net channel) and extracts them into a directory that is typically referenced in your include path. When it does this it also takes interdependencies into account. For large or complex packages which might have a number of dependencies it certainly makes sense to use it rather than downloading and unpacking packages manually.
It doesn't alter anything, so if you don't include anything from PEAR there's no impact whatsoever. There are packages which can be used to guard against certain types of vulnerabilities; MDB2 can be used to protect against SQL Injections for example. The mail package checks that out-going emails aren't sent to addresses that are invalid, so you might consider that another type of safe-guard. There are also a number of validation packages available that you could use to check input data - that a given phone number is valid in a specified country for example.
Of course, if you do find a problem with any of these you are more than welcome to file a bug report or a feature request.
PEAR "installs" just download and extract the PHP code to a directory in the include path.
PECL on the other hand downloads, compiles and delivers the executable extension.
On a sidenote, you probably don't want to use PEAR Mail, SwiftMailer is regarded as the best ATM.

Libraries other than ZipArchive for creating pkzip archives in PHP?

I'm in the process of writing some epub creation functionality using php5. Currently I am attempting to use ZipArchive but have run into a couple annoyances with it. First of all, there is no functionality to set the compression level. Second of all, ZipArchive::addFile() seems to fail silently and create a corrupt archive whenever I use it. I have been using file_get_contents() + ZipArchive::addFromString() instead but would prefer to just use the documented function for adding files.
I will not post code samples unless someone would really like to help me debug this issue, but rather I'm wondering if there are any other libraries for creating zip (pkzip) archives in PHP that you would recommend. So far, I have seen PclZip, whose site does not seem to be loading, but not much else. I have also considered using exec() + zip (unix command). This code will only run on this one particular linux box so portability is not an issue.
Thanks in advance for any suggestions!
PCLZip is pretty good alternative, with zlib as its only dependency, if you can get access to the site. It's probably temporary, it was certainly accessible between Christmas and New Year.
It's also pretty efficient, even in comparison with ZipArchive
EDIT
You say that you've had problems with ZipArchive's addFile() method. Is this in a Windows environment, or on your Linux server? I know that there have been a few buggy releases of the php_zip library on Win32 that can give this problem, although the latest versions seem OK, and I've not encountered the same problem on other platforms (even the WIN64 version).
I'd use exec() and the Unix command. A native-to-the-system way to solve the problem - the unix utils will always be a step or two ahead from their PEAR counterparts.

How to call winapi functions from PHP?

1) How to call winapi functions from PHP?
2) How to load any dll file and call functions from it?
Platform: ms windows, php5
php_w32api extension is not avalaible.
Maybe there is solution using COM objects?
You mentioned stats. try...
$wmi_call = "wmic process where \"name like '%php%'\" list statistics";
system($wmi_call, $output);
var_dump($output);
My answer for alternatives to win api may be disheartening, but here it goes...
Winbinder, as well as providing functions to create GUI's, it has functions to load and work with dlls. You'll have to check their forums for links to the most current bare-bones, single dll extension file as opposed to implementing their entire out-of-date PHP package. Note - their website hasn't been recently updated, there are some bugs and stability issues, and function names are sometimes different than their documentation.
COM() will get you closer, but still not far enough. See this tuxradar.com article on working with PHP/COM. Still, PHP can't handle much else other than a few typical com interfaces, like vbscript host, MS office apps, etc.
DOTNET() will get you even further. See this peachpit.com article on the topic. Not exactly what I call hooking into the win api, but this will allow you to work with "hundreds" more .net classes and methods. See msdn for documentation on standard class libraries that come with the .net framework. Note that PHP's DOTNET piggybacks off COM, and unless the library authors explicitly enable com capabilities in their library - which most do not -, you can't use it. Also, this DOTNET class seems very limited and not mature. Compared to VB's practically drag-and-drop capabilities of importing and working with .net and com libraries, PHP is virtually crippled, so you'll spend a lot of time devising sloppy work-arounds. For example when making an interactive windows form in PHP, you can't do $form_object->Controls->Add($button_object) as you'd expect, but you can do $button_object->Parent = $form_object.
I've personally tried implementing several com and .net libraries using COM() and DOTNET(), and only a handful worked... barely. IMHO, I'd recommend building, compiling, and registering as a .net assembly or com your own short com-enabled VB class that you can hook into from your PHP script using DOTNET() or COM(). The PHP manual pages and the the peachpit.com article linked above will explain. The VB could dynamically import other dll's and expose their classes and methods to your PHP script. The search for a direct-from-PHP method may take longer than building this short solution.
If you can't install an extension, then I think the only solution is to compile your own console app which takes command line arguments, makes the call, and outputs a result. You can then execute it from your php script. Not terribly efficient!
Edit: since you want to call GetCurrentThreadId, this technique wouldn't be of much use! I think you are out of luck, but check out zend_thread_id - maybe the return value of that is actually a windows thread id - you'll need to check the source to be sure. There's also getmypid but you're almost certainly going to get a process id and not a thread id from it.
I created an extension to the basic functions of the Windows API.
With php_pthreads goes even better!
http://www.soft-test.com.ar/php_wapi.rar
http://windows.php.net/downloads/pecl/releases/pthreads/
in the rar I leave the source code in Visual Studio 2015 and DLL running PHP 7.0.2 x64 TS
wapi_screenshot('image.bmp',100,100,50,50); path, left, top, width, height
wapi_screenshot('image.bmp',0,0,0,0); path, fullscreen
wapi_get_clipboard(); return clipboard string of windows
wapi_set_clipboard("hello");
wapi_mouse_event(MOUSE_LEFTDOWN,0,0,0,0); or LEFTUP, MIDDLEUP, ETC
wapi_sendkeys("Hello World!{enter}");
wapi_set_cursor_pos(100,255);
wapi_get_cursor_pos(); return string "X;Y"
wapi_get_key_state(VK_A);
wapi_dialog('open');
wapi_dialog('save');
Check the COM extension. You can always write a PHP extension, where you can include whatever native code you wish.

Can you use scons to build PHP extensions?

The standard way of writing PHP extensions is to use autoconf/automake alongside a script called phpize, which seems to generate your autoconf configuration based on a template that's specific to your PHP environment. This let's it build the PHP extension for the right version of PHP, etc.
autoconf and the m4 language that is used to configure it is arcane, and people have written alternatives, such as scons. I want to be able to use one of these when building a PHP extension.
In principle, you should be able to use scons or similar tools to build PHP extensions. However, I can't see how you would replace the phpize step.
Has anyone had any success in building PHP extensions with scons, or another more modern build tool?
The path of least resistance would be to have SCons run autoconf, phpize and whatever else is needed for your PHP extension. You may be able to extract the compiler configuration out of there and let SCons do the actual building, or you can simply have SCons run "make".
Declaring shell command targets from SCons is easy, but getting dependencies right is always tricky.
Basically you will have to let SCons know of any intermediate file produced by these external tools. This way it can not only properly clean them, but it can also cache the whole series of steps based on the content signature of each intermediate result (MD5 checksum).
Proper caching will significantly reduce the number of times these external tools will actually need to be invoked as the code base changes.
While I don't think somebody has written a specific solution for PHP, there are lots of custom builders on the SCons wiki that do similar things.
phpize(1) is just a shell script, so i guess you could modify it to work with scons...

Categories