Skip to content

Скептична яма за идеи

и други бележки към мене си

  • начало
  • tech
  • блог
  • здраве
  • приключения
  • ядене
  • бизнес
  • деца
  • Кой?

Category: tech

Уж се занимавам с технологии от 2000, ако не и по-отдавна, но продължавам да не пиша много по въпроса. Част от нещата, които счета за нужно да бъдат документирани все пак, ще се появяват тук, били те свързани с Linux, WordPress, програмиране, компютрите като цяло или каквото и да било друго в тази посока.

[Записки] CTF – Web първи стъпки

Posted on 2023.02.25 by vloo

Бях на събитие в init Lab, което от презентация мина към конкретни упражнения върху тестови инстанции за CTF предизвикателства. Това са моите бележките от лекцията:

Tools:
-ffuf – brute force, vhosts scanning, could pass requests to burp
— quickhits – common list for content discovery
-burp suite – intercepting requests, manipulating parameters, etc. (used as a browser proxy)
-sqlmap – sql injections
-interactsh – free alternative to burp collaborator

vulnerabilities:
-bruteforce / content discovery
— unprotected content
— directory listing
— backup files
-authentication/authorisation
–IDOR – insecure direct object reference (change the value of a request parameter like user_id)
-xss => htmlspecialchars() saves the day
–DOM XSS
–reflected XSS
–cookie stealing => httponly flag is the basic protection
–phpinfo page cookie stealing
-sql inj
–addslashes()
–real_escape_string()
–prepared statements prevent it all

Posted in techTagged бележки, сигурност, уебLeave a comment

Removing language switcher from wp-login.php

Posted on 2022.01.29 by vloo

WordPress 5.9 introduced a language switcher dropdown under the login form on wp-login.php. I didn’t see that feature in the news, so I missed it for a while. I don’t need it and most of my sites that already have multilingual content don’t need it, so I had to check how I could remove it. The direct solution with a single line of code in the theme’s functions.php is this one:

//Remove language switcher from wp-login.php, introduced in WP 5.9
add_filter( 'login_display_language_dropdown', '__return_false');
Posted in techLeave a comment

Fixing a broken USB memory

Posted on 2021.12.21 by vloo

I had this one old flash card that could neither be mounted, nor be formatted, trying it both on Windows and Linux, including GParted, Disks and a few other applications in the battle. An error message I was getting every time when trying to format it was this:

Error synchronizing after initial wipe: Timed out waiting for object (udisks-error-quark, 0)

At the same time the dongle was still alive, as I could see a diode blinking upon plugging it to the computer, and lsusb listed it as a valid USB device.

Digging around I ended up trying the following command, which in effect set 0 to every bit on the flash memory:

sudo dd if=/dev/zero of=/dev/sdc

/dev/sdc is the device, corresponding to the flash memory. One of the places it could be seen is in GParted. There are better ways but I can’t be bothered to check for them right now.

The process took more than an hour for a 8Gb of space, but after that I was able to format it and start using it as if nothing happened.

Posted in techLeave a comment

A few less known tricks with WP-CLI

Posted on 2021.10.16 by vloo
  1. wp cli alias allows for the definition of aliases to be used for different WordPress instances. Checkout the docs here: https://developer.wordpress.org/cli/commands/cli/alias/
  2. The structure of the commands is WP <NOUN> <VERB> --<PARAMETERS/FLAGS> Not that this is something revolutionary new, but I haven’t thought of it earlier. Now it helps me at remembering the commands a bit.
  3. wp admin opens a browser window with the login/wp-admin screen of the current site
  4. wp <command> --prompt asks you for all the possible parameters of the command, without you knowing any of them beforehand.
  5. wp core --debug outputs any errors if you are hitting an internal server error on the site. It’s a bit faster than digging in the error log.

Thanks to https://twitter.com/DjevaLoperka for the nice talk on ZG PHP Meetup for showing me this and other cool things with the CLI.

Posted in techLeave a comment

dataLayer за Google Tag Manager

Posted on 2021.10.15 - 2021.10.15 by vloo

Стоя до късно, за да си скубя косата с абсурдно неясния изказ на едни онлайн маркетолози, които не могат грам да се оправят с изясняването на това какво точно искат да им пращам като данни към Google Tag Manager, за да си следят определените потребителски събития и да си поставят съответните метрики. В края на краищата толкова набрах, че отворих петте линка с документация, която са препоръчали, та барем разбера какво се губи в превода с тия хора и защо е толкова трудно много постен json да го коригират по начина, по който го искат.

Обобщавам по-долу това, което разбирам и научавам, четейки отново досадните документи.

dataLayer е обектът в кода, който ползваме, за да изпращаме данни на “кораба майка”. Data Layer е абстракцията, представяна от въпросния обект, която застава между сайта ни и Google Tag Manager, за да може от нея GTM да си щипка значими данни и да ги подава на всички останали проследяващи скриптове и услуги, накатерили се по клона.

Обектът dataLayer го инициализираме по следния начин (ако го нямаме от GTM скрипта или Google Optimize скрипта):

var dataLayer = window.dataLayer = window.dataLayer || [];

На някои места (включително официалната гугълска документация) се говори за дефиниране на масив от обект с данните, който се нахлузва на dataLayer променливата. Това е грешният начин, който не трябва да се ползва никога, освен ако дефинираме този масив НАД първоначалната декларация на dataLayer, защото иначе ще имаме загуба на данни.

Правилният начин е чрез ползване на push метода:

window.dataLayer.push({
    'event': 'signup',
    'userType': 'Free User'
});

По този начин, предвид че Google слухти за dataLayer.push случки, нашите добавени данни ще стигнат до въпросния Data Layer в GTM.

За да се улесни намирането и боравенето с данните в GTM, използваме променливата event като задължителен елемент от масива. С наличието на event, хората могат да си залагат свои събития в GTM, които ще се активират, когато пристигне събитие в Data Layer с избраната променлива.

Данните си ги структурираме в JSON обект, в който можем да добавяме и масиви, където е нужно, макар че някои маркетолози не се справят много с това да вадят данните от там.

– – –

Сигурно е имало и още неща, но до там са ми стигнали нервите да си запиша. Публикувам това нещо повече от половин година по-късно в състоянието, в което го заварвам като чернова.

Posted in techLeave a comment

Using uploads from production instead of downloading them to staging/local environment

Posted on 2021.07.19 - 2021.07.19 by vloo

Ха, токущо измислих хакче за спестяване на BE Media from Production разширението и решаване на проблемите при глупави билдъри, при които той не сработва (както е с Divi).

staging/wp-content/uploads/.htaccessсъс съдържание:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ https://example.com/wp-content/uploads/$1 [R=301,L]
</IfModule>

Подобен код ще трябва да напиша и за nginx…


.htaccess врътката ми не работи, ако има hotlinking защита на сървъра. Изглежда BE Media from production фалшифицира заявка от оригиналния сървър, защото той се справя точно с този сценарий.

Posted in techLeave a comment

Let Polylang user decide if a post type is translateble or not

Posted on 2021.06.16 by vloo

I had this problem with a setup of a site with Polylang and WP Job Manager – the post type for the jobs didn’t appear in the list of post types that I could decide whether to be translated or not.

Turns out WP Job Manager has a wpml-config.xml file in it’s root directory prepared for WPML compatibility. Polylang is playing smart so it’s looking for this kind of files and is interpretting them the same way as WPML would.

Editing the wpml-config.xml solved my problem, although it would be whiped by the update of the plugin. As a PoC it works and next step would be to try to override the settings through another plugin.

Posted in techLeave a comment

Automating plugin settings with WP CLI

Posted on 2021.01.18 by vloo

The approach is rather manual at first, but once done, it should allow for automating it all through using wp option update.

Here are the steps:

  1. Install a clean WP instance.
  2. Configure the plugin in interest on that instance.
  3. Check all the wp_options settings entries that were created after the plugin activation.
    1. Consider whether the plugin configuration might have changed already existing settings on the site in wp_options table, as these will have to be added to the list too.
    2. Consider whether the plugin configuration might be keeping settings or data in other database tables, so that means of automating theese will have to be “invented” too.
    3. Consider whether any of the options values should be v
  4. For each wp_options entry that has been created or changed, we should create a corresponding WP-CLI command like this:
    1. When the value is a simple string or a number: wp option update OPTION_NAME "OPTION_VALUE"
    2. When the value is a serialized object or array: wp option update OPTION_NAME 'OPTION_VALUE' --format="json"

OPTION_VALUE in 4.2. is formed by getting the actual serialized string from the database and passing it through the unserialize() function in PHP. One could use php -a (the interactive mode) for executing the followin line: ‘var_export( unserialize( ‘OPTION_VALUE’ ) );which would print a data structure, in whicharray()wrappers should be replaced by[]` in order to reach a valid JSON format.

  1. Testing each wp option update line against the test database and checking the values in the database + the plugin settings page for any issues is the final step that would verify that the commands are doing their job.
Posted in techTagged automation, wordpressLeave a comment

Overriding custom post status in WordPress

Posted on 2020.09.04 by vloo

A custom post status is initialized by the function register_post_status. Funnily enough, one can’t remove it by using a “unregister” or “deregister” function. There just ain’t one. There isn’t a filter for altering the registration of that status either. Or at least I couldn’t find one in reasonable time.

Manipulating the original status registration parameters happens in one way only, and it’s by using the same function on the same status again, but with whatever new parameters one wants it to be. The documentation of the function states that it’s…

A simple function for creating or modifying a post status based on the parameters given

Posted in techTagged custom post status, wordpressLeave a comment

[CSS] Internet Explorer specific styles

Posted on 2020.04.29 by vloo

In the past, people could prepare separate css files specifically for different IE versions like so:

<!--[if IE 8]>
<style type="text/css">
	/* css for IE 8 */
</style>
<![endif]-->

This is no longer the case, as Microsoft dropped conditional statements since IE 10. What worked for me in one ocassion for IE 11 (without affecting Edge) was using this media query:

@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
   #selector {
        /* styles that will be applied for IE only */
   }
}
Posted in techTagged css, front-endLeave a comment

Posts navigation

Older posts
Proudly powered by WordPress | Theme: micro, developed by DevriX.