Showing posts with label Security. Show all posts
Showing posts with label Security. Show all posts

Saturday, October 22, 2022

Build Custom AWS Config rules using Guard DSL

I want to use AWS config to report S3 buckets without public blocking enabled except for some buckets with prefix like www, there is a AWS managed rule which can achieve this with a limitation: the excluded buckets must be provided as exact names separated by comma, regex match is not supported.

 

Previously, to create a custom rule, you would have to define an AWS Lambda function, from June 2022, you can author AWS Config custom rules using Guard DSL without needing to develop AWS Lambda functions.

 

What is Guard DSL?

Guard DSL is open-source policy-as-code domain-specific language (DSL) to write rules and validate JSON- and YAML-formatted data such as CloudFormation Templates, K8s configurations, and Terraform JSON plans/configurations against those rules. It is language developed by CloudFormation Guard project.

 Ignore the word CloudFormation here, Guard DSL is mainly used for validating CloudFormation template, but in the AWS config context, it has nothing to do with CloudFormation.

 

Get started with Guard DSL

Learn Guard DSL syntax

Ignore all object reference name from above document, the names are CloudFormation Objects. For the purpose of AWS config, refer to aws-config-resource-schema 

Sample AWS Config Rule with Guard DSL.

Create AWS Config Rule->Create custom rule using Guard

Scope of changes ->Resource Type(S3 Buckets)

Rule Content: 

rule s3_bucket_is_public when
    resourceType == "AWS::S3::Bucket" configuration.name != /^www/ {
        supplementaryConfiguration.PublicAccessBlockConfiguration.blockPublicPolicy exists
        supplementaryConfiguration.PublicAccessBlockConfiguration.blockPublicAcls exists
        supplementaryConfiguration.PublicAccessBlockConfiguration.restrictPublicBuckets exists
        supplementaryConfiguration.PublicAccessBlockConfiguration.ignorePublicAcls exists
    }

rule s3_bucket_not_public when
    s3_bucket_is_public {
    supplementaryConfiguration.PublicAccessBlockConfiguration {
        blockPublicAcls == true
        blockPublicPolicy == true
        restrictPublicBuckets == true
        ignorePublicAcls == true
    }
}
The rules are evaluated in order, evaluation continues regardless the result of previous rule.
PublicAccessBlockConfiguration block  has  conditions separated by new line, which implies AND
Please note the first rule name is being used as condition in the second rule

- when bucket with www prefix is being evaluated, the result is not_applicable for both conditions.
- when bucket with public blocking enabled is being evaluated, the result is compliant for both conditions
- when bucket without public blocking enabled is being evaluated, 1st rule result is not_compliant, 2nd rule result is not_applicable. effective result is not_compliant

Saturday, February 11, 2012

Enable timestamp logging in bash commands history

Bash has the built-in feature to support timestamp in history command , but it is not enabled by default in Red Hat Linux(ksh doesn’t have the feature at all)
It is recommended to tune two environment variables for history command to tighten audit.
1.Enable timestamp in command history
2.Increase the default  history file size
Enable timestamp in command history
Just need to set HISTTIMEFORMAT env variable, e.g.  HISTTIMEFORMAT="[%F %T %Z] "
The time format is the same as that of date command.
Increase the default history file size
There are two environment variables  for history size.
HISTSIZE: How many lines to keep in memory for current bash session, commands in current session are appended to ~/.bash_history on quitting.
HISTFILESIZE: How many lines to keep in history file ~/.bash_history
Both HISTSIZE and HISTFILESIZE seem to be 1000 by default, HISTSIZE=1000 is ok for current session, but HISTFILESIZE=1000 is too small to log enough commands for any past login session.
Both environment variables  are to be enabled for all users,  they can be put in global profile /etc/profile , but user defined global profile in /etc/profile.d/ is a better option.
For example, create a user global profile in /etc/profile.d
$cat /etc/profile.d/user.sh 
HISTSIZE=1000
HISTFILESIZE=40000
HISTTIMEFORMAT="[%F %T %Z] "
export HISTSIZE HISTFILESIZE HISTTIMEFORMAT
#With timestamp enabled, the history command output looks like this
$history 
19  [2012-02-03 13:41:56 EST] history
20  [2012-02-03 13:42:58 EST] date
22  [2012-02-03 13:42:55 EST] pwd

You may notice that the commands was not sorted by the time order, it is because, even “pwd” was executed  before date, but  it is was in different session and the “pwd session” was terminated after the “date session”, so the “pwd” command was appended after “date”.

To view all 40000 lines in ~/.bash_history for tracing very old commands, you need to temporarily increase HISTSIZE to 40000 before run “history”.  You can set the default HISTSIZE is 4000, but it takes too long to process for history command used in daily basis.

Other useful history related commands

#clear commands history in current session 
$history -c
#disable logging history commands
$set +o history 
#enable logging history commands
$set –o history 
#fc (fix command) 
#open last 4 commands in an editor and re-execute them after closing the editor
#it is useful if you need to re-execute more than one command
$fc -4 -1

Thursday, April 21, 2011

Setup Postfix SMTP password authentication with SASL

Simple Authentication and Security Layer(SASL) is a framework for authentication and data security in Internet protocols.
Postfix can relay the SASL framework to provide SMTP password authentication.
SMTP password authentication is suitable for roaming users who are outside of trusted network. They are still allowed to send email without relaxing SMTP restrictions , which could introduce spam emails. 
Postfix version 2.3 onwards  supports two SASL implementations(This post will discuss cryus)
[Centos 5.5 ] $ postconf -a
cyrus
dovecot 
SASL Mechanisms
- SASL mechanisms: DIGEST-MD5 CRAM-MD5 use encrypted password , but they are only supported in saslauthd mechanism:sasldb,sql,ldapdb
cyrus-sasl-md5 package provides library for DIGEST-MD5 CRAM-MD5
- SASL mechanisms: PLAIN LOGIN use clear  text password,  it is supported saslauthd mechanism: pam, but the clear text can be protected by TLS
cyrus-sasl-plain package provides library for  PLAIN LOGIN
NOTE:
  - This post only discuss SASL    PLAIN LOGIN    in saslauthd    PAM
  - make sure  you already have a basic working Postfix before continue next steps
1. Install and configure  saslauthd
$rpm -qa | grep sas
cyrus-sasl-2.1.22-5.el5_4.3
cyrus-sasl-plain-2.1.22-5.el5_4.3                
cyrus-sasl-lib-2.1.22-5.el5_4.3
#saslauthd should be configured to use pam mechanism 
$ grep MECH /etc/sysconfig/saslauthd
MECH=pam
#start /etc/init.dd/saslauthd and test it
#smtp is service name /etc/pam.d/smtp
$testsaslauthd -u guest01 -p Pass001  -s smtp
0: OK "Success."
2. Enable SASL in postfix
$cat /etc/postfix/main.cf
smtpd_sasl_auth_enable = yes
broken_sasl_auth_clients = yes
smtp_sasl_security_options = noanonymous
smtpd_recipient_restrictions =   permit_mynetworks,permit_sasl_authenticated,reject_unauth_destination
3.Restart postfix and test the authentication
#First test:  telnet to check if   PLAIN LOGIN   is shown
$(echo "ehlo localhost"; sleep 2; echo "quit") | telnet localhost 25
250-AUTH PLAIN LOGIN DIGEST-MD5 CRAM-MD5
## you can limit  mechanism  type 
$cat /usr/lib64/sasl2/smtpd.conf
pwcheck_method: saslauthd
mech_list: plain login
#Second test: test username and password by converting them to base64
$ printf  "\0guest01\0Pass001" |openssl base64
AGd1ZXN0MDEAUGFzczAwMQ==
$ (echo "AUTH PLAIN AGd1ZXN0MDEAUGFzczAwMQ=="; sleep 2 )| telnet localhost 25
Trying 127.0.0.1...
Connected to localhost (127.0.0.1).
Escape character is '^]'.
220 mail.example.com ESMTP Postfix
235 2.0.0 Authentication successful
Connection closed by foreign host.
4. Enable TLS (Optional) to protect clear text password in PLAIN LOGIN
$cat /etc/postfix/main.cf
smtpd_use_tls = yes
smtpd_tls_CAfile =  /etc/postfix/certs/ca.pem
smtpd_tls_cert_file = /etc/postfix/certs/postfix.pem
smtpd_tls_key_file = /etc/postfix/certs/postfix.key
smtpd_tls_loglevel = 1

Saturday, April 2, 2011

Authenticate BIND zone transfer with TSIG key

TSIG (Transaction SIGnature) can provide authentication and data integrity for DNS zone transfer and Dynamic DNS (DDNS ) update, but  it CAN'T provide encryption, the data still sent in clear text , just integrity checks detects data modification by middle-man.
The common practice to restrict  BIND zone transfer is IP access-list, since IP can be easily forged, authenticating  zone transfer  by shared secret: TSIG key is more secure than IP method. Unfortunately, BIND, as of 9.3.6, can't support  combination of both methods, only TSIG key  is effective when both methods applied.
Generating TSIG key:
TSIG key is encoded in BASE64, any BASE64  tool can create TSIG key.
# [1] BIND dns-keygen utility
$ dns-keygen
5TyOwB1gbs4wpYKDeGKHvA5sfBPR6L4ItQpavUXGSaTnD9xMdlb5hciBlEvV
# [2] openssl base64 encoding tool
$echo $(date) | openssl base64
U2F0IEFwciAyIDE1OjU5OjQwIEVTVCAyMDExCg==
# [3]  BIND dnssec-keygen utility, it is mainly used for secure DNS, so generating TSIG key a bit complex, but you can define key s
$dnssec-keygen -a HMAC-MD5 -b 256 -n HOST transfer
Ktransfer.+157+39609
$ cat Ktransfer.+157+39609.private
Private-key-format: v1.2
Algorithm: 157 (HMAC_MD5)
Key: BMSri735ohiGYK4qT1Ursh7se8vnx2ltjajRGsJ6x/w=
Configure named.conf
Generate TSIG key with the method of your choice, then paste the key string to a file, which is NOT world-wide readable, then embedding  the key file to named.conf

##Master DNS Server
##Key name is arbitrary, but must be same in both peers
$ cat /var/named/chroot/etc/transfer.key
key "HOST1-HOST2" {
algorithm       hmac-md5;
secret          "1B+FL8t42RXx+mELfUYkEg==";
};
$cat /var/named/chroot/etc/named.conf
include "/etc/transfer.key";
$cat /var/named/chroot/etc/named-my.zones
zone "myexample.com" IN {
type master;
file "myexample.zone";
allow-transfer { keys “HOST1-HOST2” ;};   // Can't restrict IP and  use key at the same time
};
## Slave DNS Server
##Key name is arbitrary, but must be same in both peers
$ cat /var/named/chroot/etc/transfer.key
key "HOST1-HOST2" {
algorithm       hmac-md5;
secret          "1B+FL8t42RXx+mELfUYkEg==";
};
$ cat /var/named/chroot/etc/named.conf
include "/etc/transfer.key";
server 172.16.1.1  { keys "HOST1-HOST2" ;};  // Tell Master DNS server 172.16.1.1 to use the TSIG  key
$cat /var/named/chroot/etc/named-my.zones
zone "myexample.com" IN {
type slave;
masters { 172.16.1.1 ;};
file "slaves/myexample.zone";
};

TSIG Limitations:- difficult to manage TSIG keys in large scale
- only provides security to next-hop peer
- don't provide data encryption
- BIND,as of 9.3.6, can't provide additional level security such as IP access-list on top of  TSIG key

Wednesday, October 14, 2009

Deny ssh interactive login but allow sftp

SSH interactive login need tty to be allocated but sftp/scp doesn't need tty. So you can disable SSH interactive login by no-pty option in OPENSSH. But no-pty option is valid only in public key authentication, so you have to disable password for the user with “passwd –l username” command.

I have attempted to use pam_listfile.so tty option to achieve this, I found it is impossible because pam_tty name ssh will be allocated in either ssh login or sftp.

All you need to is to put no-pty parameter in ~/.ssh/authorized_keys, it must be in the same line with the public key, multiple options are separated by comma e.g


no-pty,no-X11-forwarding ssh-dss AAAAB3Nz ... key-comment

Another useful feature of public key authentication is forced command, which means the command is invoked whenever the key is authenticated, it is great security feature for remote execution e.g backup job. you can also limit client source with "from= " option.


#Force to run command date only
$ cat /home/test/.ssh/authorized_keys
command="date" ssh-dss AAAAB3NzaC1kc3 ..

#date command was executed even given command is ls
$ ssh test@localhost ls
Wed Oct 14 10:29:39 EST 2009

#forced command can literally disable SSH interactive login.
$ ssh test@localhost
Wed Oct 14 10:29:44 EST 2009
Connection to localhost closed.