mercredi 11 avril 2012

Securiser son Prestashop, joomla, oscommerce : le htaccess

Bien.
Abordons ce jour la sécurité d'un site ouebe.
Avec LE fichier à ne pas négliger : le .htaccess


Quelque soit le CMS que vous allez utiliser, il y a fort à parier qu'il aura déjà son propre modèle de htaccess, ne serait-ce que pour définir les règles de ré-écriture d'URL.


Je vous propose ici de la compléter pour boucher quelques failles de sécurité.


Commencons par registers globals sur off (empecher les variables d'etre auto-déclarées)





php_value register_globals OFF
// ou - renseignez-vous auprès de votre hébergeur ou sur google
SetEnv REGISTER_GLOBALS 0


A partir de maintenant, il va falloir que RewriteEngine soit sur On

Donc, bien vérifier la présence de "RewriteEngine On" dans votre htaccess

1ere chose, une des plus efficaces : empêcher les attaques "skiddy". des scripts faits pour attaquer les CMS, grosso modo..

Liste assez exhaustive de tous les méchants robots :

http://www.bg-pro.com/?goto=badbot



###FILTRE CONTRE ROBOTS DES PIRATES ET ASPIRATEURS DE SITE WEB

RewriteCond %{REQUEST_URI} !^robots.txt
RewriteCond %{REQUEST_URI} !^sitemap.xml

RewriteCond %{HTTP_USER_AGENT} ^-?$ [OR] ## ANONYMES
RewriteCond %{HTTP_USER_AGENT} ^[bcdfghjklmnpqrstvwxz\ ]{8,}|^[0-9a-z]{15,}|^[0-9A-Za-z]{19,}|^[A-Za-z]{3,}\ [a-z]{4,}\ [a-z]{4,} [OR] ## CEUX QUI INVENTENT DES NOMS AU HASARD 
RewriteCond %{HTTP_USER_AGENT} 2icommerce|@nonymouse|Accoona|ActiveTouristBot|adressendeutschland|ADSARobot|Advanced\ Email\ Extractor|agent|ah-ha|aipbot|aktuelles|Alexibot|Alligator|AllSubmitter|almaden|amzn_assoc|anarchie|anonymous|Apexoo|Aqua_Products|Art-Online|ASPSeek|ASSORT|asterias|ATHENS|AtHome|Atomz|attach|autoemailspider|autohttp|BackDoorBot|BackWeb|Badass|Baiduspider|Bandit|BatchFTP|bdfetch|BecomeBot|berts|big.brother|Bitacle|Biz360|Black.Hole|BlackWidow|bladder\ fusion|BlogPeople|blogsearchbot-martin|Blogshares\ Spiders|Blog\ Checker|Bloodhound|BlowFish|bmclient|Board\ Bot|Bookmark\ search\ tool|Boston\ Project|BotALot|BotRightHere|Bot\ mailto:craftbot@yahoo.com|BravoBrian\ SpiderEngine\ MarcoPolo|Bropwers|Browsezilla|BuiltBotTough|Bullseye|bumblebee|BunnySlippers|c-spider|capture|Cegbfeieh|CFNetwork|charlotte/|CheeseBot|CherryPicker|ChinaClaw|CICC|clipping|compatible\ \;|Convera|Copernic|CopyRightCheck|cosmos|Crescent|Crescent\ Internet|Custo|cyberalert|Cyberz|DataCha0s|Daum|Deweb|diagem|Digger|Digimarc [NC,OR] ## VRAIS ET FAUX ROBOTS 
RewriteCond %{HTTP_USER_AGENT} digout4uagent|DIIbot|DirectUpdate|disco|DISCoFinder|DittoSpyder|DnloadMage|Download|Downloader|Download\ Accelerator|Download\ Demon|Download\ Wonder|dragonfly|DreamPassport|Drip|DSurf|DSurf15a|DTS.Agent|DTS\ Agent|dumbot|DynaWeb|e-collector|EasyDL|EBrowse|eCatch|echo\ extense|ecollector|edgeio|efp@gmx\.net|EirGrabber|EmailCollector|EmailSiphon|EmailWolf|Email\ Extractor|Email\ Siphon|EmeraldShield|Enterprise_Search|EroCrawler|ESurf|Eval|Everest-Vulcan|Exabot|Express\ WebPictures|Extractor|ExtractorPro|EyeNetIE|FairAd|fastlwspider|FavOrg|Favorites\ Sweeper|fetch|FEZhead|FileHound|findlinks|Flaming\ AttackBot|flashget|FlickBot|fluffy|Foobot|Forex|Franklin\ Locator|FreshDownload|frontpage|FSurf|Gaisbot|GalaxyBot|Gamespy_Arcade|Generic|genieBot|GetBot|Getleft|GetRight|GetSmart|GetWeb!|GetWebPage|gigabaz|Girafabot|Go!Zilla|go-ahead-got-it|GOFORITBOT|GornKer|Grabber|GrabNet|Grafula|Green\ Research|grub-client|grub\ crawler|hanzoweb|Harvest|Hatena\ Antenna|heritrix|hhjhj@yahoo|hloader|HMView|holmes [NC,OR] ## VRAIS ET FAUX ROBOTS 
RewriteCond %{HTTP_USER_AGENT} HomePageSearch|HooWWWer|HouxouCrawler|HTTPConnect|httpdown|HTTPGet|HTTPRetriever|http\ generic|HTTrack|humanlinks|ia_archive|IBM_Planetwide|iCCrawler|ichiro|id-search|IDBot|iGetter|imagefetch|Image\ Stripper|Image\ Sucker|imds_monitor|IncyWincy|Industry\ Program|Indy\ Library|InetURL|InfoNaviRobot|informant|Ingelin|InstallShield\ DigitalWizard|InterGET|InternetLinkAgent|InternetSeer\.com|Internet\ Ninja|IPiumBot|Iria|IRLbot|Iron33|Irvine|ISSpider|IUPUI\ Research\ Bot|Jakarta\ Commons|JBH*Agent|JBH\ Agent|JennyBot|JetCar|JetCar|jeteye|jeteyebot|JoBo|JOC\ Web\ Spider|JustView|Kapere|Kenjin|Keyword\ Density|KRetrieve|ksoap|KWebGet|Lachesis|LapozzBot|larbin|LeechFTP|leipzig.de|LexiBot|lftp|LightningDownload|likse|Link*Sleuth|LinkextractorPro|Linkie|LinkScan|LINKS\ ARoMATIZED|linktiger|LinkWalker|lmcrawler|LNSpiderguy|LocalcomBot|looksmart|Mac\ Finder|Mag-Net|Magnet|Mail\ Sweeper|mark.blonin|MaSagool|Mass\ Downloader|Mata\ Hari|MCspider|MetaProducts\ Download\ Express [NC,OR] ## VRAIS ET FAUX ROBOTS 
RewriteCond %{HTTP_USER_AGENT} Microsoft\ Data|Microsoft\ Data\ Access|Microsoft\ URL|Microsoft\ URL\ Control|MIDown|MIDown\ tool|MIIxpc|minibot\(NaverRobot\)|Mirror|Missauga|Missigua|Missouri\ College\ Browse|Mister|Mister\ PiX|MJ12bot|mkdb|MMMtoCrawl\/UrlDispatcherLLL|moget|Monster|Moozilla|Moreoverbot|mothra/netscan|MovableType|Movable\ Type|Mozi!|Mozilla/22|Mozilla/3.0\ \(compatible\)|Mozilla/5.0\ \(compatible\;\ MSIE\ 5.0\)|MSIECrawler|MSIE_6.0|MSProxy|multithreaddb|Murzillo|MVAClient|MyFamilyBot|MyGetRight|nameprotect|NASA\ Search|nationaldirectory|Naver|Navroad|NearSite|NetAnts|netattache|NetCarta|NetMechanic|netprospector|NetResearchServer|NetSpider|NetZIP|NetZippy|NetZip\ Downloader|Net\ Vampire|NEWT|Nextopia|nicerspro|NimbleCrawler|ninja|noxtrumbot|NPBot|Nutch|Nutscrape/|Octopus|Offline\ Explorer|Offline\ Navigator|OK\ Mozilla|OmniExplorer|OpaL|OpaL|Openbot|Openfind|OpenTextSiteCrawler|Oracle\ Ultra\ Search|OrangeBot|PackRat|PageGrabber|PagmIEDownload|panscient|Papa\ Foto|Papa\ Foto|pavuk|pcBrowser|PerMan [NC,OR] ## VRAIS ET FAUX ROBOTS 
RewriteCond %{HTTP_USER_AGENT} PersonaPilot|PHP\ version|PingALink|PlantyNet_WebRobot|playstarmusic|Plucker|Pockey|Port\ Huron|Program\ Shareware|Progressive\ Download|ProPowerBot|prospector|ProWebWalker|Proxy|Prozilla|psbot|PSurf|psycheclone|puf|Pump|PushSite|PussyCat|PuxaRapido|PycURL|QRVA|QuepasaCreep|QueryN|Radiation|RealDownload|Reaper|Recorder|RedCarpet|RedKernel|ReGet|relevantnoise|replacer|RepoMonkey|RMA|Robozilla|Rover|RPT-HTTPClient|RTG30|Rufus|SAPO|SBIder|scooter|ScoutAbout|script|SearchExpress|searchhippo|searchpreview|searchterms|Second\ Street\ Research|Seekbot|Seeker|Serious|Shai|shelob|Shim-Crawler|SickleBot|sitecheck|SiteMapper|SiteSnagger|Slurpy\ Verifier|SlySearch|SlySearch|SmartDownload|sna-|snagger|So-net|sogou|sootle|SpaceBison|SpankBot|spanner|SpeedDownload|Spegla|Sphere|Sphider|SpiderBot|sproose|Sqworm|SQ\ Webscanner|Stamina|Stanford|Star\ Downloader|Stripper|studybot|sucker|SuperBot|SuperHTTP|Surfbot|SurfWalker|SurveyBot|suzuran|Szukacz|tAkeOut|TALWinHttpClient|tarspider|Teleport|Teleport\ Pro [NC,OR] ## VRAIS ET FAUX ROBOTS
RewriteCond %{HTTP_USER_AGENT} Telesoft|Templeton|TestBED|TheNomad|The\ Intraformant|TightTwatBot|Titan|toCrawl/UrlDispatcher|TrackBack|TrueRobot|True_Robot|Turing|TurnitinBot|TV33_Mercator|Twisted\ PageGetter|UCmore|UdmSearch|UIowaCrawler|UMBC|UniversalFeedParser|URLGetFile|URLy\ Warning|URL\ Control|URL_Spider_Pro|UtilMind|Vacuum|vagabondo|vayala|visibilitygap|vobsub|VoidEYE|VoilaBot|voyager|vspider|W3CRobot|w3mir|Web\ Image\ Collector|Web2WAP|WebaltBot|WebAuto|webbandit|WebCapture|Webclipping|webcollage|webcollector|WebCopier|WebCopy|webcraft@bea|webdevil|webdownloader|Webdup|WebEMailExtrac.*|WebEnhancer|WebFetch|WebFilter|WebFountain|WebGo|WebHook|Webinator|WebLeacher|WEBMASTERS|WebmasterWorldForumBot|WebMiner|WebMirror|webmole|WebReaper|WebSauger|WEBsaver|Website|Website\ eXtractor|Website\ Quester|WebSnake|Webster|WebStripper|websucker|webvac|webwalk|webweasel|WebWhacker|WebZip|Web\ Data\ Extractor|Web\ Downloader|Web\ Image\ Collector|Web\ Sucker|web\.by\.mail|Wells\ Search|WEP\ Search\ 00 [NC,OR] ## VRAIS ET FAUX ROBOTS 
RewriteCond %{HTTP_USER_AGENT} WeRelateBot|whizbang|WhosTalking|Widow|Widows|Wildsoft\ Surfer|WinHttpRequest|WinHTTrack|WISEbot|WISEnutbot|WUMPUS|Wweb|WWW-Collector|WWWOFFLE|wwwster|Wysigot|x-Tractor|Xaldon|Xenu\'s|Xenus|XGET|Y!TunnelPro|YaDirectBot|YahooYSMcm|Yandex|Yeti|Zade|ZBot|zerxbot|Zeus|Zeus.*Webster|ZyBorg|^adwords|^Internet\ Explorer|^Mozilla$|^MSIE|^puf|^user|^User-Agent:\ |^User\ Agent:\ |^
Liste trop longue ? On va juste filter les plus utiliser, alors, si vous rpéférez :



##
RewriteCond %{HTTP_USER_AGENT} ^-?$ [OR] ## ANONYMES
RewriteCond %{HTTP_USER_AGENT} ^[bcdfghjklmnpqrstvwxz\ ]{8,}|^[0-9a-z]{15,}|^[0-9A-Za-z]{19,}|^[A-Za-z]{3,}\ [a-z]{4,}\ [a-z]{4,} [OR] ## CEUX QUI INVENTENT DES NOMS AU HASARD 
RewriteCond %{HTTP_USER_AGENT} ^

On va bloquer du XSS et à toute une série de failles potentielles désormais : on va bloquer les test de faille de votre site.


###  XSS, REDIRECTIONS HTTP, base64_encode, VARIABLE PHP GLOBALS VIA URL, MODIFIER VARIABLE _REQUEST VIA URL, TEST FAILLE PHP, INJECTION SQL

RewriteCond %{REQUEST_METHOD} (GET|POST) [NC]
RewriteCond %{QUERY_STRING} ^(.*)(%3C|<)/?script(.*)$ [NC,OR]
RewriteCond %{QUERY_STRING} ^(.*)(%3D|=)?javascript(%3A|:)(.*)$ [NC,OR]
RewriteCond %{QUERY_STRING} ^(.*)document\.location\.href(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)(%3D|=)http(%3A|:)(/|%2F){2}(.*)$ [NC,OR] 
RewriteCond %{QUERY_STRING} ^(.*)base64_encode(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)GLOBALS(=|[|%[0-9A-Z]{0,2})(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)_REQUEST(=|[|%[0-9A-Z]{0,2})(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)(SELECT\+|UNION+ALL|INSERT\+|DELETE\+|CHAR\(|UPDATE\+|REPLACE\+|LIMIT\+)(.*)$ [NC]
RewriteRule (.*) - [F]

Si les pirates ont malgré tout réussi a traverser tout cela, on va limiter leur possibilité d'action :

RewriteCond %{REQUEST_URI} .*((php|my)?shell|remview.*|phpremoteview.*|sshphp.*|pcom|nstview.*|c99|r57|webadmin.*|phpget.*|phpwriter.*|fileditor.*|locus7.*|storm7.*)\.(p?s?x?htm?l?|txt|aspx?|cfml?|cgi|pl|php[3-9]{0,1}|jsp?|sql|xml) [NC,OR]
RewriteCond %{REQUEST_METHOD} (GET|POST) [NC]

RewriteCond %{QUERY_STRING} ^command=.*&output.*$ [OR]
RewriteCond %{QUERY_STRING} ^nts_[a-z0-9_]{0,10}=.*$ [OR]
RewriteCond %{QUERY_STRING} ^c=(t|setup|codes)$ [OR]
RewriteCond %{QUERY_STRING} ^act=((about|cmd|selfremove|chbd|trojan|backc|massbrowsersploit|exploits|grablogins|upload.*)|((chmod|f)&f=.*))$ [OR]
RewriteCond %{QUERY_STRING} ^act=(ls|search|fsbuff|encoder|tools|processes|ftpquickbrute|security|sql|eval|update|feedback|cmd|gofile|mkfile)&d=.*$ [OR]
RewriteCond %{QUERY_STRING} ^&?c=(l?v?i?&d=|v&fnot=|setup&ref=|l&r=|d&d=|tree&d|t&d=|e&d=|i&d=|codes|md5crack).*$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)([-_a-z]{1,15})=(ls|cd|cat|rm|mv|vim|chmod|chdir|concat|mkdir|rmdir|pwd|clear|whoami|uname|tar|zip|unzip|tar|gzip|gunzip|grep|more|ln|umask|telnet|ssh|ftp|head|tail|which|mkmode|touch|logname|edit_file|search_text|find_text|php_eval|download_file|ftp_file_down|ftp_file_up|ftp_brute|mail_file|mysql|mysql_dump|db_query)([^a-zA-Z0-9].+)*$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)(wget|shell_exec|passthru|system|exec|popen|proc_open)(.*)$
RewriteRule (.*) - [F]

Ben là, on est pas trop mal.

Quelques conseils élémentaires par dessus :
les fichier en chmod 404
les dossiers en chmod 505

Ca devrait vous protéger contre pas mal d'attaques...

Commentaires et compléments bienvenus !!

mercredi 4 avril 2012

Prestashop : rendre sa boutique privée

Objetctif :
 rendre la boutique uniquement accessible via login et mot de passe.
En clair, si je ne suis pas loggé ou que je n'ai pas de compte, je ne vois pas les produits : par défaut, la page est la page d'authentification.

Solution :
Le class "patron" au début d'un prestashop, c'est le frontController.
Donc, fatalement, c'est là que l'on va ajouter une ch'tite ligne de code.

classes/FrontController

Tiens ? Une fonction init (ligne 70) !! donc, ce serait cette fonction qui gère le 1er affichage d'un prestashop ?
Voyons cela !
juste avant la balise } de fermeture de la fonction init (ligne 329 chez moi), on va rajouter ces quelques lignes :

/* RENDRE LA BOUTIQUE ACCESSIBLE UNIQUEMENT SI LOGGE */
 if(!$cookie->logged AND $page_name!='authentication' AND $page_name!='password')
{
 header('Location:./authentication.php?back=index.php');
 

Ah ben oui, c'était bien là...
:)

Bon, histoire de pas etre trop restricitf, j'autorise les pages authentification et oubli de password...vous pouvez rajouter d'autres pages en rajoutant des "    AND $page_name!='nomdelapage'    " dans le if

mardi 3 avril 2012

Plesk 9 : mise à jour version php 5.1.6 --> 5.2 ou 5.3

Ons e connecte en root sur le serveur via putty

On vire cette saloperie de sqlite2 qui fout sa zonse :
yum remove php-sqlite2


On récupère la mise à jour de php
wget -q -O - http://www.atomicorp.com/installers/atomic.sh | sh


On met à jour le PHP
yum update php


Et on redemarre le service
/etc/init.d/httpd restart    
ou
 service httpd restart


Article sera complété plus tard par une procédure plus complète

lundi 2 avril 2012

prestashop 1.4.X : imposer des commande par lot de quantité

La problématique du jour :
- Faire en sorte qu'un produit se commande par colisage imposés : par 2,4,6,8,10....
Donc, interdire, pour ce genre de produit, une commande de 3.

L'astuce :
Utiliser le champ "minimal_quantity" et un peu les maths, aussi...

Procédure
1- Le champ minimal_quantity devient le controleur des palliers de commande : on ne peut commander le produit que par multiple du minimum de Quantité minimale
Donc, dans la fiche du produit, on n'oublie pas de renseigner ce champ...

2- dans votre theme : product.js
On modifie la fonction
function checkMinimalQuantity

if ($('#quantity_wanted').val() < minimal_quantity)
devient
if ($('#quantity_wanted').val() % minimal_quantity !=0)

Oui, on utilise les modulos (caractère % en php) , qui affichent le reste d'une division. (pour faire simple, hein)


3- le controller du panier, histoire de bloquer ce pallier de commande partout, meme dans la page panier
fonction preProcess() du CartController (qui commence ligne 84 dans une verison 1.4.7)

ligne 176
après
 if (!sizeof($this->errors))
{


/* MODIF COMMANDE PAR LOT */
if ($add AND $qty >= 0)
{
if ((int)$idProductAttribute)
                        $minimal_quantity = Attribute::getAttributeMinimalQty((int)$idProductAttribute);
                     else
                        $minimal_quantity = $producToAdd->minimal_quantity;                

                     if ($qty % $minimal_quantity != 0)
                     {
                        $this->errors[] = Tools::displayError('Veuillez respecter le colisage ');
                     }
 
    /* FIN MODIF COMMANDE PAR LOTS */

Ensuite, le code se poursuit par

/* Product addition to the cart */
if (!isset(self::$cart->id) OR !self::$cart->id)
{
etc...

Voila !


jeudi 29 mars 2012

Prestashop et kimsufi - petits soucis de droits

Bon, un serveur dédié, c'est super.
Mais ca fait du SSH.
Et des problèmes de droits

Alors, il se peut que vous ayez déjà rencontré ce soucis en voulant uploader une image produit ou le logo de votre boutique :
move_uploaded_file() [function.move-uploaded-file]: SAFE MODE Restriction in effect. The script whose uid is 10001 is not allowed to access /tmp/PSiD5TQF owned by uid  48

Bon, les UID, ça dépend de vos paramétrages utilisateurs sous SSH

Et bien sur, z'y comprenez rien, vous voulez pas regrouper des droits utilsiateurs, toussa toussa..

Rapide analyse du message d'erreur : le dossier tmp pose problème.
Lequel ?
Celui qui est à la racine du dossier "img"
Paf, on le passe en 777.
Méthode punk ? Oui. Efficace ? Oui, également...

En prod, pensez juste à tout re-vérouiller en 755...


mercredi 28 mars 2012

Une class différentes pour chaque catégorie

Ma problématique :
personnaliser le listing produit suivant la catégorie prestashop que je visite

la soluce :
Une catégorie, ce n'est finalement..qu'une ID.
Donc, je vais récupérer l'ID de la catégorie, pour la rajouter en définition de class CSS

{if isset($smarty.get.id_category)} class="category_{$smarty.get.id_category|intval}"{/if}

Et ça, selon le template que vous aurez choisi, dans la feuille de style css qui gère l'affichage du tpl product-list.tpl

Enjoy !

Exemple concret :
Theme prestashop matrice
Personnalisation de l'affichage du prix dans la liste produits pour la catégorie ID 4

modif css
global.css
rajout d'une ligne apr_s 952 :
#center_column .categorie_product  span.pp_4 {width:75px;margin-top:5px;padding-top:15px;padding-bottom:19px;padding-left:25px;padding-right:25px;color:#ffffff;height:30px;background: url("../img/4.png") no-repeat}

modif product-list.tpl
Ligne 65

remplacer 



             {if !$priceDisplay}{convertPrice price=$product.price}{else}{convertPrice price=$product.price_tax_exc}{/if}
         
par 




             {if !$priceDisplay}{convertPrice price=$product.price}{else}{convertPrice price=$product.price_tax_exc}{/if}



lundi 19 mars 2012

Prestashop - changer l'ordre des prix dégressifs

Un truc qui m'a toujours semblé bizarre sous prestashop, template de base :
quantity_discounts
les prix dégressifs vont de la quantité la plus élevée à la plus faible

La logique voudrait que ce soit de la plus petite quantité à la plus haute

Bon.
On va donc aller faire un tour dans Class/SpecificPrice.php
function getQuantityDiscounts
line 196

On change DESC par ASC

Ohhh !! c'est le bon ordre ! De la plus petite quantité à la plus haute